Start learning free

LESSON 306 OF 314 · BIT MANIPULATION

Missing Number in Python: O(n) Time and O(1) Space with XOR

Practice O(n) Read the full explanation

You get a list nums of n different numbers. Each number is from 0 to n.

Exactly one number from 0 to n is not in nums. Return that missing number.

 

Example 1:

Input: nums = [4, 1, 0, 2]
Output: 3
Explanation: The array has 4 numbers, so n = 4.
Of the numbers 0 to 4, only 3 is missing.

Example 2:

Input: nums = [1, 3, 2]
Output: 0
Explanation: Here n = 3.
The numbers 1, 2 and 3 are all there.
The missing number is 0.

Example 3:

Input: nums = [0]
Output: 1
Explanation: Here n = 1, and 0 is in nums.
The missing number is 1, which is n itself.

 

Constraints:

  • n is the length of nums (len(nums)).
  • n is from 1 to 100,000.
  • Each value is from 0 to n.
  • No value appears twice.
Note:

Your algorithm should run in O(n) time and use O(1) extra space.



In Single Number, XOR made the pairs cancel: x XOR x = 0, x XOR 0 = x, and the order doesn't matter. Here no number repeats. Can you give every number that is in nums a partner to cancel with?

The indices of nums go from 0 to n - 1: add n and you have every number from 0 to n once. Start from n and XOR in every index and every value. Each value in nums meets its equal and cancels; the missing number has no partner among the values, so it is what is left.

We visit each index once, with two XORs per index: O(n) time.
We keep a single number, so the extra space is O(1).
STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · BIT MANIPULATION

    Missing Number in Python, explained

    Problem overview

    The method missingNumber receives a list nums of n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one of them is absent from nums. The method returns it.

    For nums = [3, 0, 1] we have n = 3, so the numbers 0, 1, 2 and 3 should all appear. Only 2 is absent, so the result is 2. The missing number can be n itself: for [0, 1] the result is 2. It can also be 0: for [1] the result is 0.

    The lesson asks for O(n) time and O(1) extra space.

    Approach: let every present number cancel itself out

    Two simple ideas come first. You could sort the list and look for the first gap, which costs O(n log n). Or you could put the numbers in a set and test each value from 0 to n, which is O(n) time but O(n) space. XOR gets both bounds down.

    XOR (^ in Python) has three properties that matter here:

    • x ^ x = 0: a number cancels with itself;
    • x ^ 0 = x: zero changes nothing;
    • the order doesn't matter.

    Now build a collection in which every number from 0 to n appears once, from the indices of the list plus n. The indices of nums run from 0 to n - 1, so adding n completes the range. Put that collection together with the values of nums. Each value that is present appears twice, once as an index (or n) and once as a value, and cancels. The missing number appears only among the indices, so it is the only one left.

    Step by step

    1. Start from n. Create result and set it to len(nums). The indices stop at n - 1, so n has to go in here, at the start.
    2. Visit every index. A for loop with i over range(len(nums)) covers the indices 0 to n - 1.
    3. XOR in both the index and the value. The statement result ^= i ^ nums[i] combines i and nums[i] into result.
    4. Return result. Every number that is in nums went in twice and cancelled. What is left is the missing one.

    The solution in Python

    class Solution:
        def missingNumber(self, nums: List[int]) -> int:
            result = len(nums)
            for i in range(len(nums)):
                result ^= i ^ nums[i]
            return result
    

    Python details worth knowing

    • ^= is XOR-assign. result ^= x means result = result ^ x. Because XOR is associative, result ^= i ^ nums[i] gives the same result as writing two separate ^= lines.
    • ^ is not a power operator. Exponentiation is ** in Python. ^ is bitwise XOR.
    • No overflow worries. Python integers can be any size, and XOR of numbers up to n never exceeds the largest of them in bit length.

    Trace on [3, 0, 1]

    Here result starts at 3. The table shows its value after each turn of the loop:

    inums[i]result afterwards
    030
    101
    212

    The method returns 2. In this run the 3 from the list cancelled the starting 3, the 0 cancelled index 0, the 1 cancelled index 1, and index 2, which has no partner among the values, remained.

    Complexity

    Time: the loop visits each index once and does two XORs per index, so the time is O(n).

    Space: a single number, result, is kept, so the extra space is O(1).

    Edge cases and common mistakes

    • The missing number is n. For [0, 1] the starting value 2 never meets a partner among the values, so the method returns 2.
    • The missing number is 0. For [1] the loop XORs 0 and 1 into result = 1, which leaves 1 ^ 0 ^ 1 = 0. The method returns 0.
    • Starting result at 0. That leaves n out of the collection of indices, so the answer is wrong whenever the missing number is not n: it ends up XORed with n.
    • Looping with range(len(nums) + 1). That reads nums[n], one past the end, and raises an IndexError.
    • Relying on the formula n * (n + 1) // 2 minus the sum. This also works in Python, because integers don't overflow, but in languages with fixed-size integers the sum can overflow, and the XOR version doesn't have that problem.

    Testing

    These results come from running the solution:

    numsResult
    [3, 0, 1]2
    [0, 1]2
    [1]0
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free