← Questions

Missing number

0
Coding

A list of n distinct integers holds every number from 0 to n except one. Return the missing number in linear time and constant extra space.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • missing_number(nums: list[int]) -> int.

Example

missing_number([3, 0, 1])                    ->  2
missing_number([0, 1])                       ->  2     # the top of the range is missing
missing_number([9, 6, 4, 2, 3, 5, 7, 0, 1])  ->  8

Constraints

  • 1 <= n <= 10^4; values are distinct and in [0, n].

Clarifying questions

  • Is the range always 0..n, or could it start elsewhere?
  • Is the input sorted?
  • May I modify the list?
  • Can numbers be large enough that a sum overflows (in a fixed-width language)?

What a strong answer covers

  • The sum formula: n (n + 1) / 2 minus the sum of the list, and the overflow risk in fixed-width integers.
  • XOR of all indices and values, which cannot overflow.
  • O(n) time and O(1) space, against sorting (O(n log n)) or a hash set (O(n) space).
  • Edge cases: the missing number is 0 or n, a list of one element.

Follow-ups

  • The list is sorted. Do it in O(log n).
  • Two numbers are missing. Find both in one pass and O(1) space.
  • One number is missing and another appears twice.
  • The numbers are in a file too big for memory.

What it tests

arrays · math · bit manipulation

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding