Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the two non-repeating elements in an array of repeating element XOR operator?

Tags:

c

algorithm

xor

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

like image 671
Ajay Yadav Avatar asked Aug 07 '12 09:08

Ajay Yadav


1 Answers

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.

like image 184
amit Avatar answered Oct 19 '22 18:10

amit