Kth Smallest Element in a Sorted Matrix

MediumK-Way Merge · Binary Search on Value🧩 K-Way MergeLeetCode #378 ↗Updated

Problem

An n x n matrix has every row and every column sorted in non-decreasing order. Return the k-th smallest value in the whole matrix, counting duplicates (it is the k-th element of the sorted multiset, not the k-th distinct value). Aim for better than O(n2) memory.
Input[[1,5,9],[10,11,13],[12,13,15]], k=8Output13
Input[[-5]], k=1Output-5

1 ≤ n ≤ 300  ·  -109 ≤ matrix[i][j] ≤ 109  ·  1 ≤ k ≤ n2  ·  Follow-up: O(1) extra memory?

Try it yourself

Java
class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Search the value range, not the indices. For any value x you can count entries ≤ x in O(n) by walking a staircase from the bottom-left corner; the answer is the smallest x with count ≥ k.
PatternK-Way Merge

Instinct Several sorted lists, rows or streams and you need the global order, the k-th smallest or a range: keep one cursor per list in a min-heap.

Memory hack Line up the heads, crown the smallest, then let its next-in-line step up.

Open the K-Way Merge guide →

Approaches

Brute ForceFlatten & Sort

Time O(n2 log n)Space O(n2)

Ignore the sorted structure: copy all n2 values into one array, sort it, and read index k-1.

Java
public int kthSmallest(int[][] matrix, int k) {
    int n = matrix.length, idx = 0;
    int[] all = new int[n * n];
    for (int[] row : matrix) {
        for (int v : row) all[idx++] = v;
    }
    Arrays.sort(all);
    return all[k - 1];
}

Trivial and correct, but wastes the sortedness and stores every cell.

At a glance

LevelApproachTimeSpace
Brute ForceFlatten & SortO(n2 log n)O(n2)
BetterMin-Heap K-Way MergeO(k log n)O(n)
OptimalBinary Search on Value + Staircase CountO(n log(max−min))O(1)
Common pitfalls
  • mid = lo + (hi - lo) / 2 overflows int when values span ±109.
  • Returning the first mid whose count equals k — it may not be in the matrix.
  • Heap comparator a[0] - b[0] overflows on large negative/positive values.
Interview tips
  • Start with flatten-and-sort, then point out each row is a sorted list (k-way merge).
  • Explain why lo ends on a real matrix value (smallest x with count ≥ k).
  • Draw the staircase count — same walk as Search a 2D Matrix II (240).
Pattern
Binary search on the answer + monotone count → k-th smallest in sorted rows/columns or pair sums.
My notes saved in this browser