Given an array of integers. If the number a and its negation -a both present in the array then print it. ex:if {10, 5, 0, 9, -10, 7, -5} is given then print 10, 5. I gave the interviewer O(N) time and O(N) Space complexity code based on HashMap but he further asked me to reduce the space complexity to O(1) in the worst-case keeping time complexity O(N). Note: Counting sort was not allowed. Please, can anyone provide me the O(1) space complexity approach?
Asked
Active
Viewed 201 times
3
-
Add a tag to specify what language you want your answer in. Also add the solution that you have. – jmargolisvt Sep 28 '19 at 14:50
-
2Don't think it is possible – Ninja420 Sep 28 '19 at 15:15
-
If the numbers are small, you can use a bitmask to keep track of the items. – Willem Van Onsem Sep 28 '19 at 15:50
-
Do the negative values always appear last? – Willem Van Onsem Sep 28 '19 at 18:23
-
Is using a binary trie of positive numbers a solution? – nice_dev Sep 28 '19 at 19:44
-
@vivek_23 how is a binary trie for N elements O(1) space? – גלעד ברקן Sep 28 '19 at 19:53
-
Well, the max depth of the tree would just be 31 for integer range elements. Also, the trie is only going to be for positive numbers. When we come across negative elements, we could take absolute value of it and check for its existence in the trie. – nice_dev Sep 28 '19 at 20:01
-
@vivek_23 what about the trie's width? How does the trie identify N items in O(1) space? [As far as I can tell](http://opendatastructures.org/ods-java/13_1_BinaryTrie_digital_sea.html), space complexity of a binary trie is `O(n*w)`. – גלעד ברקן Sep 28 '19 at 20:20
-
@גלעדברקן Trie's width totally depends upon the arrangement of the numbers. Height shouldn't go more than 31 for integer range elements. Anyway, not sure if interviewer had any solution, or was it just a trick question. – nice_dev Sep 30 '19 at 09:28
-
@vivek_23 Again: how is "height 1" of a trie "the same" as getting to O(1) space? – GhostCat Sep 30 '19 at 09:31
-
@GhostCat Because the height would never go beyond 31 for integers regardless of the size of the array. Not sure about width as I haven't implemented yet, but just a rough idea. – nice_dev Sep 30 '19 at 09:36
-
Maybe the recruiter wanted you to push back that such solution is feasible and explain why? – Andrey Taptunov Sep 30 '19 at 09:55
1 Answers
3
This is not possible in O(n)
time and O(1)
space if the array elements are unordered and are within an arbitrary range. If the array is sorted, we can solve it within those constraints using two pointers.

גלעד ברקן
- 23,602
- 3
- 25
- 61
-
-
@HarshulAgarwal great. Let's hear his solution, as well as clear input parameters as to ordering and range. – גלעד ברקן Mar 07 '20 at 17:40