Missing Number

25 min · missingNumber()

A workshop labels n + 1 storage bins from 0 through n, but today's inventory lists only n of those labels. One label never made it onto the sheet.

Given an integer array nums of length n, return the missing value from the complete range 0..n.

The inventory has strict ground rules:

  • Every value in nums is distinct.
  • Every value lies between 0 and n, inclusive.
  • Exactly one value from that range is absent.

Constraints

  • 1 <= nums.length <= 100_000
  • 0 <= nums[i] <= nums.length
  • All values in nums are distinct.
  • Exactly one value in 0..nums.length is missing.

Hints

Put the labels in order

If you sort a copy, the first position whose index doesn't equal its value reveals the gap. Remember the case where every visited position matches.

Pair two complete lists

The indices contribute 0 through n - 1, while the array contributes every value except one. Add n itself, then look for an operation that cancels matching values.

Cancel with XOR

A value XORed with itself becomes zero. XOR n, every index, and every array value; all present numbers cancel in pairs, so the missing one remains.

Follow-up

The sum formula n * (n + 1) / 2 also gives a linear-time answer. Why might XOR be a safer choice in a language where integer addition can overflow?

Visible cases

Examples

Example 1

ready
Input
nums = [
  3,
  0,
  1
]
Expected
2
Why
the range is 0 through 3, and 2 is absent

Example 2

ready
Input
nums = [
  0,
  1
]
Expected
2
Why
the missing value can be the upper endpoint n

Example 3

ready
Input
nums = [
  9,
  6,
  4,
  2,
  3,
  5,
  7,
  0,
  1
]
Expected
8
Why
all labels from 0 through 9 appear except 8

Interview signal

Asked at

AmazonMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite