Missing Number
The key idea
Every index
0..n-1 and every value share the full set 0..n except for the one missing number. XOR each index with each value: identical numbers cancel to 0, leaving only the missing one. The Gauss sum n*(n+1)/2 minus the actual sum gives the same answer in O(1) space.Problem
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Constraints
n == nums.length1 <= n <= 10^40 <= nums[i] <= n- All the numbers of
numsare unique.
Examples
Input: nums = [3,0,1]
Output: 2
Input: nums = [0,1]
Output: 2
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization