The problem: you get an array of n distinct numbers taken from the range 0..n. Exactly one value in that range is absent. Return it. It looks like a warm-up, and it is, but interviewers like it because each solution opens a different follow-up question.
Sort the array, then walk it. The first index i where nums[i] != i is the answer; if no index mismatches, the answer is n.
def missing_number(nums):
nums.sort()
for i, v in enumerate(nums):
if v != i:
return i
return len(nums)
That costs O(n log n) time and mutates the input. Say that out loud: the interviewer will usually ask whether you are allowed to change the caller's array.
The numbers 0..n add up to n*(n+1)/2. Subtract the actual sum and the difference is the missing value.
def missing_number(nums):
n = len(nums)
return n * (n + 1) // 2 - sum(nums)
O(n) time, O(1) extra space. In Python integers do not overflow, but in Java or C++ with 32-bit ints, n*(n+1) overflows once n passes about 46,000. Fix it by accumulating i - nums[i] as you go, or by using a 64-bit type. Mentioning the overflow before you are asked is an easy signal of care.
XOR every index 0..n and every value. Each present number appears twice and cancels; the missing one survives.
def missing_number(nums):
x = len(nums)
for i, v in enumerate(nums):
x ^= i ^ v
return x
Same complexity as the sum, no overflow risk in any language. It is the answer most interviewers are fishing for, but only if you can explain why it works: XOR is associative, commutative, and a ^ a = 0.
a ^ b; split all numbers by any set bit of that result and XOR each group separately.nums[i] != i: O(log n).Start with sort-and-scan in one sentence, move to the sum, flag overflow, then land on XOR. Three solutions in five minutes shows range without wasting time. If you want to rehearse that kind of narration under real pressure, a tool like the Linkjob AI interview assistant can help you practice explaining trade-offs as you code.
Disclosure: written by the Linkjob AI team.