Skip to content

The Missing Value

Easy#xor-cancel#single-pass~20 min

The mission

Problem

A list holds n distinct values drawn from 0 up to n, in any order, so exactly one value of that range is absent. Find it in one pass using constant extra space, which rules out sorting and rules out a set of everything seen.

Examples

Input:  nums = [3, 0, 1]
Output: 2
Input:  nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
Output: 8
Input:  nums = [0]
Output: 1
Why:    edge case, the missing value can be n itself

Hints

0 / 3

Target time
O(n)
Target space
O(1)

Constraints

  • n distinct values drawn from 0 to n
  • exactly one value of the range is missing

Stuck on the idea rather than the code? XOR Tricks covers it.

Python 3Ctrl+Enter runs
Custom test case