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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int KthSmallest(int[][] matrix, int k) {
6 int n = matrix.Length;
7 PriorityQueue<(int val, int r, int c), int> minHeap = new PriorityQueue<(int val, int r, int c), int>();
8
9 for (int i = 0; i < Math.Min(n, k); i++)
10 minHeap.Enqueue((matrix[i][0], i, 0), matrix[i][0]);
11
12 int number = 0;
13 while (k-- > 0) {
14 var (value, r, c) = minHeap.Dequeue();
15 number = value;
16 if (c < n - 1)
17 minHeap.Enqueue((matrix[r][c + 1], r, c + 1), matrix[r][c + 1]);
18 }
19
20 return number;
21 }
22}
The C# solution establishes an ordered priority queue where it pushes in initial columns' elements and relies upon dequeueing to progressively consume smallest elements as dictated by natural order in the matrix. As with other solutions, managing elements this way ensures accessing upcoming relevant row entries until the k-th smallest is detected, which becomes the final return value.
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.