arrays
math
bit-manipulation
You are given an array nums containing n distinct numbers taken from the range 0 through n.
Exactly one value in that range is missing. Return the missing number.
Input / output
- Input:
nums: int[] - Output: the missing integer in
[0, n]
Examples
nums = [3, 0, 1]returns2.nums = [0, 1]returns2.nums = [9,6,4,2,3,5,7,0,1]returns8.
Constraints
1 <= nums.length <= 1000000 <= nums[i] <= nums.length- All values in
numsare distinct.
Edge cases
- The missing value may be
0. - The missing value may be
nitself. - The input is not guaranteed to be sorted.
Target complexity
- Aim for
O(n)time andO(1)extra space.
Hints
- Compare the expected sum of
0 + 1 + ... + nwith the actual array sum. - The XOR trick also works because equal values cancel each other.
Follow-up What other constant-space approach can you derive using XOR instead of arithmetic sums?
Examples
Example 1
Input: nums = [3,0,1]
Output: 2
Example 2
Input: nums = [0,1]
Output: 2
Example 3
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.