PracticeNeetCode ↗LeetCode ↗
Given an array nums containing n distinct numbers taken from the range [0, n], return the one number in that range that's missing from the array.
nums, and everything but the missing number pairs off and cancels.nums has n elements but the range is [0, n] (n + 1 numbers), there's always exactly one index with no matching value.n*(n+1)/2 - sum(nums)) also works, but XOR avoids any risk of integer overflow in other languages.result = len(nums) (this accounts for index n, which has no corresponding array slot).i and value n in nums: update result ^= i ^ n.result.Time: O(n) — Space: O(1)
def missingNumber(nums: list[int]) -> int:
result = len(nums)
for i, n in enumerate(nums):
result ^= i ^ n
return resultHow the solution above works, piece by piece.
result starts at len(nums) because that index doesn't exist in the loop.Running it on nums = [3, 0, 1]: