378. Kth Smallest Element in a Sorted Matrix
Asked at 11Meta57Apple35Amazon34Google26Microsoft25Bloomberg14X94PhonePe64Oracle41TikTok26Goldman Sachs21
Problem
In the n×n matrix, every row and every column is sorted ascending. Return the k-th smallest element in sorted order (duplicates count), using less than O(n²) memory.
Example: [[1,5,9],[10,11,13],[12,13,15]], k = 8 → 13
Constraints: n ≤ 300.
Rows are sorted lists → k-way merge: heap seeded with each row's first element; pop k−1 times, pushing the next in the same row. (Alt: binary search on value + count ≤ mid staircase, O(n log range).)
Complexity: O(k log n).
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
n = len(matrix)
h = [(matrix[r][0], r, 0) for r in range(min(n, k))]
heapify(h)
for _ in range(k - 1):
_, r, c = heappop(h)
if c + 1 < n:
heappush(h, (matrix[r][c + 1], r, c + 1))
return h[0][0]
assert Solution().kthSmallest([[1, 5, 9], [10, 11, 13], [12, 13, 15]], 8) == 13
assert Solution().kthSmallest([[-5]], 1) == -5
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); // {val, r, c}
for (int r = 0; r < Math.min(n, k); r++) pq.add(new int[]{matrix[r][0], r, 0});
for (int i = 0; i < k - 1; i++) {
int[] t = pq.poll();
if (t[2] + 1 < n) pq.add(new int[]{matrix[t[1]][t[2] + 1], t[1], t[2] + 1});
}
return pq.peek()[0];
}
}
type cell struct{ v, r, c int }
type cellHeap []cell
func (h cellHeap) Len() int { return len(h) }
func (h cellHeap) Less(i, j int) bool { return h[i].v < h[j].v }
func (h cellHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *cellHeap) Push(x any) { *h = append(*h, x.(cell)) }
func (h *cellHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func kthSmallest(matrix [][]int, k int) int {
n := len(matrix)
h := &cellHeap{}
for r := 0; r < min(n, k); r++ { // the first column of each row
heap.Push(h, cell{matrix[r][0], r, 0})
}
for i := 0; i < k-1; i++ { // pop k-1 smallest, advancing along their rows
c := heap.Pop(h).(cell)
if c.c+1 < n {
heap.Push(h, cell{matrix[c.r][c.c+1], c.r, c.c + 1})
}
}
return (*h)[0].v
}