1060. Missing Element in Sorted Array π
Description
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 kth 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 * 1041 <= nums[i] <= 107numsis sorted in ascending order, and all the elements are unique.1 <= k <= 108
Follow up: Can you find a logarithmic time complexity (i.e., O(log(n))) solution?
Solutions
Solution 1
Thinking
The array is sorted and distinct, so the number of missing values before index \(i\) is \(nums[i]-nums[0]-i\). A linear walk finds the \(k\)-th missing, but the follow-up asks for logarithmic time.
\(\textit{missing}(i)\) is increasing. If \(k\) exceeds the missing count at the end, the answer lies past the array; otherwise we bisect the least \(i\) with \(\textit{missing}(i)\ge k\) and add the leftover gap to \(nums[i-1]\).
The search range is \([0,n-1]\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |