Problem overview
The method missingNumber(_ nums: [Int]) -> Int receives an array of n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one of them is absent, and the method returns it.
For nums = [3, 0, 1], n is 3, so the numbers 0, 1, 2 and 3 should all appear. Only 2 is absent, so the answer is 2. For [0, 1] the answer is 2, because the missing number can be n itself. For [1] it is 0.
The lesson asks for O(n) time and O(1) extra space.
Approach: let equal numbers cancel
A set of the values gives O(n) time but needs O(n) space. Sorting avoids the extra space but costs O(n log n). XOR meets both limits.
XOR (^) has three properties that matter here: x ^ x is 0, x ^ 0 is x, and the order of operations doesn't matter. So when a group of numbers is XORed together, every number that appears twice cancels, and what remains is the XOR of the numbers that appear once.
Here no number repeats, so the trick is to give every present number a partner. The indices of nums run from 0 to n - 1. Add n and you have every number from 0 to n, once each. XOR in all of those, then XOR in every value of nums. Each value in the array meets its equal among the indices and n, and the pair cancels. The missing number appears only among the indices and n, with no partner, so it is what is left.
Step by step
- Start
resultatnums.count, which isn. It is avar. The indices stop atn - 1, sonhas to be added at the start. - Loop
iover0..<nums.count, which visits every index. - XOR in the index and the value:
result ^= i ^ nums[i]. - Return
result.
The solution in Swift
class Solution {
func missingNumber(_ nums: [Int]) -> Int {
var result = nums.count
for i in 0..<nums.count {
result ^= i ^ nums[i]
}
return result
}
}
The Swift details worth a closer look:
^=. It is the compound assignment for XOR:result ^= vmeansresult = result ^ v. Inresult ^= i ^ nums[i], the right side is computed first.0..<nums.count. The half-open range stops beforenums.count, soiis always a valid index. Becausenums.countis at least 1 here, the range is never inverted, but even for an empty array0..<0is a valid empty range.- No overflow. XOR never overflows, unlike a sum-based solution. Swift traps on overflow, so the XOR version has no overflow concern at all.
Tracing [3, 0, 1]
Here n is 3, so result starts at 3:
start result=3
i=0 value=3 result=0
i=1 value=0 result=1
i=2 value=1 result=2
After the first pass the 3s have cancelled, and 0 is XORed twice in total, once as index 0 and once as a value, so it cancels too. Only 2 has no partner, and the result is 2.
Complexity
Time: O(n). The loop visits each index once and does two XORs per index.
Space: O(1). A single integer, result, is kept.
Edge cases and common mistakes
- The missing number is
n. For[0, 1]the answer is 2. That is whyresultstarts atnums.countrather than 0: otherwisenwould never enter the XOR. - The missing number is 0.
[1]gives 0, and[0]gives 1. - Starting at 0. Starting
resultat 0 leavesnuncancelled, and the final answer would be the missing number XORn. - Looping to
nums.countinclusive. Readingnums[nums.count]is out of range and crashes. - Distinct numbers. The cancelling argument relies on each value appearing once. An array with a repeated value breaks it.
- A longer example.
[9, 6, 4, 2, 3, 5, 7, 0, 1]hasn = 9and returns 8.
Testing
nums = [3, 0, 1]gives2.nums = [0, 1]gives2.nums = [1]gives0.nums = [0]gives1.nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]gives8.
