---
# System prepended metadata

title: 378. Kth Smallest Element in a Sorted Matrix

---

# 378. Kth Smallest Element in a Sorted Matrix

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

```
    Example 1:

        matrix = [
           [ 1,  5,  9],
           [10, 11, 13],
           [12, 13, 15]
        ],
        k = 8,

        return 13.
```
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.


```
min heap:
1
12
output:
1,5,9,
```


### Approach
```python=
import heapq
def smallest(matrix, k):
    count = 0
    myheap = [(matrix[row][0], row, 0) for row in range(len(matrix))]
    heapq.heapify(myheap)
    result = -1
    while count < k:
        ele, row, col = heappop(myheap)
        count += 1
        if count == k:
            result = ele
        if row < len(matrix) and col < len(matrix[0]) - 1:
            myheap = heappush([matrix[row][col + 1], row, col + 1])
        else:
            break
    
    return result
```