Missing number (XOR)
n numbers are drawn from 0..n with one value missing. Find it by XORing indices and values together.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
The numbers 0..n XORed together, with every present value also XORed in, would cancel every value that appears in both lists, since x ^ x = 0. Only the missing number from 0..n, which has no partner in the array, survives. Folding in the index i instead of a separate range loop gets both lists XORed in one pass.
Code
public static int MissingNumber(int[] a) {
int n = a.Length;
int result = n;
for (int i = 0; i < n; i++)
result ^= i ^ a[i];
return result;
}static int missingNumber(int[] a) {
int n = a.length;
int result = n;
for (int i = 0; i < n; i++)
result ^= i ^ a[i];
return result;
}int missingNumber(const vector<int>& a) {
int n = a.size();
int result = n;
for (int i = 0; i < n; i++)
result ^= i ^ a[i];
return result;
}def missing_number(a: list[int]) -> int:
n = len(a)
result = n
for i in range(n):
result ^= i ^ a[i]
return resultTips
- Starting result at n instead of 0 accounts for the one index (n itself) that the loop never reaches.
- This avoids the overflow risk of sum(0..n) - sum(a) on very large inputs.
In the .NET library
The same cancel-in-pairs idea powers Single number: here the pairs are (index, value) instead of (duplicate, duplicate).