0

I got this interview question I think is impossible.

If you have an array and you must in place remove all unique elements from it in place while keeping the order and with no extra memory.

E.g.

input = [1,1,2,3,4,3,4]
output = [1,1,3,4,3,4]

I tried, sorting, but you have to keep the items in place.

Two pointers, which are O(n^2) and counters which use extra memory but those weren't efficient enough.

Maybe something with bit flips?

hemloc.io
  • 1
  • 1
  • 3
    O(n) means linear, so you can pass two or three times (maybe more) through the array, don't you agree? – davidbuzatto Feb 17 '22 at 00:10
  • Yep fully agree, but without the ability to save state across the iterations I'm not sure how helpful that is, e.g. one pass to build a data structure to help us keep count and then another pass to remove would work fine if we could keep extra memory. There's no restrictions on the size of the int either so we can't use a constant count lol. – hemloc.io Feb 17 '22 at 00:13
  • Unless there's a constraint on valid elements (e.g. must be positive), you can't do anything with flipping bits because you transform one valid element into another valid element. – Eric J. Feb 17 '22 at 00:15
  • Related. https://afteracademy.com/blog/remove-duplicates-from-an-unsorted-array – Eric J. Feb 17 '22 at 00:18
  • Mm there's also this which I found which is the same minus the efficiency constraints. https://stackoverflow.com/questions/26870699/delete-unique-elements-from-a-list – hemloc.io Feb 17 '22 at 00:32
  • The question is a bit under specified. ‘No extra memory’ is impossible, so ‘constant extra memory’ is the more common assumption. The range of integers allowed and the size (in bits) of array storage is crucial. If all the elements are sufficiently smaller than the maximum allowed by the integer type, you can build your own hash set in the high bits of each array element to get O(n). – kcsquared Feb 17 '22 at 00:49
  • Woah didn't think of that, I don't think that was the answer, but that's wicked clever haha. Changed title to O(1) extra memory for clarity – hemloc.io Feb 17 '22 at 00:57
  • There is no constraint on the range of each array element? – Abhinav Mathur Feb 17 '22 at 10:09
  • I don't think the problem is well-enough specified to be answerable. It's almost certainly impossible without tricks of using spare bits in the input array, or if the values in the array are constrained somehow. – Paul Hankin Feb 17 '22 at 10:48
  • Hmmm yeah I was thinking the same thing. I think my interviewer maybe have misremembered the answer or question. – hemloc.io Feb 18 '22 at 13:57

0 Answers0