Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Find Missing Number using XOR in C++

Find a missing number with XOR in C++: XOR 1 to n against the array so pairs cancel, then find two missing numbers by splitting on the lowest set bit.

AdvancedBitwise Operations ProgramsExample 5 of 5
find-missing-number-using-xor.cpp
1#include <iostream>
2#include <vector>
3using namespace std;
4
5// Find missing number in array containing n-1 numbers from 1 to n
6int findMissingNumber(vector<int>& arr, int n) {
7 int xor1 = 0; // XOR of all numbers from 1 to n
8 int xor2 = 0; // XOR of all numbers in array
9
10 // XOR of numbers 1 to n
11 for (int i = 1; i <= n; i++) {
12 xor1 ^= i;
13 }
14
15 // XOR of numbers in array
16 for (int num : arr) {
17 xor2 ^= num;
18 }
19
20 // Missing number is xor1 ^ xor2
21 return xor1 ^ xor2;
22}
23
24// Find two missing numbers
25pair<int, int> findTwoMissingNumbers(vector<int>& arr, int n) {
26 int xor1 = 0;
27 int xor2 = 0;
28
29 // XOR of all numbers from 1 to n
30 for (int i = 1; i <= n; i++) {
31 xor1 ^= i;
32 }
33
34 // XOR of numbers in array
35 for (int num : arr) {
36 xor2 ^= num;
37 }
38
39 // XOR of two missing numbers
40 int xorMissing = xor1 ^ xor2;
41
42 // Find rightmost set bit
43 int rightmostSetBit = xorMissing & ~(xorMissing - 1);
44
45 int missing1 = 0, missing2 = 0;
46
47 // Separate numbers into two groups based on rightmost set bit
48 for (int i = 1; i <= n; i++) {
49 if (i & rightmostSetBit) {
50 missing1 ^= i;
51 } else {
52 missing2 ^= i;
53 }
54 }
55
56 for (int num : arr) {
57 if (num & rightmostSetBit) {
58 missing1 ^= num;
59 } else {
60 missing2 ^= num;
61 }
62 }
63
64 return {missing1, missing2};
65}
66
67int main() {
68 // Test case 1: One missing number
69 vector<int> arr1 = {1, 2, 4, 5, 6}; // Missing 3
70 int n1 = 6;
71 cout << "Array: ";
72 for (int num : arr1) cout << num << " ";
73 cout << "\nMissing number: " << findMissingNumber(arr1, n1) << endl;
74
75 // Test case 2: Two missing numbers
76 vector<int> arr2 = {1, 3, 5, 6}; // Missing 2 and 4
77 int n2 = 6;
78 cout << "\nArray: ";
79 for (int num : arr2) cout << num << " ";
80 auto result = findTwoMissingNumbers(arr2, n2);
81 cout << "\nMissing numbers: " << result.first << " and " << result.second << endl;
82
83 return 0;
84}

Sample Output

Missing number: 3

7 ^ 4.

Missing numbers: 2 and 4

2 has the isolated bit 010 set; 4 does not.

In this one

  • Why XOR cancels every number that appears twice
  • How to find one missing number in O(n) time and O(1) space
  • How the lowest set bit splits two missing numbers apart
  • Why XOR is safer than the sum formula

How it works

  1. 1

    XOR 1 to n into xor1 and the array into xor2.

  2. 2

    One missing: return xor1 ^ xor2.

  3. 3

    Two missing: xorMissing = m1 ^ m2.

  4. 4

    Isolate its lowest set bit.

  5. 5

    XOR each group separately to get m1 and m2.

Dry run: Find Missing Number using XOR

Two missing, arr {1, 3, 5, 6}, n = 6

  1. 1.xorMissing = 2 ^ 4 = 110, lowest bit = 010
  2. 2.Bit set: 1..6 → 2, 3, 6; arr → 3, 6 → XOR = 2
  3. 3.Bit clear: 1..6 → 1, 4, 5; arr → 1, 5 → XOR = 4
Two missing, arr {1, 3, 5, 6}, n = 6
xorMissing = 2 ^ 4 = 110, lowest bit = 010
Bit set:   1..6 → 2, 3, 6; arr → 3, 6   → XOR = 2
Bit clear: 1..6 → 1, 4, 5; arr → 1, 5   → XOR = 4

Edge cases

Nothing missing

Pass {1,2,3,4,5,6} to findMissingNumber.

The result is 0, which is not in 1 to n, so treat 0 as "none missing".

Wrong n

Pass n = 5 for {1, 2, 4, 5, 6}.

xor1 leaves out 6, so the answer is wrong (3 ^ 6 = 5). n must be the full range size.

Duplicates in the input

Use {1, 2, 2, 5, 6} with n = 6.

The duplicate 2 cancels itself, so the result mixes the missing numbers and the extra copy. The method only works when every value is unique.

What's going on

You are given the numbers 1 to n with one missing, in any order. XOR finds the missing one in a single pass with no extra memory.

The idea: XOR every number from 1 to n, then XOR every number in the array. Each number that appears in both cancels out, because x ^ x = 0. The only thing left is the missing number.

For {1, 2, 4, 5, 6} with n = 6: xor1 = 1^2^3^4^5^6 = 7, and xor2 = 1^2^4^5^6 = 4. Then 7 ^ 4 = 3, the missing number.

The second function handles two missing numbers, which is harder. XORing everything as before leaves xorMissing = m1 ^ m2. For {1, 3, 5, 6}, the missing numbers are 2 and 4, so that is 2 ^ 4 = 6 (110).

Because m1 and m2 are different, xorMissing has at least one 1 bit, which is a position where they differ. xorMissing & ~(xorMissing - 1) isolates the lowest such bit; here, 010. (You will also see this written as x & -x.)

Now split every number, both 1 to n and the array, into two groups by that bit. m1 and m2 land in different groups, and every other number appears twice inside its own group. XORing within each group cancels the pairs and leaves one missing number per group: 2 in the group with that bit set and 4 in the other.

Both functions run in O(n) time with O(1) extra space. A sum formula also works for one missing number, n(n+1)/2 minus the array sum, but it can overflow for large n. XOR never overflows.

The method assumes the input is valid: no duplicates and every other number present. If the array had a duplicate as well as a gap, the XOR result would be meaningless.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <vector> is there because it provides vector container class. Leave one out and the compiler stops at the first name it does not recognize.

Understanding XOR Properties

Key XOR Properties:

a ^ a = 0 (XOR with itself is zero)
a ^ 0 = a (XOR with zero is identity)
XOR is commutative: a ^ b = b ^ a
XOR is associative: (a ^ b) ^ c = a ^ (b ^ c)

Why Useful:

XOR cancels out pairs
Missing number appears once
Other numbers appear twice (cancel)
Result is missing number

Finding Single Missing Number

Algorithm:

1.XOR all numbers from 1 to n → xor1
2.XOR all numbers in array → xor2
3.Missing number = xor1 ^ xor2

What happens here:

xor1: XOR of complete set (1 to n)
xor2: XOR of array (missing one number)
xor1 ^ xor2: cancels all pairs, leaves missing
Example: {1,2,4,5} missing 3
xor1 = 1^2^3^4^5
xor2 = 1^2^4^5
Result = 3

Finding Two Missing Numbers

Algorithm:

1.XOR all numbers 1 to n → xor1
2.XOR all numbers in array → xor2
3.xorMissing = xor1 ^ xor2 (XOR of two missing)
4.Find rightmost set bit in xorMissing
5.Separate numbers into two groups
6.Find missing in each group

What happens here:

xorMissing contains XOR of two missing numbers
Rightmost set bit: numbers differ at this bit
Group by this bit: one missing in each group
Find missing in each group separately

Rightmost Set Bit

Finding Rightmost Set Bit:

int rightmostSetBit = xorMissing & ~(xorMissing - 1);

What happens here:

xorMissing - 1: flips rightmost set bit and bits to right
~(xorMissing - 1): inverts (all 1s except rightmost set bit)
xorMissing & ~(...): extracts rightmost set bit
Isolates the differing bit position

Separating into Groups

Grouping Logic:

Group 1: numbers with rightmost set bit set
Group 2: numbers with rightmost set bit clear
One missing number in each group
Find missing in each group using XOR

What happens here:

Two missing numbers differ at rightmost set bit
One has bit set, other has bit clear
Separates them into different groups
Each group has one missing number

Time and Space Complexity

Time Complexity:

O(n) - single pass through numbers
Linear time complexity
Optimal for this problem
Very efficient

Space Complexity:

O(1) - constant extra space
Only few variables needed
No additional data structures
Space optimal

When to Use XOR Approach

Good fits:

Finding missing numbers
Array with one missing
Array with two missing
Space-constrained problems
Efficient solutions needed

Example Scenarios:

Finding missing ID
Array with missing element
Duplicate detection
Efficient algorithms
Interview problems

Important Considerations

XOR Properties:

Understand XOR behavior
Cancellation property
Pair elimination
Foundation of algorithm

Edge Cases:

Handle empty array
Single element missing
Two elements missing
Boundary conditions

Efficiency:

Optimal time: O(n)
Optimal space: O(1)
Better than sorting
Better than hash set

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is 1^2^3^4 ^ 1^2^4?

Pick an answer to check it.

Question 2

Why split the numbers by one bit of m1 ^ m2?

Pick an answer to check it.

Questions people ask

Why not just sort and scan?

That is O(n log n). XOR is O(n) with no extra memory.

Does the order of the array matter?

No. XOR is commutative.

Which is first in the pair?

The one whose isolated bit is set. Here that is 2, so the output says 2 and 4.