Sponsored
Sponsored
By using a min-heap (priority queue), you can efficiently extract the smallest elements one by one. Initially, insert the first element of each row into the heap. Then, repeat the process of extracting the smallest element and inserting the next element from the corresponding row. Continue this until you extract the k-th smallest element.
Time Complexity: O(k log n)
, where n
is the size of each row/column.
Space Complexity: O(n)
, due to the maintained heap.
1import heapq
2
3def kthSmallest(matrix, k):
4 n = len(matrix)
5 min_heap = [(matrix[i][0], i, 0) for i in range(min(n, k))]
6 heapq.heapify(min_heap)
7
8 count, number = 0, 0
9 while k:
10 number, r, c = heapq.heappop(min_heap)
11 if c < n - 1:
12 heapq.heappush(min_heap, (matrix[r][c+1], r, c+1))
13 k -= 1
14 return number
15
16# Example usage
17print(kthSmallest([[1,5,9],[10,11,13],[12,13,15]], 8))
This Python solution also makes use of a min-heap for tracking the smallest elements with respect to the matrix's order. By heappush and heappop operations on a zero-indexed heap, we achieve the desired order through repeated insertions of each sub-sequential next element per row. By the time k
operations are performed, we arrive at the targeted smallest desired element.
This approach uses binary search over the range of possible values in the matrix to find the k-th smallest element. The idea is to repeatedly narrow the range by counting the number of elements in the matrix that are less than or equal to the current middle value. Depending on this count, adjust the binary search range to hone in on the k-th smallest element.
Time Complexity: O(n log(max-min))
, resulting from binary search log sweeps invoking count linear phase.
Space Complexity: O(1)
, since alterations occur in-place within computation limits of primitive variables.
This C solution employs binary search on the matrix's values. By calculating the number of elements less than or equal to the mid-point value in the range, the solution dynamically adjusts search bounds until the k-th smallest is uncovered at the low-end track of the narrowed range. The logic banks on ordered nature without direct sorting.