Practice · Bit manipulation · 2 of 3

Find the Missing Number

The list nums holds n different numbers, all from the range 0 to n. That range has n + 1 numbers, so exactly one of them is missing. Return the missing number.

Aim for O(n) time and a constant amount of extra memory.

Example 1

Input
nums = [2, 0, 4, 1]
Output
3
Four numbers, so the range is 0 to 4, and 3 is missing.

Example 2

Input
nums = [0, 1]
Output
2
Two numbers, so the range is 0 to 2: 0 and 1 are there, so 2 is missing.

Constraints

  • nums holds n numbers, where 1 ≤ n ≤ 10⁴.
  • Every number is between 0 and n, and no number appears twice.