KatInterview

K-th Value in a Row-and-Column Sorted Grid

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchmatrixheap

Last updated

Tests binary search on value space combined with an O(n) staircase count to efficiently locate the k-th smallest element in a doubly sorted matrix.

Problem

You are given an n × n grid of integers called grid, where every row is sorted in nondecreasing order left to right, and every column is sorted in nondecreasing order top to bottom.

Given a 1-indexed integer k, return the element that would appear at position k if every value in the grid were listed in one sorted sequence. Duplicate values occupy separate positions in that sequence.

For example, in [[1,2],[2,3]] with k = 3, the sorted sequence is [1, 2, 2, 3], so the answer is 2.


Two Approaches to Consider

Approach 1 — Min-Heap over row fronts

Each row is independently sorted, so the grid can be treated as n sorted lists being merged:

  • Seed a min-heap with the first element of each row (up to min(n, k) rows).
  • Pop the minimum k − 1 times; each time a value at column c is popped from row r, push the next element in that row (c + 1) if it exists.
  • The top of the heap after k − 1 pops is the answer.

This runs in O(k log min(n, k)) time and O(min(n, k)) space. It works even without column-sorted order, but that means it leaves performance on the table.

Approach 2 — Binary search on the value range

Define count(x) as the number of grid entries that are ≤ x. Because the grid is doubly sorted, count is nondecreasing in x. Binary search on the interval [grid[0][0], grid[n-1][n-1]] for the smallest value x where count(x) ≥ k.

count(mid) can be computed in O(n) using a staircase walk starting from the bottom-left corner (n-1, 0):

  • If grid[row][col] ≤ mid, every cell above it in that column is also ≤ mid (column is sorted), so add row + 1 to the count and move right.
  • If grid[row][col] > mid, every cell to the right in that row is also > mid (row is sorted), so move up.

Each step moves either right or up, so the walk completes in at most 2n steps.

Binary search over the value range runs in O(n · log(max − min)) time and O(1) extra space.


Correctness of the Binary Search Termination

The loop maintains the invariant that the true answer always lies in [lo, hi]:

  • If count(mid) < k, all values ≤ mid are too few, so the answer is strictly greater: set lo = mid + 1.
  • If count(mid) ≥ k, mid itself could be the answer, so set hi = mid (do not exclude it).

When the loop ends, lo == hi. That value is guaranteed to be an actual element of the grid. If it were not, then count(lo − 1) would equal count(lo) ≥ k, contradicting lo being the smallest such value. This argument relies on values being integers.


Constraints

  • 1 ≤ n ≤ 300
  • n == len(grid) == len(grid[i]) for all i
  • -10^9 ≤ grid[i][j] ≤ 10^9
  • Each row and each column of grid is sorted in nondecreasing order
  • 1 ≤ k ≤ n^2

Examples

Example 1

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

Output: 13

Example 2

Input: kth_value_in_sorted_grid([[-5, -4], [-3, 2]], 3)

Output: -3

Example 3

Input: kth_value_in_sorted_grid([[1, 2, 2], [2, 2, 3], [2, 3, 4]], 5)

Output: 2

Hints

Hint 1

Rather than sorting all n² values, think about what property is monotonic across the grid's value range — something you can binary search on directly.

Hint 2

To count how many values in the grid are ≤ some midpoint, try starting at the bottom-left corner and walking either right or upward depending on how each cell compares to mid. How many steps does this walk take at most?

Hint 3

When the binary search loop exits with lo == hi, you need that result to be an actual grid element, not just an arbitrary integer. Think about why count(lo - 1) < k must hold, and what that tells you about whether lo appears in the grid.