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?- A. 12
- B. 10
- C. 14
- 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
- Problem: Find the area of the largest square of 1s in a binary matrix. python def square(m): R, C = len(m), len(m[0]); dp = [[0] (C + 1)…
- Problem: Length of the longest common CONTIGUOUS subarray of two arrays (DP on suffix matches). python def common(a, b): dp = [[0] (len(b)…
- Problem: A knight makes k uniformly random moves (8 directions) on an n × n board; once it leaves the board it stays off. What is the…
- Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack). python def most(strs…
- Problem: Delete characters from two strings so they become equal, minimising the sum of ASCII codes deleted. python def cost(a, b): m, n =…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Report (first player's total) − (second…