VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-two-missing-numbers-set-2-xor-based-solution/

⇱ Find Two Missing Numbers | Set 2 (XOR based solution) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Two Missing Numbers | Set 2 (XOR based solution)

Last Updated : 23 Jul, 2025

Given an array of n unique integers where each element in the array is in range [1, n]. The array has all distinct elements and size of an array is (n-2). Hence Two numbers from the range are missing from this array. Find the two missing numbers.
Examples: 
 

Input : arr[] = {1, 3, 5, 6}, n = 6
Output : 2 4

Input : arr[] = {1, 2, 4}, n = 5
Output : 3 5

Input : arr[] = {1, 2}, n = 4
Output : 3 4


 


Find Two Missing Numbers | Set 1 (An Interesting Linear Time Solution)
We have discussed two methods to solve this problem in above article. The method 1 requires O(n) extra space and method 2 can causes overflow. In this post, a new solution is discussed. The solution discussed here is O(n) time, O(1) extra space and causes no overflow.
Below are steps. 
 

  1. Find XOR of all array elements and natural numbers from 1 to n. Let the array be arr[] = {1, 3, 5, 6}
     XOR = (1 ^ 3 ^ 5 ^ 6) ^ (1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6)
  2. As per the property of XOR, same elements will cancel out and we will be left with 2 XOR 4 = 6 (110). But we don't know the exact numbers,let them be X and Y.
  3. A bit is set in xor only if corresponding bits in X and Y are different. This is the crucial step to understand.
  4. We take a set bit in XOR. Let us consider the rightmost set bit in XOR, set_bit_no = 010
  5. Now again if we XOR all the elements of arr[] and 1 to n that have rightmost bit set we will get one of the repeating numbers, say x.
    Ex: Elements in arr[] with bit set: {3, 6}
    Elements from 1 to n with bit set {2, 3, 6}
    Result of XOR'ing all these is x = 2.
  6. Similarly, if we XOR all the elements of arr[] and 1 to n that have rightmost bit not set, we will get the other element, say y.
    Ex: Elements in arr[] with bit not set: {1, 5}
    Elements from 1 to n with bit not set {1, 4, 5}
    Result of XOR'ing all these is y = 4 


Below is the implementation of above steps. 
 

Output:  

Two Missing Numbers are
2 4


Time Complexity : O(n) 
Auxiliary Space : O(1) 
No integer overflow
 

Comment