Skip to content
ΣDSA Patterns
Menu
Language

Bit Manipulation

Guide 4 of 6 · Path 4 of 6

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

Tested only
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

Bit XOR identity (same family as single number).

Reflection