Kth Missing Positive Number Problem
Description
LeetCode Problem 1539. Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
Find the kth positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
Solution
Approach: Binary Search on the Missing Count
A linear scan works, but the array is sorted, so we can binary search.
If nothing were missing, index i would hold the value i + 1. So the number of positive integers missing before arr[i] is
missing(i) = arr[i] - (i + 1).
This count never decreases as i grows, because the values are strictly increasing. Binary search for low, the first index with missing(low) >= k; if there is none, low = len(arr).
Then the answer is k + low. All low numbers before that index are smaller than the answer, and fewer than k integers are missing below arr[low - 1]. Counting up from 1, we pass exactly low numbers that are in arr and k that are not, so we land on k + low.
Check with arr = [2,3,4,7,11], k = 5: the missing counts are [1,1,1,3,6], so low = 4 and the answer is 5 + 4 = 9.
The edge case is when every missing count is below k, as in arr = [1,2,3,4], k = 2. Then low is the length of the array, 4, and the formula still gives 2 + 4 = 6; letting high start at len(arr) handles this without a special case.
Complexity: O(log n) time and O(1) space, where n is the length of arr.
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
# Before index i, arr[i] - (i + 1) positive integers are missing.
# Find the first index where at least k are missing.
low, high = 0, len(arr)
while low < high:
mid = (low + high) // 2
if arr[mid] - (mid + 1) < k:
low = mid + 1
else:
high = mid
# low numbers of arr come before the answer, so it is k + low.
return k + low
Now write it from memory
Close the write-up and solve it yourself against the tests.