Missing Number

easy

You're handed an array nums of n distinct integers. Every value is drawn from the range [0, n] — that's n + 1 possible numbers for only n slots, so exactly one value from that range never shows up.

Return that single missing number.

For nums = [3, 0, 1] we have n = 3, so the full range is [0, 3] = {0, 1, 2, 3}. The array holds 0, 1, 3 — the only absentee is 2, so the answer is 2.

Hints

You have n slots but n + 1 possible values — one value from 0…n simply never appears. How would you spot which one?
Checking 'is k in the array?' by re-scanning is slow. What structure makes that check instant — or can you avoid checking each candidate entirely?
You know the sum of a full 0…n. Compare it against the sum you actually have; the gap is the answer, in O(n) time and O(1) space.

Common doubts

There are n numbers occupying n slots, but they're chosen from n + 1 candidates (0 through n inclusive). That extra candidate is exactly the one that goes missing.
Yes. If nums = [1, 2, 3] then 0 is missing; if nums = [0, 1, 2] then 3 (which equals n) is missing. The sum formula handles both without special cases.
With n up to 10^4 the expected sum is about 5×10^7, safe in a 32-bit int. In C++ we still widen to long long as a habit; if overflow ever worried you, the XOR method sidesteps it entirely.

Interview follow-ups

Sum alone gives you a + b, which isn't enough to separate them. Add a second equation — the sum of squares — or partition the numbers by a distinguishing bit and XOR within each group, the classic 'two single numbers' technique.
Yes — that's precisely what the sum and XOR approaches deliver: O(n) time, O(1) space, and they never touch nums. It's the classic "no extra space, don't modify the input" follow-up.

Fun facts

  • The sum trick is a 250-year-old shortcut: as a schoolboy, Carl Friedrich Gauss reportedly summed 1…100 instantly by pairing terms — the very formula n(n+1)/2 we lean on here.
  • The 'expected minus actual' idea reappears everywhere: checksums, find-the-duplicate, reconciling ledgers, and error-detecting codes all compare an ideal aggregate against reality.

Asked at

AmazonMicrosoftGoogleBloombergAdobe
Frequently Sometimes Occasionally
Example 1
Input: nums = [3,0,1]
Output: 2
n = 3, so the range is [0,3]. Every number appears except 2.
Example 2
Input: nums = [0,1]
Output: 2
n = 2, so the range is [0,2]. 0 and 1 are present, so 2 is missing.
Example 3
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
n = 9, so the range is [0,9]. Every number is present except 8.
Constraints

- n == nums.length - 1 <= n <= 10^4 - 0 <= nums[i] <= n - All the numbers of nums are unique.

Solve this problem →