Is it possible to design an algorithm that uses constant space for the following function?
Input: non-negative integers; every integer appears twice, except one that appears only once.
Output: The integer that appears exactly once.
Details and Assumptions: Assume that storing each integer takes constant amount of space regardless of the number of bits in the integer.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
The solution to this problem relies on the properties of ⊕ (XOR).
We know that ⊕ gives a zero whenever both operands are equal. a ⊕ a = 0
Also, 0 is the identity of the ⊕ . So, a ⊕ 0 = 0 ⊕ a = a
Now, suppose the integers given to us are x 1 , x 2 ⋯ x n . Now, because ⊕ is commutative, we can assume, without loss of generality, that x n is the unique integer and x 1 = x 2 , x 3 = x 4 , x 5 = x 6 , ⋯ .
Then, we are assured that x 1 ⊕ x 2 ⊕ x 3 ⋯ x n = x n
So, we can just use an accumulator to ⊕ all the values that are fed in: