LeetCode 378: Kth Smallest Element in a Sorted Matrix

link

Sweep line

With row heads in a min-heap, we can traverse the elements in sorted order using sweep line.

Time: \mathcal{O}(n + k \cdot \lg{n}), space: \mathcal{O}(n).

from heapq import heapify, heappush as push, heappop as pop

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        n = len(matrix)
        min_heap = [(row[0], i, 1) for i, row in enumerate(matrix)]
        heapify(min_heap)

        pop_count = k - 1
        while pop_count > 0:
            _, row_index, next_col_index = pop(min_heap)
            if next_col_index < n:
                row = matrix[row_index]
                push(min_heap, (row[next_col_index], row_index, next_col_index + 1))

            pop_count -= 1

        return min_heap[0][0]

Leave a comment