Missing Number
You're given an array nums of n distinct integers, each between 0 and n inclusive, in no particular order. That range holds n + 1 values, so exactly one of them is absent from nums. Return the missing value; note that it can be n itself. Aim for O(n) time and O(1) extra space.
Examples
nums = [3,0,1] returns 2
n = 3, so the range is 0, 1, 2 and 3. 0, 1 and 3 are present, which leaves 2.
nums = [0,1] returns 2
n = 2, so the range is 0 to 2. Both 0 and 1 are there, so the missing value is n itself, 2.
Constraints
- 1 <= n <= 10^4
- All numbers are distinct and in [0, n].
Hints
Values come from 0..n with no duplicates, what if each value belonged at a specific index?
Swap each value to its target index in place, then scan for a mismatch.
While iterating, if nums[i] < n and nums[i] != i, swap nums[i] with nums[nums[i]]; otherwise advance. After the pass, the index where nums[j] != j is the missing number; if every index matches, it's n.
Drill This: Your Approach First
Approach
Every value v < n has a home, index v. Walk the array: while nums[i] is less than n and not at its home, swap it into index nums[i]; otherwise move on. Each swap parks one value for good, so there are at most n swaps. Then the first index j with nums[j] != j is the missing number, and if every index matches, the answer is n. It rearranges nums in place.
Time
O(n)
Space
O(1)
Pitfall
Solutions
class Solution {
public int missingNumber(int[] nums) {
int i = 0;
while (i < nums.length) {
if (nums[i] < nums.length && nums[i] != i) {
int tmp = nums[i];
nums[i] = nums[tmp];
nums[tmp] = tmp;
} else {
i++;
}
}
for (int j = 0; j < nums.length; j++) {
if (nums[j] != j) return j;
}
return nums.length;
}
}class Solution:
def missingNumber(self, nums):
i, n = 0, len(nums)
while i < n:
if nums[i] < n and nums[i] != i:
j = nums[i]
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
for j in range(n):
if nums[j] != j:
return j
return n