Problem Statement
Missing Number
You get a list called nums. It is supposed to hold every whole number from 0 up to n, where n is how many numbers are in the list. But exactly one number from that range is missing, and your job is to find it. The trick we use is XOR. XOR is a way to combine two numbers bit by bit, and it has one magic property: if you XOR the same number twice, it disappears and turns into 0. So if we XOR every number in the full range 0 to n together with every number actually in the list, every number that shows up in both places cancels itself out. The only one left standing is the number that was missing.
Signals to notice
Brute force first
Sort and scan for the gap. Or use a boolean array. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
The key insight
Expected sum = n(n+1)/2. Actual sum = sum of array. Missing = expected - actual. Or XOR all numbers with 0.n — the missing number is the result. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.
Trace it on nums=[3,0,1]
init: n=3, result=n=3 i=0: result = 3 ^ 0 ^ nums[0]=3 -> 3^0^3 = 0 i=1: result = 0 ^ 1 ^ nums[1]=0 -> 0^1^0 = 1 i=2: result = 1 ^ 2 ^ nums[2]=1 -> 1^2^1 = 2 loop done: every index/value paired & canceled except missing 2 return result = 2
What must stay true
The sum of 0.n is a known formula. The difference between the expected sum and the actual sum is exactly the missing number. XOR achieves the same by canceling all paired values. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.
Shape of the loop
result = n // seed with n (the index never present as a value)
for i in 0..n-1:
result ^= i // fold in each index
result ^= nums[i] // fold in each value; pairs cancel
return result // survivor = missing numberPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Integer overflow with the sum approach for very large n — use XOR instead, which never overflows. Or use long/BigInt. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.