Missing Number solution explained
The Missing Number solution uses the fact that the full range 0 to n has a known total: subtract the sum of the list from n(n + 1) / 2 and what remains is the missing value. An XOR version does the same job without any risk of overflow, because every value that appears both as an index and as an entry cancels itself out. Both run in O(n) time with O(1) extra memory.
By Evin JohnPublished 7 min read
The problem in plain words
Imagine numbered tickets from 0 to n, one of each. One ticket was lost, and the remaining n tickets are handed to you in no particular order. Which number is missing? Every ticket that is present appears exactly once, and the missing one can be any value in the range, including 0 or n itself.
| List | Range | Missing | Note |
|---|---|---|---|
| [1, 0, 3] | 0 to 3 | 2 | A value from the middle |
| [4, 2, 0, 1] | 0 to 4 | 3 | Unsorted input |
| [0] | 0 to 1 | 1 | The top of the range is missing |
| [1, 2] | 0 to 2 | 0 | Zero is missing; easy to forget |
| [] | 0 to 0 | 0 | An empty list means the range is just 0 |
What the interviewer wants to see
Most candidates find a working answer in a minute. The interesting part is the conversation that follows: can you reach O(1) extra memory, do you know why the sum version can overflow in a fixed-width language, and can you explain the XOR version clearly rather than recite it? It is also a quick test of edge cases, because the two ends of the range behave differently from the middle.
Follow-up questions
- Two numbers are missing. The sum and the sum of squares give two equations; or XOR everything to get a ^ b, split by any set bit, and XOR each group separately.
- The list is sorted. Binary search for the first index i where the entry is not equal to i, which is O(log n).
- One number is duplicated and one is missing. Compare the actual sum and sum of squares with the expected ones, or mark visited positions by flipping signs in place.
- The numbers arrive as a stream too large to store. Keep a running XOR or a running sum; both need only one variable.
- You may not modify the input. All the answers here leave it unchanged.
First answers
The most literal approach checks each candidate from 0 to n and asks whether it is in the list. With a plain list scan that is O(n²). Sorting first and walking until position i holds something other than i brings it to O(n log n). Putting the values in a hash set makes each check O(1) and the total O(n), at the cost of O(n) memory. Any of these is a fine opening, as long as you then ask whether the extra memory or time is needed.
def missing_by_scanning(nums):
for candidate in range(len(nums) + 1):
if candidate not in nums: # a list scan: O(n) per check
return candidateThe arithmetic answer
If nothing were missing, the values would add up to 0 + 1 + ... + n, which is n(n + 1) / 2. The list's actual sum is smaller by exactly the missing value. In Python, integers never overflow, so this is safe for any size. In a language with fixed-width integers, the expected total for a large n can exceed the type's range, so either use a wider type or subtract as you go, or switch to XOR.
def missing_by_sum(nums):
n = len(nums)
return n * (n + 1) // 2 - sum(nums)The XOR answer
XOR has two properties that make it a perfect eraser: any value XORed with itself is 0, and any value XORed with 0 is unchanged. The order of operations does not matter. So XOR together every index from 0 to n - 1, the number n itself, and every value in the list. Each value that is present shows up twice, once as an index-range number and once as an entry, and cancels. The only number that appears once is the missing one, and that is what is left.
def missing_by_xor(nums):
result = len(nums) # n itself has no index to pair with
for i, value in enumerate(nums):
result ^= i ^ value
return resultfunction missingNumber(nums) {
let result = nums.length;
for (let i = 0; i < nums.length; i++) {
result ^= i ^ nums[i];
}
return result;
}Trace it on [1, 0, 3]: start with 3, then fold in index 0 and value 1, index 1 and value 0, index 2 and value 3. The pile holds 3, 0, 1, 1, 0, 2, 3. The two 3s cancel, the two 0s cancel, the two 1s cancel, and 2 remains.
Cost of each approach
| Approach | Time | Extra memory | Notes |
|---|---|---|---|
| Check each candidate with a list scan | O(n²) | O(1) | Correct, too slow for large inputs |
| Sort, then find the first gap | O(n log n) | O(1) to O(n), depending on the sort | Sorting in place changes the input |
| Hash set of values | O(n) | O(n) | Fast; memory is the cost |
| Sum difference | O(n) | O(1) | Overflow risk in fixed-width languages |
| XOR of indexes and values | O(n) | O(1) | No overflow; needs a clear explanation |
Edge cases
- The missing value is 0. The sort-and-scan version must check position 0, not start at 1.
- The missing value is n. Every position matches its value, so the gap is after the end.
- An empty list, where n is 0 and the answer is 0.
- A list of length one: [0] gives 1 and [1] gives 0.
- Very large n in a fixed-width language, where n(n + 1) can overflow before the division.
Common slips
- Using the largest value in the list as n. If n itself is missing, the largest value is n - 1 and the answer comes out wrong. Use the list's length.
- Starting the XOR at 0 instead of n, which forgets the one number that never appears as an index.
- Dividing before multiplying in integer arithmetic, so n / 2 truncates for odd n.
- Sorting the caller's list in place without asking whether that is allowed.
- Calling the set version O(1) memory.
How to explain it out loud
Fictional example
- Candidate
- A set of the values would let me check 0 through n in linear time, but it uses linear memory. I think we can do better because we know exactly what the complete range looks like.
- Candidate
- The complete range sums to n times n plus one over two, so the gap between that and the actual sum is the missing number. I'll take n from the list's length, not from the largest value, because n itself might be the missing one.
- Candidate
- If overflow is a concern, XOR does the same without big totals: every present value appears twice, as an index and as an entry, and cancels. Linear time, constant memory.
Related problems
Number of 1 Bits is a good companion if XOR and AND tricks are new. Sum of Two Integers shows XOR acting as addition without carries. The set-based first answer is the same idea as the lookup in Two Sum, and Valid Sudoku uses sets to spot repeats rather than gaps.
Where Natively helps
When you rehearse a short problem like this, the risk is answering too fast and skipping the edge cases. Natively can read the prompt from a screenshot on your Mac or Windows PC, compare your first idea with the constant-memory ones, and remind you to test a missing 0 or a missing n. The transcript it keeps of a mock interview shows you afterwards whether you explained the cancellation or just wrote the loop.
Questions people ask
How do you find the missing number from 0 to n?
Subtract the sum of the list from n(n + 1) / 2, where n is the list's length, or XOR all indexes, the value n and all entries together. Both take O(n) time and O(1) extra memory.
Why does the XOR method work for Missing Number?
A value XORed with itself is 0 and XOR order does not matter. Every present number appears twice, once in the index range and once in the list, so it cancels, leaving only the missing number.
Can the sum method overflow?
In languages with fixed-width integers, n(n + 1) / 2 can exceed the type for large n. Use a wider type, subtract as you go, or use XOR. Python integers do not overflow.
Should n be the largest value in the list?
No. Use the list's length. If n itself is the missing value, the largest entry is n - 1 and the answer would come out wrong.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
