Data Structures & AlgorithmsVery hardProduct company OA
Problem: A 3 × 3 matrix has every row and column sorted ascending. Find the k-th smallest value by binary searching on the VALUE and counting entries ≤ mid.
Problem: A 3 × 3 matrix has every row and column sorted ascending. Find the k-th smallest value by binary searching on the VALUE and counting entries ≤ mid.
from bisect import bisect_right
def kth(m, k):
lo, hi = m[0][0], m[-1][-1]
while lo < hi:
mid = (lo + hi) // 2
if sum(bisect_right(row, mid) for row in m) >= k:
hi = mid
else:
lo = mid + 1
return lo
m = [[2, 6, 8], [3, 7, 10], [5, 9, 14]]
print(kth(m, 4), kth(m, 7), kth(m, 9))What is printed?- A. 6 8 14
- B. 3 7 14
- C. 6 9 14
- D. 7 9 14
Correct answer: C. 6 9 14
count(v) = number of entries ≤ v is monotone in v, so find the smallest v with count(v) ≥ k; that v is always an actual entry. Sorted values: 2, 3, 5, 6, 7, 8, 9, 10, 14 → 4th = 6, 7th = 9, 9th = 14. Reading the matrix row by row (the trap) gives 7 for k = 4. Complexity O(n log n · log(range)) here; a staircase count makes it O(n · log range).
More Coding Interview Problems questions
- Problem: Each move removes either the leftmost or the rightmost box and subtracts its weight from x. Find the minimum moves to make x…
- Problem: A speech-analysis tool reports the maximum number of vowels in any window of exactly k consecutive letters. python def…
- Problem: Move all zero readings to the end of the array in place while keeping the order of the non-zero readings. python def…
- Problem: In a text editor '#' means backspace (on an empty buffer it does nothing). Compute the final text with a stack. python def…
- Problem: Normalise a Unix-style absolute path: collapse repeated slashes, drop '.', and let '..' go up one directory (never above root)…
- Problem: Find the minimum number of brackets to insert so that a string of '(' and ')' becomes balanced. python def minadd(s): open = add…