LeetCode #268 Easy

Missing Number

Missing Number is LeetCode 268 (Easy). The array nums holds n distinct numbers, all taken from the range 0 to n.

  • That range has n + 1 numbers, so exactly one of them is absent.
  • Return the absent number.

The follow-up asks for O(n) time and O(1) extra space, which rules out sorting and rules out a set of seen values.

Constraints
  • n == nums.length
  • 1 <= n <= 10⁴
  • 0 <= nums[i] <= n
  • All the numbers of nums are unique.
mathbit-manipulationarray
Open on LeetCode ↗
02

Intuition

If nothing were missing, the numbers would be 0, 1, 2, …, n, and their sum is known without looking at the array: n(n + 1) / 2. The array has every one of those numbers except one, so its sum falls short by exactly the missing value.

So to find the missing number, start from the full total and subtract each number in the array. Each subtraction removes a number that is present. When the array runs out, the only number never subtracted is the missing one, and it is all that is left of the total.

How to spot this pattern

Distinct values from a known, gap-free range with one value absent: compare what the range should add up to with what the array adds up to. Find All Numbers Disappeared in an Array handles several gaps, and Single Number uses the same XOR cancelling trick on pairs.

03

Approach

Try it first

Before reading on, write down what 0 + 1 + … + n equals for n = 3, then compare it with the sum of [3, 0, 1]. Aim for one pass and two variables.

1

Work out the full total

Let n be the array length. The complete range 0 to n sums to n * (n + 1) / 2. That needs no loop, because the formula pairs the smallest and largest numbers, which always add to n.

2

Take each present number out

Walk the array once and subtract every value from the total. Values are distinct, so each number in the range is removed at most once.

3

Return what is left

After the loop, the total holds the sum of the numbers that never appeared. Exactly one number is absent, so that sum is the answer, including when the answer is 0 or n.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def missingNumber(self, nums):
▶3 n = len(nums)
▶4 expected = n * (n + 1) // 2
▶5 for x in nums:
▶6 expected -= x
▶7 return expected
nums301numbers 0 to 30123running total60 to 3 adds up to 6
n3
expected60 + 1 + 2 + 3
With 3 numbers in the array, the full set is 0 to 3. Its sum is 3 × 4 ÷ 2 = 6. Every number that shows up will be taken back out of this total.
nums301numbers 0 to 30123running total6−3=3saw 3 → total drops to 3
x3
expected3
3 is present, so it cannot be the missing number. Taking it off the total leaves 6 − 3 = 3, the sum of the numbers not seen yet.
nums301numbers 0 to 30123running total3−0=3saw 0 → total drops to 3
x0
expected3
0 is present, so it cannot be the missing number. Taking it off the total leaves 3 − 0 = 3, the sum of the numbers not seen yet.
nums301numbers 0 to 30123running total3−1=2saw 1 → total drops to 2
x1
expected2
1 is present, so it cannot be the missing number. Taking it off the total leaves 3 − 1 = 2, the sum of the numbers not seen yet.
nums301numbers 0 to 30123running total2answer: 2
result2
Every number in the array has been removed, and exactly one slot stayed empty. The total that is left is the sum of the unseen numbers, which is just that one number: 2.
05

XOR of indices and values

Start with n, then XOR in every index i and every value nums[i]. Together the indices and n list each number from 0 to n once. Each value in the array matches one of those and cancels it, because a ^ a = 0. The one number with no partner survives.

▶1class Solution:
▶2 def missingNumber(self, nums):
▶3 result = len(nums)
▶4 for i, x in enumerate(nums):
▶5 result ^= i ^ x
▶6 return result
06

Common pitfalls

Using 1 to n instead of 0 to n

✗ Wrong
expected = n * (n - 1) // 2
✓ Right
expected = n * (n + 1) // 2

The array has n values but the range has n + 1, because it starts at 0 and ends at n. With the shorter formula, [0, 1] gives 1 − 1 = 0 instead of 2, and every answer comes out n too small.

Checking neighbours after sorting

✗ Wrong
nums.sort()
for i in range(len(nums)):
    if nums[i] != i:
        return i
✓ Right
nums.sort()
for i in range(len(nums)):
    if nums[i] != i:
        return i
return len(nums)

When the missing number is n itself, every position matches its value and the loop never returns. [0, 1] falls through and returns nothing. Sorting also costs O(n log n), which misses the follow-up.

07

Complexity

Time
O(n)
Space
O(1)
One pass over the array and one running number. In C++ and Java the total is at most 10⁴ × (10⁴ + 1) / 2, about 5 × 10⁷, so a plain int holds it.
08

Missing Number FAQ

Can the sum overflow on bigger inputs?

In languages with fixed-size integers, yes: for n above about 46,000, n * (n + 1) passes the 32-bit limit. Subtracting as you go (total += i + 1 - nums[i]) keeps the running value small, and the XOR version below never grows past the largest number at all.

What if more than one number is missing?

One equation can only pin down one unknown. With two gaps, use both the sum and the sum of squares, or mark seen values in place by flipping signs, as in Find All Numbers Disappeared in an Array.