1539. Kth Missing Positive Number
Problem
arr is a strictly increasing array of positive integers. Return the k-th positive integer that is missing from it.
Example: arr = [2,3,4,7,11], k = 5 → 9 (missing: 1, 5, 6, 8, 9, …)
Constraints: follow-up: better than O(n).
Missing count before index i is arr[i] − (i + 1) (monotonic). Find the first index where it is ≥ k; the answer is lo + k.
Complexity: O(log n).
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
lo, hi = 0, len(arr)
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] - (mid + 1) >= k:
hi = mid
else:
lo = mid + 1
return lo + k
assert Solution().findKthPositive([2, 3, 4, 7, 11], 5) == 9
assert Solution().findKthPositive([1, 2, 3, 4], 2) == 6
class Solution {
public int findKthPositive(int[] arr, int k) {
int lo = 0, hi = arr.length;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (arr[mid] - (mid + 1) >= k) hi = mid; else lo = mid + 1;
}
return lo + k;
}
}
func findKthPositive(arr []int, k int) int {
lo, hi := 0, len(arr) // first index with arr[i]-(i+1) >= k missing numbers before it
for lo < hi {
mid := lo + (hi-lo)/2
if arr[mid]-(mid+1) >= k {
hi = mid
} else {
lo = mid + 1
}
}
return lo + k
}