HARD Lab · Binary · 24

268. Missing Number

Given an array holding a permutation of 0..n with exactly one value absent, find it in O(n) time and O(1) space using XOR bit manipulation — pair every index with its value and let the un-matched number survive.

EasyBit ManipulationMathTypeScript

PROBLEM What we're solving

You receive an array of n distinct integers drawn from 0..n — exactly one value is missing. Return it.

Example: nums = [3, 0, 1] — the range is 0..3 but 2 is absent → return 2. You can't simply sort and scan (that's O(n log n)); you need a single pass.

KEY IDEA XOR pairs cancel; the survivor is missing

Insight → XOR is its own inverse: a ^ a = 0 and a ^ 0 = a. If you XOR together all indices 0..n and all values in the array, every present number appears exactly twice (once as an index, once as a value) and cancels out. The one missing number has no partner — it survives as the final result.

RECIPE Seed with n, fold in i and nums[i]

  • 0 · Seed xor with n. The full range is 0..n but the loop only reaches indices 0..n-1, so seed with xor = n to include the top bound.
  • 1 · Loop i from 0 to n-1. Each iteration does xor ^= i ^ nums[i] — folds in the index and the value simultaneously.
  • 2 · Return xor. Every value present in nums has been XOR-ed in twice (once as an index, once as itself) and cancelled. Only the missing value has no partner.
Classic confusion → people seed xor = 0 and only loop over the values, forgetting to include the indices 0..n. The pairing only works when every expected number appears on both sides — index side and value side. Seed with n and fold in i alongside nums[i].

COST Complexity & alternatives

Sort then scan
O(n log n)
Easy to reason about, but sorting dominates.
XOR / Gauss sum
O(n)
Single pass, O(1) extra space.

The Gauss sum alternative: the sum of 0..n is n*(n+1)/2. Subtract the actual array sum — the difference is the missing number. Both approaches are O(n) / O(1), but XOR avoids any risk of integer overflow on very large n.

Pattern transfer → the same "XOR pairs cancel" trick solves Single Number (LC 136 — only one unpaired element in an array), Single Number II (LC 137 — every element appears 3× except one), and Find the Duplicate Number (LC 287 with the cycle-detection variant).

RUN IT XOR every index and value — the lone survivor is missing

step 0 / 7
STARTArray has 3 elements so the full range is 0..3. Seed xor = n = 3. XOR-ing a number with itself cancels to 0; the lone survivor will be the missing value.
nums300112
State
3
xor
i
nums[i]
current elementindex / value being foldedmissing number (result)
slowfast

TYPESCRIPT The solution, annotated

missingNumber.ts
function missingNumber(nums: number[]): number {
  // XOR approach — O(n) time, O(1) space
  let xor = nums.length;          // seed with n (the "extra" index)
  for (let i = 0; i < nums.length; i++) {
    xor ^= i ^ nums[i];           // fold in index i and value nums[i]
  }
  return xor;                     // every paired value cancelled; survivor is missing
}

// Alternative: Gauss sum — O(n) time, O(1) space
// function missingNumber(nums: number[]): number {
//   const n = nums.length;
//   const expected = (n * (n + 1)) / 2;   // sum of 0..n
//   const actual   = nums.reduce((a, b) => a + b, 0);
//   return expected - actual;
// }

Reading it block by block

Line 3 — seed xor with n. The index loop runs from 0 to n-1, producing indices 0..n-1. But the expected range is 0..n. Seeding xor = n injects the top bound so every expected index is accounted for.
Lines 4–6 — the XOR fold. Each iteration does xor ^= i ^ nums[i]. This is equivalent to XOR-ing the two sets {0,1,...,n} and {nums[0],...,nums[n-1]} together in one loop. Every present value appears once in each set → pairs cancel to 0.
Line 7 — return xor. The missing number had no matching index to cancel with, so it is the sole survivor in xor. This is the answer.
Lines 11–15 — Gauss alternative (commented out). Compute expected = n*(n+1)/2 then subtract the array sum. Same O(n) / O(1) complexity, but relies on subtraction which could overflow for very large inputs in a language without big integers. XOR is always safe.
Complexity → O(n) time — a single pass over the array. O(1) extra space — only one accumulator variable xor. The Gauss formula is the same complexity; XOR wins on overflow safety.

INTERVIEWFollow-ups they'll ask

  • "What if there are two missing numbers?" XOR alone is insufficient; you need the Gauss sum approach extended with sum-of-squares (or bit partitioning) to separate two unknowns. This is a classic follow-on hard variant.
  • "Can you solve it without extra math — just bit ops?" Yes — the XOR solution already does this. Explain a ^ a = 0 and a ^ 0 = a so the interviewer sees you understand why it works.
  • "What about overflow?" The Gauss sum n*(n+1)/2 can overflow a 32-bit integer for large n. XOR never overflows. In TypeScript numbers are 64-bit floats (safe up to 2^53) so both are fine in practice, but it's a good point to raise.
  • "What if the array contains duplicates instead of a missing value?" That is LC 287 (Find the Duplicate Number) — a different problem requiring Floyd's cycle detection or binary search on the count.
  • Edge cases: nums = [0] → missing is 1; nums = [1] → missing is 0. Both work correctly because we seed with n = 1.

MNEMONIC The one-liner

"Pair every index with its value — the unmatched one survives the XOR."

TRIGGERS When you see ___ → reach for ___

"missing one value from 0..n"XOR index ^ value, seed = n
"find unpaired / single element"XOR — pairs cancel to 0
"O(1) space, no sorting"Bit manipulation or Gauss sum
"sum of consecutive integers"n*(n+1)/2 Gauss formula

SKELETON The reusable shape

skeleton.ts
function missingNumber(nums: number[]): number {
  let xor = nums.length;
  for (let i = 0; i < nums.length; i++) {
    xor ^= i ^ nums[i];
  }
  return xor;
}

FLASHCARDS Tap to flip

Why does XOR find the missing number?
a ^ a = 0. Every present value appears twice (once as an index, once as a value) and cancels. The missing value has no partner — it survives.
tap to flip
1 / 7
Answer to reveal explanations. No penalty for retries.Score: 0 / 7
QUESTION 01
nums = [3, 0, 1]. What does the XOR approach return?
QUESTION 02
Why must you seed xor with n rather than 0?
QUESTION 03
What are the time and space complexities of the XOR solution?
QUESTION 04
The Gauss sum formula for this problem is:
QUESTION 05
nums = [1]. What is the missing number?
QUESTION 06
A key advantage of XOR over the Gauss sum approach is:
QUESTION 07
Which sibling problem is best solved with the identical XOR "pairs cancel" trick?