SDE & MLE Prep

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