Start learning free

LESSON 306 OF 314 · BIT MANIPULATION

Missing Number in Go: O(1) Space with XOR

Practice O(n) Read the full explanation

You get an array 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

    GO · BIT MANIPULATION

    Missing Number in Go, explained

    Problem overview

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

    For nums = [3, 0, 1], n is 3 and the range is 0, 1, 2, 3. The numbers 0, 1 and 3 are present, so the answer is 2. For nums = [0, 1] the answer is 2, which is n itself. For nums = [1] the answer is 0.

    The lesson asks for O(n) time and O(1) extra space, which rules out a map or a set of the numbers seen.

    Approach: let equal numbers cancel

    XOR, written ^ in Go, has three useful properties: x ^ x is 0, x ^ 0 is x, and the order of the operands doesn't matter. So when a group of numbers is XORed together, any number that appears twice vanishes.

    Here nothing repeats inside nums, but we can give every number in nums a partner. The indices of nums run from 0 to n - 1. Add n to those and you have every number from 0 to n exactly once. Now XOR together all of those numbers and all the values in nums. Each value that is in nums meets an equal number among the indices and n, and the pair cancels. The missing number appears only among the indices and n, so nothing cancels it, and it is what is left.

    The implementation starts result at n, then folds in each index and each value. For nums = [3, 0, 1] the running value is:

    start 3
    i 0 nums[i] 3 result 0
    i 1 nums[i] 0 result 1
    i 2 nums[i] 1 result 2
    

    The final value, 2, is the missing number.

    Other solutions exist. Adding up 0 to n with the formula n * (n + 1) / 2 and subtracting the sum of nums also works in Go, where int is 64 bits and no overflow happens at these sizes. The XOR version does the same job with no arithmetic at all.

    Step by step

    1. Create result with := and start it at len(nums), which is n. The indices stop at n - 1, so n has to enter the XOR here.
    2. Loop over every index: i starts at 0 and goes up while i < len(nums).
    3. XOR the index and the value into result with ^=. Both i and nums[i] go in on each pass.
    4. Return result after the loop.

    The solution in Go

    func missingNumber(nums []int) int {
        result := len(nums)
        for i := 0; i < len(nums); i++ {
            result ^= i ^ nums[i]
        }
        return result
    }
    

    The Go details worth knowing:

    • ^ has two meanings. Between two operands, as in i ^ nums[i], it is XOR. In front of a single operand, ^x, it flips every bit. ^= is the compound assignment for XOR.
    • Evaluation order. result ^= i ^ nums[i] first computes i ^ nums[i] and then folds the result into result. Because XOR is associative and commutative, this equals XORing each of the three numbers in separately.
    • len(nums) is an int. It has the same type as the indices and the values, so no conversion is needed.

    Complexity

    Time: O(n). The loop makes one pass over the slice and does two XORs per element.

    Space: O(1). The function keeps result and the loop variable.

    Edge cases and common mistakes

    • The missing number is n. For [0, 1] every value from 0 to n - 1 is present. result starts at n, and nothing in the loop cancels it, so it is returned: 2.
    • The missing number is 0. For [1] the result is 0, because the index 0 has no equal value to cancel it.
    • Starting result at 0. Then n never enters the XOR, and the function returns the missing number XOR n. For [3, 0, 1] that gives 1 instead of 2, and for [0, 1, 2, 4] it gives 7 instead of 3.
    • Only XORing the values. Without the indices there is nothing for the values to cancel against.
    • Relying on order. The slice does not need to be sorted. [9, 6, 4, 2, 3, 5, 7, 0, 1] returns 8.

    Testing

    • nums = [3, 0, 1] gives 2.
    • nums = [0, 1] gives 2.
    • nums = [1] gives 0.
    • nums = [0, 1, 2, 4] gives 3.
    • nums = [4, 3, 2, 1] gives 0.
    • nums = [9, 6, 4, 2, 3, 5, 7, 0, 1] gives 8.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free