Skip to content
mlmentorship

Missing Number

Cancel expected and observed integer values under an exact one-omission contract, then change validation or omission count.

Published · 9 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Missing Number

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. An integer list nums of length n, containing distinct values from the inclusive domain 0..n. Output. Return the one domain value absent from the list. Rules. Exactly one member is missing, and all other members appear once. Input order is arbitrary. Duplicates, out-of-range values, and multiple omissions violate the contract. Do not modify the list. Empty input has domain {0} and returns zero. Example. [3, 0, 1] has length 3, so its domain is 0..3; return 2. For [0, 1], return 2, the missing upper endpoint.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Initialize with n, then XOR every expected index and actual value so matched numbers cancel and the missing value survives.

Problem trace

Paired values cancel; the missing value remains

Worked example: paired XOR terms cancel and leave the absent valueMatch each observed value with its copy in the complete expected range. Paired copies cancel. The unpaired value is the missing number, regardless of observation order.Equal XOR terms cancel; the missingrange value stays unpairedRange above; observations below00112332All equal pairs cancel. The absentexpected value two remains.
Read it this way: Match each observed value with its copy in the complete expected range. Paired copies cancel. The unpaired value is the missing number, regardless of observation order. Does reordering the observed values change which expected term remains unpaired?
Full interview answer 9 min read

Find the sole missing integer when every other member of a consecutive domain appears exactly once.

Problem

Input. An integer list nums of length n, containing distinct values from the inclusive domain 0..n.

Output. Return the one domain value absent from the list.

Rules. Exactly one member is missing, and all other members appear once. Input order is arbitrary. Duplicates, out-of-range values, and multiple omissions violate the contract. Do not modify the list. Empty input has domain {0} and returns zero.

Example. [3, 0, 1] has length 3, so its domain is 0..3; return 2. For [0, 1], return 2, the missing upper endpoint.

Picture

The pictured input [3,0,1] omits the value 2. Pairing equal values explains the result without requiring execution to follow this order:

ExpectedObservedXOR contribution
000
110
2absent2
330

Problem trace

Paired values cancel; the missing value remains

Input and goalValues come from 0 through `n`, with one missing. Return the missing value.
Seed the unmatched endpointSeed missing with 3 to include the domain endpoint omitted by enumerate.
i=0300112
expectedDomain[0, 1, 2, 3]accumulatormissing = len(nums) = 3 = 0011₂
i
0
expected domain
[0, 1, 2, 3]
accumulator
missing = len(nums) = 3 = 0011₂

Recognize it
Values should contain every integer from 0 through n exactly once except one, making the actual multiset differ from the expected multiset by a single value.
Keep true
After processing indices before i, missing equals n XOR every processed expected index XOR every processed actual value. Equal values may be regrouped and cancel because XOR is associative, commutative, and self-inverse.
Reuse it
When all values occur in canceling pairs except one, XOR removes order and pair placement from the problem; the same invariant finds a unique element or separates parity-based membership differences.
Seed missing with 3 to include the domain endpoint omitted by enumerate. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does seeding with 3 matter for this input? Which value survives all pair cancellations?
Reference drawing

Problem trace

Paired values cancel; the missing value remains

Worked example: paired XOR terms cancel and leave the absent valueMatch each observed value with its copy in the complete expected range. Paired copies cancel. The unpaired value is the missing number, regardless of observation order.Equal XOR terms cancel; the missingrange value stays unpairedRange above; observations below00112332All equal pairs cancel. The absentexpected value two remains.
Execution trace
Input and goalValues come from 0 through `n`, with one missing. Return the missing value.
Seed the unmatched endpointSeed missing with 3 to include the domain endpoint omitted by enumerate.
i=0300112
expectedDomain[0, 1, 2, 3]accumulatormissing = len(nums) = 3 = 0011₂
i
0
expected domain
[0, 1, 2, 3]
accumulator
missing = len(nums) = 3 = 0011₂

Recognize it
Values should contain every integer from 0 through n exactly once except one, making the actual multiset differ from the expected multiset by a single value.
Keep true
After processing indices before i, missing equals n XOR every processed expected index XOR every processed actual value. Equal values may be regrouped and cancel because XOR is associative, commutative, and self-inverse.
Reuse it
When all values occur in canceling pairs except one, XOR removes order and pair placement from the problem; the same invariant finds a unique element or separates parity-based membership differences.
Seed missing with 3 to include the domain endpoint omitted by enumerate. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does seeding with 3 matter for this input? Which value survives all pair cancellations?
Read it this way: Match each observed value with its copy in the complete expected range. Paired copies cancel. The unpaired value is the missing number, regardless of observation order. Does reordering the observed values change which expected term remains unpaired?

Code

enumerate(nums) supplies expected indices 0..n-1, not endpoint n. Seed missing = n to complete the expected side.

def missing_number(nums: list[int]) -> int:
   missing = len(nums)
   for index, num in enumerate(nums):
      missing ^= index ^ num
   return missing

Why One Value Survives

After a processed prefix, missing XORs the seed, every processed expected index, and every processed observation.

XOR is associative and commutative. Every equal pair cancels because value ^ value == 0, and zero changes nothing.

At completion, each present domain value appears twice. Only the absent value appears once.

The actual accumulator trace is 3 -> 0 -> 1 -> 2. Intermediate accumulators need not be missing values.

Premise and Cost

Empty input omits zero and returns zero. Input order does not affect the result, and the input is unchanged.

Duplicate [0,0,2] violates the premise. The source returns two, which is present; XOR has not validated the observations.

The reference performs XOR operations with a constant number of integer slots. Python’s bit costs depend on integer width.

Recall: What information does XOR discard? Equal pairs disappear, so only occurrence parity remains, not full multiplicity.

Validate the Universe

Choose this when: Duplicate or out-of-range observations should return None.

This helper still requires integer elements; it does not parse or coerce arbitrary types.

def missing_number_checked(nums):
   unique = set(nums)
   if len(unique) != len(nums) or any(
      value < 0 or value > len(nums) for value in nums
   ):
      return None
   return missing_number(nums)

It rejects [0,0] and accepts [3,0,1], returning two. Distinct in-range observations certify exactly one omission because the domain has one extra member.

Validation adds set entries and expected hash work. It leaves the input unchanged.

Recover Two Missing Values

Choose this when: n distinct observations come from 0..n+1, leaving exactly two omissions.

The total XOR is missing_a ^ missing_b, not either answer alone. Distinct missing values differ in at least one bit.

Use the lowest differing bit to separate them. Equal present values still cancel within the same bucket.

def two_missing_numbers(nums):
   difference = 0
   for value in range(len(nums) + 2):
      difference ^= value
   for value in nums:
      difference ^= value
   distinguishing_bit = difference & -difference
   first = 0
   for value in range(len(nums) + 2):
      if value & distinguishing_bit:
         first ^= value
   for value in nums:
      if value & distinguishing_bit:
         first ^= value
   return sorted([first, difference ^ first])

For [0,1,3], it returns [2,4]. Empty input returns [0,1]. Output is sorted, and input is unchanged.

This helper assumes its new domain contract; it does not validate it. It uses XOR operations and constant integer slots, excluding width-dependent bit storage.

Transfer

One XOR cannot reconstruct an arbitrary missing set. Cancellation works because the contract limits which parity differences can remain.