Missing Number

Find the number from 0 to n that an array leaves out, by letting XOR cancel every number that appears twice.

Given an array nums of n distinct numbers taken from the range 0 to n, return the one number in that range that the array does not contain. Solve it in O(n) time with O(1) extra space, which means a fixed amount of memory besides the input, however long the array is.

Example 1
Input: [3, 0, 1]
Output: 2
Explanation: n = 3, so the range is 0 to 3, and 2 is missing.
Example 2
Input: [0, 1]
Output: 2
Explanation: The missing number can be n itself.
Example 3
Input: [9, 6, 4, 2, 3, 5, 7, 0, 1]
Output: 8
Solution

The Idea

Picture four seats numbered 0 to 3 and three guests, each with a ticket for a different seat. One seat stays empty. In Example 1 the tickets are 3, 0 and 1, so seat 2 is the empty one. Sorting the tickets would show the gap but costs extra time, and ticking seats off on a list costs extra memory.

Here is another way to see it. The array has three slots, with indexes 0, 1 and 2, and n is 3. Together, the indexes and n list every number from 0 to 3 exactly once. The values list every number from 0 to 3 except the missing one. So each present number shows up twice, and the missing number shows up once. How can the pairs cancel each other without matching them up one by one?

Java has an operator for that cancelling: ^, called XOR (exclusive or). It looks at two int values in binary, one bit position at a time, and writes 1 where the two bits differ and 0 where they are the same. So 3 ^ 3 is 0, because every bit matches, and any number XOR 0 is that number unchanged. The order in which numbers are XOR-ed together does not change the result.

Bit positions are counted from the right: position 0 is worth 1, position 1 is worth 2, and position 2 is worth 4. So 3 is 011 in binary, and 2 is 010. A Java int has 32 bits, but for the numbers 0 to 3 every bit above position 1 is 0, so three positions are enough to show them.

Look at the picture below. Each row is one of the seven numbers that go into the XOR for [3, 0, 1]. The row labelled n comes first, then each index followed by the value stored there. Blue labels mark n and indexes 0 and 1, teal labels mark the values, and index 2 is in orange.

For [3, 0, 1] with n = 3, the seven numbers n, index 0, value 3, index 1, value 0, index 2 and value 1 in binary, with columns for positions 2, 1 and 0. Index 2 has no partner. Position 2 has no 1s, position 1 has three and position 0 has four, so the XOR of all seven is 010, which is 2.

Value 3 pairs with n, value 0 with index 0, and value 1 with index 1. Only the orange row, index 2, labelled no partner, has no twin. In the column for position 0, four rows have a 1, an even count, so the XOR has 0 there. Position 1 has three 1s, an odd count, so the XOR has 1 there.

Why does the count decide it? Two equal numbers put the same bit into every column, so they always add an even number of 1s. Only index 2 adds 1s that nothing matches. That is why the row labelled XOR of all seven reads 010, which is 2: the XOR of everything is exactly the missing number.

Solution Approach

Turning the cancelling into code means seeing why simpler ways fall short, settling which numbers go into the XOR and what the running result starts as, and weighing an optional sum-based way.

Simpler ways and their cost

Why not check each number from 0 to n in turn? Each check scans the whole array, so the work grows with n times n. Sorting the array first and looking for the first index whose value differs takes O(n log n) time. Putting the values in a HashSet and asking it about each number is fast, but the set holds n numbers, which breaks the O(1) space rule.

Which numbers go into the XOR

Does each index have to meet its own value? No, because the order of the XORs does not matter. The code walks the array with one loop, and at index i it mixes in both i and the value nums[i], even though they are usually different numbers. In Example 1, index 0 holds 3. That 3 still meets its twin, n, which goes into the XOR separately, and the result comes out the same.

The starting value

Where does n go in? The loop only sees the indexes 0 to n - 1, so n has no index of its own. Starting the running result x at n puts it in before the loop. If x started at 0, n would never go in, and the result would be the missing number XOR n. For [3, 0, 1] that gives 1, and for [0, 1] it gives 0, both wrong.

The sum of 0 to n, an alternative

The numbers 0 to n add up to n × (n + 1) / 2, so subtracting the array's sum also leaves the missing number. In Example 1 that is 6 minus 4, which is 2. The catch is size: the product n × (n + 1) is worked out before the division.

In an int, that product stops fitting in 32 bits once n passes 46,340, and Java wraps it around to a negative number without any error. Computing the sum in long avoids that. XOR has no such limit here, because XOR-ing numbers below a power of two never gives a number at or above that power.

Java Solution

The method missingNumber works in these steps:

  1. First, set the running result x to nums.length, which is n, so n goes into the XOR before the loop.
  2. Then a for loop moves the index i from 0 to n - 1. At each step, x ^= i ^ nums[i] mixes in the index and the value stored there.
  3. When the loop ends, every present number has met its twin and cancelled, so x holds the missing number, and the method returns it.

A second method, missingBySumInInt, does the sum way in int on purpose, to show where it breaks. The main method runs the three examples and the one-element arrays [0] and [1]. It then gives both methods an array of the numbers 50,000 down to 0 without 12,345.

Java
public class MissingNumber {

    public static int missingNumber(int[] nums) {
        int x = nums.length;              // n has no index of its own, so it goes in first
        for (int i = 0; i < nums.length; i++) {
            x ^= i ^ nums[i];             // a value that is present cancels its matching index
        }
        return x;
    }

    // The sum way, computed in int: n * (n + 1) overflows once n passes 46,340.
    static int missingBySumInInt(int[] nums) {
        int n = nums.length;
        int expected = n * (n + 1) / 2;
        int sum = 0;
        for (int v : nums) {
            sum += v;
        }
        return expected - sum;
    }

    public static void main(String[] args) {
        System.out.println(missingNumber(new int[] {3, 0, 1}));
        System.out.println(missingNumber(new int[] {0, 1}));
        System.out.println(missingNumber(new int[] {9, 6, 4, 2, 3, 5, 7, 0, 1}));
        System.out.println(missingNumber(new int[] {0}));
        System.out.println(missingNumber(new int[] {1}));

        int[] big = new int[50000];      // 50,000 down to 0, without 12,345
        for (int v = 50000, k = 0; v >= 0; v--) {
            if (v != 12345) {
                big[k++] = v;
            }
        }
        System.out.println("xor: " + missingNumber(big) + ", int sum: " + missingBySumInInt(big));
    }
}

Running it prints:

Output
2
2
8
1
0
xor: 12345, int sum: -2147471303

The second line, 2, is Example 2's answer and also n itself. In [0, 1] every value cancelled its own index, and only the starting value of x was left. The 1 and the 0 below the 8 come from [0] and [1], where n is 1 and the missing number is whichever of 0 and 1 the array lacks.

Look at the last line. XOR finds 12345 in the large array, while the int sum prints -2147471303. Here n is 50,000, and 50,000 × 50,001 is 2,500,050,000, which is too big for an int, so the sum way subtracts from a wrapped-around number.

Complexity

The method reads each slot of the array once and keeps a single running number.

  • Time: O(n), because the loop runs once for each of the n slots and does two XORs at each step.
  • Space: O(1), because only x and the index i are kept, and the input array is read without being changed.

The same cancelling of equal pairs finds the one number without a twin in Single Number.