If there were no O (1) space restrictions, you could go to the hash map with values ββthat are an occurrence counter.
int getUniqueElement(int[] arr) { int ones = 0 ; //At any point of time, this variable holds XOR of all the elements which have appeared "only" once. int twos = 0 ; //At any point of time, this variable holds XOR of all the elements which have appeared "only" twice. int not_threes ; for( int x : arr ) { twos |= ones & x ; //add it to twos if it exists in ones ones ^= x ; //if it exists in ones, remove it, otherwise, add it // Next 3 lines of code just converts the common 1 between "ones" and "twos" to zero. not_threes = ~(ones & twos) ;//if x is in ones and twos, dont add it to Threes. ones &= not_threes ;//remove x from ones twos &= not_threes ;//remove x from twos } return ones; }
It mainly uses the fact that x^x = 0 and 0^x=x . Thus, all paired elements get XOR'd and disappear, leaving a lone element.
In short:
If the bit is already in one, add it to two.
XOR will add this bit to them if it is not there, or remove this bit from those if it already exists.
If the bit is in both two and two, remove it from two and two.
Upon completion, they contain bits that only appear 3 * n + 1 times, which are bits for an element that appears only once.
Rahul source share