Find the two numbers with odd occurrences in an unsorted array | Prints two numbers that occur odd number of times . Function assumes that array size is at least 2 and there are exactly two numbers occurring odd number of times . ; Will hold XOR of two odd occurring elements ; Will have only single set bit of xor2 ; Get the xor of all the elements in arr [ ] . The xor will basically be xor of two odd occurring elements ; Get one set bit in the xor2 . We get rightmost set bit in the following line as it is to get . ; divide elements in two sets : 1 ) The elements having the corresponding bit as 1. 2 ) The elements having the corresponding bit as 0. ; XOR of first set is finally going to hold one odd occurring number x ; XOR of second set is finally going to hold the other odd occurring number y ; Driver code
function printTwoOdd ( arr , size ) { let xor2 = arr [ 0 ] ; let set_bit_no ; let i ; int n = size - 2 ; let x = 0 , y = 0 ; for ( i = 1 ; i < size ; i ++ ) xor2 = xor2 ^ arr [ i ] ; set_bit_no = xor2 & ~ ( xor2 - 1 ) ; for ( i = 0 ; i < size ; i ++ ) { if ( ( arr [ i ] & set_bit_no ) > 0 ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } document . write ( " " + x + " " + y + " " ) ; } let arr = [ 4 , 2 , 4 , 5 , 2 , 3 , 3 , 1 ] ; let arr_size = arr . length ; printTwoOdd ( arr , arr_size ) ;