Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: In an n × n matrix whose rows and columns are both sorted, find the k-th smallest value by binary searching on the VALUE and counting entries ≤ mid with a staircase walk.

Problem: In an n × n matrix whose rows and columns are both sorted, find the k-th smallest value by binary searching on the VALUE and counting entries ≤ mid with a staircase walk.
def kth(m, k):
    n = len(m); lo, hi = m[0][0], m[-1][-1]
    while lo < hi:
        mid = (lo + hi) // 2
        cnt, r, c = 0, n - 1, 0
        while r >= 0 and c < n:
            if m[r][c] <= mid: cnt += r + 1; c += 1
            else: r -= 1
        if cnt < k: lo = mid + 1
        else: hi = mid
    return lo
print(kth([[2, 6, 8], [3, 7, 10], [5, 9, 12]], 5))
What is printed?
  1. A. 6
  2. B. 8
  3. C. 10
  4. D. 7

Correct answer: D. 7

Sorted values are 2, 3, 5, 6, 7, 8, 9, 10, 12, so the 5th smallest is 7; the search returns the smallest v with count(≤ v) ≥ k, which is always a matrix entry. Counting with < instead of ≤ returns the 6th smallest (8), an off-by-one in k returns the 4th (6), and adding r instead of r + 1 per column undercounts and gives 10.

More Coding Interview Problems questions

Exams that ask this topic