Recently I was given the following task:
Suppose you're given an array of elements of length N where every element except for two special, which appears once, occurs exactly twice. Find this special numbers.
I also know that every element in array is non-negative and is not more than 10^9 and the length of the array, N is less than or equal to 10^6
I think that the solution is using xors. Here is my thoughts:
Let's xor all elements in array. Since xor is commutative, e.g. xor(a, b)=xor(b, a), we can conclude that all elements which occurs twice will be zeroed:
xor(a, b, a, c)=xor(a, a, b, c)=xor(xor(a, a), b, c)=xor(0, b, c)=xor(b, c)
And then xoring whole array we'll get the xor of our two special elements. What to do next? Maybe, some other solutions?
P.S. Please, don't tell me anything about hash tables. Firstly, I've tried it, but it didn't work, since my hash functions were not able to compress all range of numbers into array with any reasonable size(for my machine at least). Secondly, it is prohibited by task's condition.
EDIT: My bad, I didn't mention that sorted is also prohibited.