Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Find the k-th positive integer missing from a strictly increasing array, by binary search on 'missing before index i' = a[i] − (i + 1).

Problem: Find the k-th positive integer missing from a strictly increasing array, by binary search on 'missing before index i' = a[i] − (i + 1).
def kth_missing(a, k):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] - (mid + 1) < k: lo = mid + 1
        else: hi = mid
    return lo + k
print(kth_missing([1, 4, 5, 9, 10, 15], 6))
What is printed?
  1. A. 12
  2. B. 10
  3. C. 14
  4. D. 11

Correct answer: D. 11

Missing numbers are 2, 3, 6, 7, 8, 11, 12, … so the 6th is 11. The search finds lo = 5 (the first index with at least 6 missing before it) and returns lo + k = 11.

More Coding Interview Problems questions

Exams that ask this topic