Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

The k-th smallest value in a sorted matrix

Medium · Target 25 minutes · Binary search · Type asked atGoogleMetaTwo Sigma

An n × n matrix has every row and every column sorted in non-decreasing order. Return its k-th smallest value, counting repeated values separately (the k-th in sorted order, not the k-th distinct). Use less than O(n²) memory.

Examples

InputOutputWhy
matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 813In order: 1, 5, 9, 10, 11, 12, 13, 13, 15.
matrix = [[-5]], k = 1-5
matrix = [[1,2],[1,3]], k = 21

Constraints

  • 1 ≤ n ≤ 300
  • −10⁹ ≤ matrix[i][j] ≤ 10⁹
  • 1 ≤ k ≤ n²

Hints

Hint 1

A heap of row fronts works in O(k log n). Try a different question: for a value x, how many cells are ≤ x?

Hint 2

Count them with the staircase walk from the bottom-left corner: O(n) for the whole matrix.

Hint 3

count(x) never decreases as x grows. The answer is the smallest x with count(x) ≥ k. Search x between the smallest and largest values.

Where people lose marks

  • Returning a value that is not in the matrix: the search must find the first x with count ≥ k, not any such x.
  • Writing (lo + hi) / 2 in C++, Java or Rust, which truncates toward zero: for lo = −3, hi = −2 it gives −2 = hi, and hi = mid never shrinks the range. lo + (hi − lo) / 2 is the floor whatever the signs.
  • Counting distinct values: the k-th smallest counts repeats.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.