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 . ; 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 ; Range of numbers is 2 plus size of array
< ? php function findTwoMissingNumbers ( $ arr , $ n ) { $ XOR = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n - 2 ; $ i ++ ) $ XOR ^= $ arr [ $ i ] ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ XOR ^= $ i ; $ set_bit_no = $ XOR & ~ ( $ XOR - 1 ) ; $ x = 0 ; $ y = 0 ; for ( $ i = 0 ; $ i < $ n - 2 ; $ 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 ; } echo " Two ▁ Missing ▁ Numbers ▁ are STRNEWLINE " , $ x ; echo " STRNEWLINE " , $ y ; } $ arr = array ( 1 , 3 , 5 , 6 ) ; $ n = 2 + count ( $ arr ) ; findTwoMissingNumbers ( $ arr , $ n ) ; ? >