Find Two Missing Numbers | Set 2 ( XOR based solution ) | Java Program to find 2 Missing Numbers ; 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 . int 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
import java . util . * ; class GFG { static void findTwoMissingNumbers ( int arr [ ] , int n ) { int XOR = arr [ 0 ] ; for ( int i = 1 ; i < n - 2 ; i ++ ) XOR ^= arr [ i ] ; for ( int i = 1 ; i <= n ; i ++ ) XOR ^= i ; int set_bit_no = XOR & ~ ( XOR - 1 ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( ( arr [ i ] & set_bit_no ) > 0 ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } for ( int i = 1 ; i <= n ; i ++ ) { if ( ( i & set_bit_no ) > 0 ) x = x ^ i ; else y = y ^ i ; } System . out . println ( " Two ▁ Missing ▁ Numbers ▁ are ▁ " ) ; System . out . println ( x + " ▁ " + y ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 5 , 6 } ; int n = 2 + arr . length ; findTwoMissingNumbers ( arr , n ) ; } }