Skip to content

Missing Number

Find the one number missing from the range 0 to n by XORing every index with every value.

EasyBit Manipulation
Solve on LeetCode

The problem

You get an array nums of n distinct numbers, all taken from the range 0 to n. Exactly one number of that range is missing. Return it, using only O(1) extra space.

Input nums = [4, 0, 3, 1]

Output 2

n is 4, so the range is 0 to 4, and 2 is the one not in the array.

Input nums = [2, 0, 1]

Output 3

The missing number can be n itself.

Key constraint: The numbers are distinct and come from 0 to n, so the indexes 0 to n - 1 plus n itself list every number of the range exactly once.

How to spot the pattern

  • A range of numbers with exactly one missing.
  • Pairing every value with a matching index lets everything except the answer cancel out.

The idea

If you XOR together all the numbers 0 to n and all the values in the array, every number that is present appears twice and cancels to 0, because x ^ x = 0. Only the missing number appears once, so it is what remains. The indexes 0 to n - 1 supply most of the range for free, and starting the result at n covers the last one.

Brute force: Put the numbers in a set and check 0 to n one by one, which takes O(n) time but also O(n) extra space.

Step by step

  1. 1Start with result = n.
  2. 2For each index i, XOR both i and nums[i] into result.
  3. 3Return result.

Code

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        # XOR all the indexes 0..n with all the values: every number that is present
        # shows up twice and cancels, so only the missing one is left
        result = len(nums)  # n has no index of its own, so start with it
        for i, x in enumerate(nums):
            result ^= i ^ x
        return result

Complexity

Time

O(n)

Space

O(1)

One pass that keeps a single number.

Watch out for

  • Forgetting that the missing number can be n itself: if result does not start at n, that case comes out wrong.
  • Using the sum formula with fixed-size integers when n is huge, where n * (n + 1) / 2 can overflow; XOR never does.

Follow-up questions

Is there a way without bits?

Yes: the missing number is n * (n + 1) / 2 minus the sum of the array. It is just as fast; only watch for overflow when n is large.

What if the array were sorted?

Binary search for the first index where nums[i] != i; that index is the missing number, found in O(log n) time.

In Hinglish

0 se n tak ke saare numbers aur array ki saari values ka XOR lo. Jo number dono jagah hai woh cancel, jo missing hai wahi bachega.

Related problems