Skip to content
StackDecode
Array techniquesAnimated

Missing Number Algorithm

Expected sum 0..n minus the actual sum (or XOR everything).

Time

O(n)

Extra space

O(1)

Use it for

One value missing from 0..n.

How it works

  1. The array holds n distinct numbers from 0 to n, so exactly one is missing.
  2. The numbers 0..n add up to n(n+1)/2.
  3. Subtract the actual sum of the array: the difference is the missing number.
  4. Constant extra memory and one pass.

Watch it run

Loading animation…