0:00 / 0:00

One number from 0 to n is gone. Add up what 0 to n should total, subtract what you have, and the gap is the answer.

▼

The problem

LeetCode 268 (Easy). Given an array nums of n distinct numbers taken from the range 0..n, return the one number in the range that is missing.

Example (LeetCode's third): nums = [9, 6, 4, 2, 3, 5, 7, 0, 1], n = 9 → 8.

def missing_number(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    return expected - sum(nums)
TRY IT ON LEETCODE ▶

The solution

def missing_number(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    return expected - sum(nums)

Transcript

Missing Number. You get a list of n different numbers, each between zero and n. That range holds n plus one values, but the list has only n, so exactly one is missing. Find it.

Here are nine numbers: nine, six, four, two, three, five, seven, zero, one. So n is nine, and we need ten lockers, from zero to nine. Drop each number into its locker. One locker stays empty: locker eight. The answer is eight.

The obvious ways work, but each one costs something. Sort the numbers and walk along until one doesn't match its place: that takes n log n time. Or put every number in a set, then ask for zero, one, two, and so on. That's linear time, but a whole set of extra space.

Here's the trick: don't hunt for the gap, weigh it. If nothing were missing, the lockers would add up to zero plus one plus two, all the way to n. That's n times n plus one, over two. Now add up the numbers you actually have. The shortfall is exactly the missing one.

In code, take n from the length, compute the expected total, subtract the sum of the list, and return it. Where big sums can overflow, XOR every index and every value together, starting from n. Each number that's present shows up twice and cancels out, so only the missing one survives.

Back to our nine numbers. N is nine, so a full set adds up to nine times ten over two: forty-five. Now tally what we have: nine, fifteen, nineteen, twenty-one, twenty-four, twenty-nine, thirty-six, thirty-six, thirty-seven. Forty-five minus thirty-seven is eight. Locker eight.

We read each number once, so the time is linear. We keep one running total, so the space is constant.

Count what should be there, subtract what is. That's Missing Number.