Find the two repeating elements in a given array | Javascript code to Find the two repeating elements in a given array ; Will hold Xor of all elements ; Will have only single set bit of Xor ; Get the Xor of all elements in arr [ ] and { 1 , 2 . . n } ; Get the rightmost set bit in set_bit_no ; Now divide elements in two sets by comparing rightmost set bit of Xor with bit at same position in each element . ; Xor of first set in arr [ ] ; Xor of second set in arr [ ] ; Xor of first set in arr [ ] and { 1 , 2 , ... n } ; Xor of second set in arr [ ] and { 1 , 2 , ... n } ; driver code
function printRepeating ( arr , size ) { let Xor = arr [ 0 ] ; let set_bit_no ; let i ; let n = size - 2 ; let x = 0 , y = 0 ; for ( i = 1 ; i < size ; i ++ ) Xor ^= arr [ i ] ; for ( i = 1 ; i <= n ; i ++ ) Xor ^= i ; set_bit_no = Xor & ~ ( Xor - 1 ) ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ i ] & set_bit_no ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } for ( i = 1 ; i <= n ; i ++ ) { if ( i & set_bit_no ) x = x ^ i ; else y = y ^ i ; } document . write ( " " + y + " " + x ) ; } let arr = [ 4 , 2 , 4 , 5 , 2 , 3 , 1 ] ; let arr_size = arr . length ; printRepeating ( arr , arr_size ) ;