Skip to content
DSA Patterns
Menu
Language
Bit ManipulationLC #2684 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Missing Number

Problem (restated)

Array of n distinct numbers in [0, n]. Find the missing one.

Intuition

XOR of 0..n with all nums cancels pairs; leftover is missing.

Approaches

XOR 0..n with nums

Unverified
Time O(n)Space O(1)

Idea. x=0..n fold with nums.

Walkthrough. [3,0,1] → 2.

Trade-offs. Sum formula also O(n); XOR avoids overflow concerns in other langs.

Solution
export function missingNumber(nums: number[]): number {
  let x = nums.length;
  for (let i = 0; i < nums.length; i++) x ^= i ^ nums[i]!;
  return x;
}
export function missingNumber(nums: number[]): number {
  let x = nums.length;
  for (let i = 0; i < nums.length; i++) x ^= i ^ nums[i]!;
  return x;
}

Template connection

XOR 0..n together with every value in nums. The missing number is the value that never paired.

Reflection

  • XOR 0 through n together with every value in the array. Pairs cancel and the missing number remains. n * (n + 1) / 2 - sum(nums) is the same answer.
  • 0 may be the missing value. n may be the missing value: the array holds n numbers from a range of n + 1. A single 0 means 1 is missing.
  • The sum can overflow. The XOR cannot.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

nums = [3,0,1] holds n=3 distinct values from [0,3]. One is missing.

3
0
0
1
1
2

XOR 0..n with nums

Key:CurrentActive rangeMatchSettled