Problem: Array contains distinct numbers from to . One is missing. Find it.
XOR approach: XOR all array elements with . Pairs cancel, leaving the missing number.
function missingNumber(nums):
n = nums.length
result = n
for i from 0 to n-1:
result = result ^ i ^ nums[i]
return result
Example: , .
- XOR: .
- Missing: .
Alternative: Sum formula. Expected sum = . Subtract actual sum.
Both are time, space (excluding input). XOR avoids potential overflow.