find 3 non repeating numbers in an array using xor and constant extra space
let XOR = xor of all the numbers in the array let say
then the ith bit of xor will be 1 (set)
only if either
1. All the 3 non repeating numbers have ith bit set.
2. 1 non repeating number has ith bit set.
and the ith bit of xor will be 0 (unset)
only if either
1. All the 3 non repeating numbers have ith bit unset.
2. 1 non repeating number has ith bit unset.
we make two arrays named set and unset
CASE 1. ( ith bit is set )
if the ith bit of xor is set then we check if the set array has ith element not equal to xor value,
then its a non repeating element. Thats because,
in that case only 2. point satisfies as stated above which is only the number.
CASE 2. ( ith bit is unset )
in this case too only 2. point of the unset statement says that it will be only one element else it will be xor of all the elements.
Comments
Post a Comment