Missing Number
Given an array containing n distinct numbers from 0, 1, 2, ..., n, find the one that is missing.
Example
3,0,1
2
- Input:
numsis , a list of distinct whole numbers. Its length is , and that count fixes the range: the values are supposed to come from . - That range holds candidates but the list only has entries, so exactly one candidate is absent.
- Math: the answer is the single element of . Checking each candidate: is present, is present, is not, is present.
- Output: the integer
2, a single number rather than a list, because there is only ever one gap. - Notice that is read from the list's length, not from its largest value. For , , so the range is and the missing value is
2, the top end itself, even though it is larger than every value in the list. The order ofnumsnever affects the answer.
Constraints
- 1 <= n <= 10^4
- 0 <= nums[i] <= n
- All numbers are unique