Missing Element in Sorted Array Problem
Description
LeetCode Problem 1060.
Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the k^th missing number starting from the leftmost number of the array.
Example 1:
Input: nums = [4,7,9,10], k = 1
Output: 5
Explanation: The first missing number is 5.
Example 2:
Input: nums = [4,7,9,10], k = 3
Output: 8
Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8.
Example 3:
Input: nums = [1,2,4], k = 3
Output: 6
Explanation: The missing numbers are [3,5,6,7,...], hence the third missing number is 6.
Constraints:
1 <= nums.length <= 5 * 10^41 <= nums[i] <= 10^7numsis sorted in ascending order, and all the elements are unique.1 <= k <= 10^8
Follow up: Can you find a logarithmic time complexity (i.e., O(log(n))) solution?
Solution
Approach: Binary Search on the Missing Count
Because the numbers are distinct and sorted, we can say how many numbers are missing before any index without looking at the others. From nums[0] up to nums[i] there are nums[i] - nums[0] + 1 integers and i + 1 of them are in the array, so
missing(i) = nums[i] - nums[0] - i
For [4, 7, 9, 10] this is 0, 2, 3, 3. It never decreases as i grows.
- If
k > missing(n - 1), the answer is past the last element:nums[n - 1] + (k - missing(n - 1)). - Otherwise, binary search for the smallest
iwithmissing(i) >= k. Thek-th missing number lies betweennums[i - 1]andnums[i], andmissing(i - 1)of the missing numbers come beforenums[i - 1], so the answer isnums[i - 1] + (k - missing(i - 1)).
Since missing(0) = 0 < k, that i is always at least 1, so nums[i - 1] exists.
Complexity: O(log n) time and O(1) extra space.
class Solution:
def missingElement(self, nums: List[int], k: int) -> int:
def missing(i: int) -> int:
return nums[i] - nums[0] - i # numbers missing between nums[0] and nums[i]
n = len(nums)
if k > missing(n - 1):
return nums[n - 1] + k - missing(n - 1) # the answer is past the last element
# The smallest i with missing(i) >= k; the answer lies between nums[i - 1] and nums[i].
lo, hi = 1, n - 1
while lo < hi:
mid = (lo + hi) // 2
if missing(mid) >= k:
hi = mid
else:
lo = mid + 1
return nums[lo - 1] + k - missing(lo - 1)