LeetCode #378 Medium

Kth Smallest Element in a Sorted Matrix

Kth Smallest Element in a Sorted Matrix is LeetCode 378 (Medium). You get an n x n matrix whose every row and every column is sorted in non-decreasing order, and an integer k. Return the kth smallest value in the whole matrix.

  • It is the kth value in sorted order, not the kth distinct value: repeated numbers count once per copy.
  • The solution must use less than O(n²) memory, so copying all the values into one list and sorting it is not allowed.
  • Values can be negative, down to -10⁹.
Constraints
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 300
  • -10⁹ <= matrix[i][j] <= 10⁹
  • All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
  • 1 <= k <= n²
heapbinary-searchmatrix
Open on LeetCode ↗
02

Intuition

Rows and columns are sorted, but the matrix as a whole is not, so you cannot jump to position k. Binary search on the value instead. For any guess x, count how many cells are at most x. That count only grows as x grows, so the answer is the smallest x whose count reaches k.

The count is cheap because of the sorting:

  • Start at the bottom-left cell. If it is at most x, so is everything above it, and the whole column counts at once; move right.
  • If it is bigger than x, so is everything to its right, and that row is done; move up.

Each move retires a row or a column, so one count takes at most 2n moves.

How to spot this pattern

When a structure is too awkward to index but easy to count against, binary search on the answer's value: guess, count how many items are at most the guess, and shrink the range. The same move solves Median in a Row-Wise Sorted Matrix and Find K-th Smallest Pair Distance.

03

Approach

Try it first

Before reading on, take the guess 12 for the matrix [[1, 5, 9], [10, 11, 13], [12, 13, 15]] and count the cells at most 12 without checking all nine. Which corner lets every comparison settle a whole row or column? Then decide how that count tells you whether the 8th smallest is above or below 12.

1

Set the value range

The smallest value is matrix[0][0] and the largest is matrix[n-1][n-1], so set lo and hi to them. The answer is always inside [lo, hi], and every step keeps it there.

2

Count the cells at most mid

Start at row n - 1, column 0. If the cell is at most mid, add r + 1 for the column above it and move right; otherwise move up. Stop when you leave the grid. Each move discards a whole row or column, which keeps a count at O(n).

3

Shrink the range

With mid = lo + (hi - lo) // 2: if the count is at least k, the kth smallest is mid or less, so set hi = mid and keep mid as a candidate. Otherwise it is bigger than mid, so set lo = mid + 1.

4

Return when the range is one value

When lo == hi, that value is the smallest number with at least k cells at most it, which is exactly the kth smallest. Return lo.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
▶3 n = len(matrix)
▶4 
▶5 def count_at_most(x):
▶6 count, r, c = 0, n - 1, 0
▶7 while r >= 0 and c < n:
▶8 if matrix[r][c] <= x:
▶9 count += r + 1
▶10 c += 1
▶11 else:
▶12 r -= 1
▶13 return count
▶14 
▶15 lo, hi = matrix[0][0], matrix[-1][-1]
▶16 while lo < hi:
▶17 mid = lo + (hi - lo) // 2
▶18 if count_at_most(mid) >= k:
▶19 hi = mid
▶20 else:
▶21 lo = mid + 1
▶22 return lo
matrix151011range1lo11hicellcountvs2ksearch values 1 to 11, the two corners
lo1
hi11
k2
The smallest value sits top-left and the largest bottom-right, so the answer lies in [1, 11]. The search runs over values, not positions: for a guess mid, count the cells ≤ mid.
matrix151011range1lo6mid11hicell10>6count0vs2kguess 6: 10 > 6 → move up
mid6
cell10row 1, col 0
count0
Guess mid = 6 and count from the bottom-left corner. 10 > 6, and everything to its right in this row is bigger still, so the rest of row 1 is ruled out. Move up a row.
matrix151011range1lo6mid11hicell1≤6count1vs2k1 ≤ 6 → +1, move right
mid6
cell1row 0, col 0
count1
1 ≤ 6, so this cell counts: +1. Move right to the next column.
matrix151011range1lo6mid11hicell5≤6count2vs2k5 ≤ 6 → +1, move right
mid6
cell5row 0, col 1
count2
5 ≤ 6, so this cell counts: +1. Move right to the next column.
matrix151011range1lo6mid6hicellcount2≥2k2 cells ≤ 6 → answer is 6 or less
count2cells ≤ 6
lo1
hi6
2 cells are ≤ 6, at least k = 2, so the kth smallest is 6 or less. Keep mid as a candidate: hi = 6. The range shrinks from [1, 11] to [1, 6].
matrix151011range1lo3mid6hicell10>3count0vs2kguess 3: 10 > 3 → move up
mid3
cell10row 1, col 0
count0
Guess mid = 3 and count from the bottom-left corner. 10 > 3, and everything to its right in this row is bigger still, so the rest of row 1 is ruled out. Move up a row.
matrix151011range1lo3mid6hicell1≤3count1vs2k1 ≤ 3 → +1, move right
mid3
cell1row 0, col 0
count1
1 ≤ 3, so this cell counts: +1. Move right to the next column.
matrix151011range1lo3mid6hicell5>3count1vs2k5 > 3 → move up
mid3
cell5row 0, col 1
count1
5 > 3, and everything to its right in this row is bigger still, so the rest of row 0 is ruled out. Move up a row.
matrix151011range4lo3mid6hicellcount1<2k1 cell ≤ 3 → answer is above 3
count1cells ≤ 3
lo4
hi6
Only 1 cell is ≤ 3, fewer than k = 2, so the kth smallest is bigger than 3: lo = 4. The range shrinks from [1, 6] to [4, 6].
matrix151011range4lo5mid6hicell10>5count0vs2kguess 5: 10 > 5 → move up
mid5
cell10row 1, col 0
count0
Guess mid = 5 and count from the bottom-left corner. 10 > 5, and everything to its right in this row is bigger still, so the rest of row 1 is ruled out. Move up a row.
matrix151011range4lo5mid6hicell1≤5count1vs2k1 ≤ 5 → +1, move right
mid5
cell1row 0, col 0
count1
1 ≤ 5, so this cell counts: +1. Move right to the next column.
matrix151011range4lo5mid6hicell5≤5count2vs2k5 ≤ 5 → +1, move right
mid5
cell5row 0, col 1
count2
5 ≤ 5, so this cell counts: +1. Move right to the next column.
matrix151011range4lo5mid5hicellcount2≥2k2 cells ≤ 5 → answer is 5 or less
count2cells ≤ 5
lo4
hi5
2 cells are ≤ 5, at least k = 2, so the kth smallest is 5 or less. Keep mid as a candidate: hi = 5. The range shrinks from [4, 6] to [4, 5].
matrix151011range4lo4mid5hicell10>4count0vs2kguess 4: 10 > 4 → move up
mid4
cell10row 1, col 0
count0
Guess mid = 4 and count from the bottom-left corner. 10 > 4, and everything to its right in this row is bigger still, so the rest of row 1 is ruled out. Move up a row.
matrix151011range4lo4mid5hicell1≤4count1vs2k1 ≤ 4 → +1, move right
mid4
cell1row 0, col 0
count1
1 ≤ 4, so this cell counts: +1. Move right to the next column.
matrix151011range4lo4mid5hicell5>4count1vs2k5 > 4 → move up
mid4
cell5row 0, col 1
count1
5 > 4, and everything to its right in this row is bigger still, so the rest of row 0 is ruled out. Move up a row.
matrix151011range5lo4mid5hicellcount1<2k1 cell ≤ 4 → answer is above 4
count1cells ≤ 4
lo5
hi5
Only 1 cell is ≤ 4, fewer than k = 2, so the kth smallest is bigger than 4: lo = 5. The range shrinks from [4, 5] to [5, 5].
matrix151011range5lo5hicellcountvs2krange closed on 5 → answer 5
lo5
hi5
result5
The range has closed on one value, 5: the smallest number with at least 2 cells ≤ it. That number must sit in the matrix (highlighted), because any value not in the matrix has the same count as the value just below it.
05

Min-heap over the rows

Each row is a sorted list, so the matrix is n lists to merge. Start the heap with the first cell of every row. Each pop gives the next smallest value overall; then push the cell to its right in the same row. The kth pop is the answer, and the heap never holds more than n cells.

▶1import heapq
▶2 
▶3class Solution:
▶4 def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
▶5 n = len(matrix)
▶6 heap = [(matrix[r][0], r, 0) for r in range(n)]
▶7 heapq.heapify(heap)
▶8 for _ in range(k - 1):
▶9 _, r, c = heapq.heappop(heap)
▶10 if c + 1 < n:
▶11 heapq.heappush(heap, (matrix[r][c + 1], r, c + 1))
▶12 return heap[0][0]
06

Common pitfalls

Returning mid as soon as the count equals k

✗ Wrong
if count_at_most(mid) == k:
    return mid
✓ Right
if count_at_most(mid) >= k:
    hi = mid
else:
    lo = mid + 1

mid is any number in the range, not necessarily a cell. For [[1, 5], [10, 11]] with k = 2, the first guess is 6 and two cells are at most 6, so this returns 6; the answer is 5.

Testing count > k instead of count >= k

✗ Wrong
if count_at_most(mid) > k:
    hi = mid
✓ Right
if count_at_most(mid) >= k:
    hi = mid

A count of exactly k means mid could be the answer, so it must stay in the range. For [[1, 2], [1, 3]] with k = 2, three cells are at most 2 and two are at most 1, so the strict test moves lo past 1 and returns 2; the answer is 1.

Computing mid as (lo + hi) / 2 in C++ or Java

✗ Wrong
int mid = (lo + hi) / 2;
✓ Right
int mid = lo + (hi - lo) / 2;

Integer division rounds toward zero, so with negative values mid can land on hi. For [[-3, -2], [-2, -2]] with k = 1, lo = -3, hi = -2 gives mid = -2 forever and the loop never ends. Python's // rounds down, so this one is a C++ and Java trap.

07

Edge cases

A 1 x 1 matrix

lo and hi start equal, the loop never runs, and the single value is returned.

k = 1 or k = n²

The range closes on matrix[0][0] or matrix[n-1][n-1], the two corners. No special case is needed, since both are inside the starting range.

08

Complexity

Time
O(n log(max − min))
Space
O(1)
max − min is the gap between the bottom-right and top-left values, at most 2·10⁹, so the range halves about 31 times. Each halving runs one staircase count of at most 2n moves, and only a few integers are stored.
09

Kth Smallest Element in a Sorted Matrix FAQ

Why is the returned value always in the matrix?

The loop ends on the smallest x with at least k cells at most x. Suppose no cell equals x. Then the cells at most x are the same cells as those at most x - 1, so x - 1 also has at least k, and x was not the smallest. That contradiction means some cell holds x.

Why start the count at the bottom-left corner?

From there, moving up always gives a smaller value and moving right always gives a bigger one, so each comparison settles a whole column or a whole row. The top-right corner works the same way. From the top-left, both moves give bigger values, so a comparison tells you nothing about which way to go.

Can it be done in O(n) time?

Yes, with a selection algorithm by Frederickson and Johnson that works on sorted matrices, but it is long and rarely asked. In interviews, binary search on the value or the min-heap is expected.