← Questions
Missing number
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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) / 2minus 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
0orn, 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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