You can try this.It will take O (n) time
int xor = arr[0]; int set_bit_no; int i; int x = 0; //First unpair number int y = 0; //second unpair number for (i = 1; i < n; i++) xor ^= arr[i]; set_bit_no = xor & ~(xor-1);//Get the rightmost set bit in set_bit_no for (i = 0; i < n; i++) { if (arr[i] & set_bit_no) { //XOR of first set x = x ^ arr[i]; } else { //XOR of second set y = y ^ arr[i]; } }
Explanation ... arr [] = {2, 4, 7, 9, 2, 4} 1) Get the XOR of all the elements. xor = 2 ^ 4 ^ 7 ^ 9 ^ 2 ^ 4 = 14 (1110) 2) Get a number that has only one bit of the xor bit.
Since we can easily get the rightmost bit, let us use it. set_bit_no = xor and ~ (xor-1) = (1110) and ~ (1101) = 0010 Now set_bit_no will only set the most extreme bit of xor. 3) Now we divide the elements into two sets and make xor of elements in each set, and we get non-repeating elements 7 and 9.
source share