Skip to main content

378. Kth Smallest Element in a Sorted Matrix

Python

Min Heap

  • Time: O(N*M)
  • Space: O(N*M)
import heapq


class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
heap = []
for row in matrix:
for num in row:
heapq.heappush(heap, num)

return heapq.nsmallest(k, heap)[-1]