SDE & MLE Prep

378. Kth Smallest Element in a Sorted Matrix

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]