The 30 second answer
The array holds n distinct numbers from zero to n with one missing. XOR every index from zero to n with every value; equal numbers cancel, so what remains is the missing one. The sum formula also works, but XOR cannot overflow. Both are linear time and constant space.
Problem An array has n distinct numbers taken from the range 0 to n. Return the one number in that range that is missing. Original: LeetCode 268: Missing Number.
Understanding the prompt "Distinct" and "range 0..n" with n values means exactly one gap.
Pattern recognition A known value range plus O(1) space points to XOR cancellation, a sum formula, or index marking.
Brute force Sort and look for the first index where nums[i] != i: O(n log n). Or use a HashSet: O(n) space.
Optimal Start x = n, then x ^= i ^ nums[i] for each i. Pairs cancel and the missing value remains.
Alternatives n(n+1)/2 minus the sum of the array. Compute it in long, or note that int overflow cancels out in two's-complement arithmetic. XOR avoids the question entirely.
Java solution
public class MissingNumber {
static int missingNumber(int[] nums) {
int x = nums.length;
for (int i = 0; i < nums.length; i++) x ^= i ^ nums[i];
return x;
}
public static void main(String[] args) {
System.out.println(missingNumber(new int[] {3, 0, 1})); // 2
System.out.println(missingNumber(new int[] {0, 1})); // 2
System.out.println(missingNumber(new int[] {9, 6, 4, 2, 3, 5, 7, 0, 1})); // 8
}
}Complexity O(n) time and O(1) space.
Edge cases
- The missing number is n, as in [0,1], which returns 2.
- The missing number is 0.
- A single element.
Follow-ups
- Several numbers missing: see Find All Numbers Disappeared in an Array.
- One duplicate plus one missing: XOR partitioning, or index marking.
Tests [3,0,1] returns 2. [0,1] returns 2. [9,6,4,2,3,5,7,0,1] returns 8.
How to say it in the interview "XOR of a number with itself is zero, so if I XOR all indices 0..n and all values, everything pairs off except the missing number. One pass, constant space, no overflow concerns."
Sources (2)
- LeetCode 268: Missing Numberleetcode.com
- JLS 17, 15.22.1: Integer bitwise operatorsdocs.oracle.com