Given an n x n
matrix where each of the rows and columns is sorted in ascending order, find the k
th smallest element in the matrix.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
]
k = 8
Output: 13
Note:
k
is always valid, 1 ≤ k ≤ n^2.n
?k
th smallest elements (duplicates), should we return any specific one or the problem guarantees that there won’t be such cases?k
times.mid
value in the given range and count how many elements in the matrix are less than or equal to mid
.Here, we will implement the Heap Approach using Python’s heapq
library for brevity and ease of understanding.
import heapq
def kthSmallest(matrix, k):
n = len(matrix)
min_heap = []
# Initialize min heap with the first element from each row.
for r in range(min(len(matrix), k)): # Only need the first min(len(matrix), k)
heapq.heappush(min_heap, (matrix[r][0], r, 0))
# Extract min element from heap k times
while k:
element, r, c = heapq.heappop(min_heap)
if c < n - 1:
heapq.heappush(min_heap, (matrix[r][c+1], r, c+1))
k -= 1
return element
# Example usage:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
]
k = 8
print(kthSmallest(matrix, k)) # Output should be 13
k
operations, it’s O(k * log(min(k, n))).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?