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?
  1. A. 6 8 14
  2. B. 3 7 14
  3. C. 6 9 14
  4. 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

Exams that ask this topic