Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: A sorted list of distinct positive IDs has gaps. Find the k-th positive integer missing from it in O(log n): before index i, a[i] − (i + 1) numbers are missing.

Problem: A sorted list of distinct positive IDs has gaps. Find the k-th positive integer missing from it in O(log n): before index i, a[i] − (i + 1) numbers are missing.
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([3, 4, 8, 10, 11], 4), kth_missing([1, 2, 3], 2), kth_missing([5, 6], 3))
What is printed?
  1. A. 6 5 3
  2. B. 7 5 3
  3. C. 6 5 7
  4. D. 6 4 3

Correct answer: A. 6 5 3

Find lo = the number of array values that come before the k-th missing number; the answer is then k + lo. [3, 4, 8, 10, 11]: missing counts 2, 2, 5, 6, 6; the first count ≥ 4 is at index 2, so lo = 2 and the answer is 6 (missing: 1, 2, 5, 6, …). [1, 2, 3] has no gaps → 3 + 2 = 5. [5, 6]: 1, 2, 3 are missing → 3. O(log n).

More Coding Interview Problems questions

Exams that ask this topic