XOR the range with the array
XOR every index 0..n with every value. Pairs cancel; the missing number is left.
The complete range is 0..n. The array is that range minus one value. XOR is how you subtract without summing.
Algorithm
- Start
acc = n. - XOR
accwith each(i ^ nums[i]). - Return
acc.
- Time
- O(n)
- Space
- O(1)
class Solution: def missingNumber(self, nums: list[int]) -> int: acc = len(nums) for i, x in enumerate(nums): acc ^= i ^ x return acc