import heapq
def kthSmallest(mat, k):
# create a max heap with first row of elements
heap = []
for i in range(len(mat[0])):
heapq.heappush(heap, (-mat[0][i], 0, i))
# pop k-1 smallest elements from the heap
for i in range(k-1):
num, row, col = heapq.heappop(heap)
# add next element from the same row
if row < len(mat)-1:
heapq.heappush(heap, (-mat[row+1][col], row+1, col))
# the kth smallest element is now at the top of the heap
return -heapq.heappop(heap)[0]+1
mat = [[10, 25, 20, 40],
[15, 45, 35, 30],
[24, 29, 37, 48],
[32, 33, 39, 50]]
k = 7
print("Kth smallest element is:", kthSmallest(mat, k))