Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Bit Manipulation

Missing Number

EASY✓ CHIP-TIMEDLC #268 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: An array holding n distinct numbers pulled from the range 0 to n has exactly one value missing — find it without ever fully sorting the array.

An array shows up holding n distinct integers, each one pulled from the range 0 through n inclusive — since that range actually has n + 1 possible values, exactly one of them never made it in.

The task is to name that missing value. Nothing about the array's order is meaningful — the values can appear in any arrangement, and no duplicates ever show up.

Only one number is ever absent, and the array's length always matches n, so the missing value can be pinned down without needing a full sort or a separate presence array.

  • the array holds exactly n distinct integers, sized from empty up to a few hundred thousand
  • every value lies between 0 and n inclusive, with exactly one value absent
  • no duplicates ever appear in the input array
  • the order of the array carries no guarantee and is not meaningful
EX 01
nums = [3, 0, 1]
→ 2
missing value in the middle
EX 02
nums = [0, 1]
→ 2
missing the largest value
EX 03
nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
→ 8
larger range, missing near the top

The hintstake only what you need

HINT 1 THE NUDGE

Checking, for every candidate in the range, whether it shows up anywhere in the array works — but each check re-scans the whole thing.

HINT 2 THE STRUCTURE

Every number from 0 to n should appear exactly once except the missing one. What operation cancels a value against its own index for free?

HINT 3 ONE STEP FROM THE ANSWER

XOR every index 0..n together with every array value. Every present number cancels against the index that would have held it, leaving the missing one.

Coach's boardthe pattern, step by step

THE XOR GAPPATTERN · XOR INDEX AGAINST VALUEnums = [3, 0, 1]
3
0
1
RUNNING XOR (n folded in)
result → 3
STEP 1

n=3, so start the accumulator at 3 — XOR in every index and every array value, and whatever survives unpaired is the missing number.

STEP 1 / 5 · ← → WORK TOO

The splitstwo paces, two languages

grind/missing-number.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        result = len(nums)
        for i, v in enumerate(nums):
            result ^= i ^ v
        return result
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 6 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED