KatInterview

K-th Smallest Entry in a Row and Column Sorted Grid

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchmatrixheaps-sorting

Last updated

Find the k-th smallest value in a two-dimensional grid where every row and column is sorted in ascending order.

You are given a 2D integer grid matrix of dimension n x m, where every individual row and column is ordered in non-decreasing order. You are also given an integer k.

Find and return the $k$-th smallest element present in the grid when considering all $n \times m$ entries sorted together in non-decreasing order (1-indexed). Duplicates should be counted individually.

Constraints

  • $n == \text{len}(matrix)$
  • $m == \text{len}(matrix[i])$
  • $1 \le n, m \le 300$
  • $-10^9 \le matrix[i][j] \le 10^9$
  • $1 \le k \le n \times m$
  • Each row of matrix is sorted in non-decreasing order.
  • Each column of matrix is sorted in non-decreasing order.

Examples

Example 1

Input: kth_smallest_matrix([[1, 5, 9], [10, 11, 13], [12, 13, 15]], 8)

Output: 13

Example 2

Input: kth_smallest_matrix([[1, 2], [3, 4]], 2)

Output: 2

Example 3

Input: kth_smallest_matrix([[1, 1, 1], [1, 1, 1]], 5)

Output: 1

Hints

Hint 1

The smallest possible value is at the top-left corner matrix[0][0] and the largest is at the bottom-right corner matrix[-1][-1].

Hint 2

Can you search over the range of potential values [min_val, max_val] using binary search?

Hint 3

For a candidate midpoint x, count how many elements in the matrix are less than or equal to x. Because rows are sorted, binary search (or a staircase traversal) can count this efficiently.