Find Two Missing Numbers | Set 2 ( XOR based solution ) | Function to find two missing numbers in range [ 1 , n ] . This function assumes that size of array is n - 2 and all array elements are distinct ; Get the XOR of all elements in arr [ ] and { 1 , 2 . . n } ; Get a set bit of XOR ( We get the rightmost set bit ) ; Now divide elements in two sets by comparing rightmost set bit of XOR with bit at same position in each element . let x = 0 , y = 0 ; Initialize missing numbers ; 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 program to test above function ; Range of numbers is 2 plus size of array
function findTwoMissingNumbers ( arr , n ) { let XOR = arr [ 0 ] ; for ( let i = 1 ; i < n - 2 ; i ++ ) XOR ^= arr [ i ] ; for ( let i = 1 ; i <= n ; i ++ ) XOR ^= i ; let set_bit_no = XOR & ~ ( XOR - 1 ) ; for ( let i = 0 ; i < n - 2 ; i ++ ) { if ( arr [ i ] & set_bit_no ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } for ( let i = 1 ; i <= n ; i ++ ) { if ( i & set_bit_no ) x = x ^ i ; else y = y ^ i ; } document . write ( ` ${ x } ${ y } ` ) ; } let arr = [ 1 , 3 , 5 , 6 ] ; n = 2 + arr . length ; findTwoMissingNumbers ( arr , n ) ;