QUESTION
Given an n x n
matrix
where each of the rows and columns is sorted in ascending order, return the kth
smallest element in the matrix.
Note that it is the kth
smallest element in the sorted order, not the kth
distinct element.
You must find a solution with a memory complexity better than O(n2)
.
Example 1:
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13(8TH),15], and the 8th smallest number is 13
Leetcode
SOLUTION
- Treat each row in a matrix as a seprate sorted array, merge the rows uptill K elements and return when the last element poped out of the heap. Similar to Merge K sorted Arrays
- Code
matrix =
[
[1,5,9],
[10,11,13],
[12,13,15]
]
import heapq
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
# treat each row in a matrix as a seprate sorted array
heap = []
# Add all pointers for zero-th index in all rows
# to the heap, along with the number and array.
ROWS = len(matrix)
for i in range(ROWS):
heappush(heap,(matrix[i][0],matrix[i],i,0))
element = -1
for i in range(k):
element, array, row, index = heappop(heap)
nextElementIndex = index + 1
nextElementExists = nextElementIndex < len(matrix[0])
if nextElementExists:
heappush(heap,(matrix[row][nextElementIndex],matrix[row],row,nextElementIndex))
return element