K-th Value in a Row-and-Column Sorted Grid
Heaps, Sorting & SearchAuto-graded · 19 test casesLast 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 − 1times; each time a value at columncis popped from rowr, push the next element in that row (c + 1) if it exists. - The top of the heap after
k − 1pops 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 addrow + 1to 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: setlo = mid + 1. - If
count(mid) ≥ k, mid itself could be the answer, so sethi = 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 ≤ 300n == len(grid) == len(grid[i])for alli-10^9 ≤ grid[i][j] ≤ 10^9- Each row and each column of
gridis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why binary search on values works
Sorting all n² entries would take O(n² log n) time and O(n²) space, ignoring the sorted structure entirely. The key insight is that count(x) — the number of grid entries ≤ x — is nondecreasing as x grows. That monotonicity is exactly what binary search requires.
The goal becomes: find the smallest integer x in the range [grid[0][0], grid[n-1][n-1]] such that count(x) ≥ k. Binary search halves this interval each iteration.
The O(n) staircase count
Naively counting entries ≤ mid row-by-row with binary search costs O(n log n) per iteration. We can do better by exploiting both the row and column ordering simultaneously.
Start at the bottom-left corner (n-1, 0) and walk:
grid[row][col] ≤ mid→ every cell in this column from row 0 to rowrowis also ≤ mid (column sorted). Addrow + 1to the count and step right.grid[row][col] > mid→ every cell in this row from col to coln-1is also ≥ mid (row sorted), so this whole section is irrelevant. Step up.
Each move strictly advances either the column or the row, so the walk terminates in at most 2n steps.
Why lo is always a real grid element
When the loop ends, lo == hi. Suppose this value did not appear anywhere in the grid. Then count(lo - 1) = count(lo) ≥ k, which means lo - 1 also satisfies the predicate — but the binary search was looking for the smallest such value, so lo could have been set lower. That is a contradiction. Therefore lo must exist in the grid, and because elements are integers, it is precisely the k-th smallest value.
Binary search boundary choices
- When
count(mid) < k: too few values are ≤ mid, so the answer is strictly larger. Setlo = mid + 1. - When
count(mid) ≥ k: mid is a valid candidate. Sethi = mid— never exclude it. - The loop condition
lo < hicombined withmid = lo + (hi - lo) // 2(which floors towardlo) guaranteesmid < hialways, sohistrictly decreases andlostrictly increases each iteration, ensuring termination.
Edge cases
n = 1:lo == hiat the start; the loop never runs andlois returned immediately.k = 1ork = n²: the search naturally converges togrid[0][0]orgrid[-1][-1].- Duplicates: counting with
≤handles them correctly. In[[1,1],[1,2]]withk = 3,count(1) = 3 ≥ 3and the answer is1. - Negative values:
lo + (hi - lo) // 2stays in range and Python's floor division handles negatives correctly.
Complexity
| Approach | Time | Space |
|---|---|---|
| Flatten and sort | O(n² log n) | O(n²) |
| Min-heap over row fronts | O(k log min(n, k)) | O(min(n, k)) |
| Value-space binary search | O(n · log(max − min)) | O(1) |
The binary search performs at most log₂(max − min) iterations (≤ 60 for 32-bit integers), each costing O(n). It does not depend on k and uses constant extra space, making it the strongest general solution.
The heap can be preferable when k is very small relative to n, when the value range is enormous, or when values are not integers (the "result is a real element" proof breaks for floats).
Full solution
from typing import List
def kth_value_in_sorted_grid(grid: List[List[int]], k: int) -> int:
n = len(grid)
lo = grid[0][0] # smallest possible answer
hi = grid[-1][-1] # largest possible answer
while lo < hi:
mid = lo + (hi - lo) // 2
# O(n) staircase count: how many entries are <= mid?
count = 0
row = n - 1
col = 0
while row >= 0 and col < n:
if grid[row][col] <= mid:
# grid[0][col] through grid[row][col] are all <= mid
count += row + 1
col += 1
else:
row -= 1
if count < k:
lo = mid + 1 # answer is strictly greater than mid
else:
hi = mid # mid is a candidate; do not exclude it
return lo