Suppose I have an array with 2n+2 elements. n elements in array are occurring twice and remaining two elements are unique. You have to solve this in O(n) time and O(1) space. One of the solution is using XOR. But I am not able to understand that. Can anyone help me regarding that or can give me better solution ?
Link of the Problem and solution is this
First - note that a xor a == 0
, for each a
.
Let's say you have two unique numbers - x,y
.
If you do xor on each element, you end up with a single number, which equals x xor y
(because each dupe pair nullify itself), and has at least one bit "up". Chose this bit (Doesn't matter which up bit you take if there are more then one), and split the list into two sub lists:
(1) All numbers that have this bit set.
(2) all numbers that have this bit unset.
One of the unique numbers has this bit, the other does not (otherwise - it was not "up" in the first place), so you have one unique number in each list.
Iterate each list once more, and do xor on all elements, the result is the unique number in this list, since each duplicate pair nullify itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With