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?- A. 6 5 3
- B. 7 5 3
- C. 6 5 7
- 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
- Problem: Find the minimum of a rotated sorted array that may contain DUPLICATES. python def findmin(a): lo, hi = 0, len(a) - 1 while lo <…
- Problem: Arrange non-negative integers so that their concatenation forms the largest number (returned as a string). Sort with the…
- Problem: A company sends 2n candidates to two interview centres, n to each; costs[i] = (cost at A, cost at B). Minimise the total cost by…
- Problem: Delete the fewest characters so that no two distinct letters have the same (non-zero) frequency. python from collections import…
- Problem: Does an array contain indices i < j < k with a[i] < a[j] < a[k]? An O(n), O(1) greedy keeps the smallest 'first' and the smallest…
- Problem: Can a hand of cards be split into groups of exactly w consecutive values? Greedily start groups at the smallest remaining card…