CodingNodes / Bit Manipulation / Missing Number System design Space play · ←→ step · R restart

Problem

You get nums, n different numbers, each taken from the range 0..n. Exactly one number in that range is not in the array.

Return the missing number.

Constraints

  • n = nums.length
  • 1 ≤ n ≤ 10000
  • 0 ≤ nums[i] ≤ n
  • All values in nums are different

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: One pass over the array, two XORs per element.

Space: Only the number x is kept, and an XOR never grows beyond the bits of n.

XOR of a number with itself is 0, and XOR with 0 changes nothing. Start x at n, then XOR in every index and every value. Each number from 0 to n shows up once as a label (index, or n itself) and once as a value, except the missing one, which only shows up as a label. Everything else cancels, so x is the missing number.