Leetcode 378. Kth Smallest Element in a Sorted Matrix
Given an n x n
matrix where each of the rows and columns is sorted in ascending order, find the kth smallest element in the matrix.
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
]
k = 8
Output: 13
n
(the dimensions of the matrix)?k
.k
times.#include <vector>
#include <queue>
#include <tuple>
using namespace std;
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
// Min-heap to store elements as (value, row, col)
auto comp = [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) {
return get<0>(a) > get<0>(b);
};
priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, decltype(comp)> minHeap(comp);
int n = matrix.size();
// Initialize the heap with first element of each row.
for (int r = 0; r < min(n, k); ++r) {
minHeap.push({matrix[r][0], r, 0});
}
int value = 0;
for (int i = 0; i < k; ++i) {
auto [val, r, c] = minHeap.top();
minHeap.pop();
value = val;
if (c + 1 < n) {
// Push the next element in the row into the heap.
minHeap.push({matrix[r][c + 1], r, c + 1});
}
}
return value;
}
};
O(min(k, n))
to push the first elements of each row into the heap.O(k log(min(k, n)))
for k
operations (pop and push).
O(log min(k, n))
time.Hence, the overall time complexity is O(k log(min(k, n)))
.
This method ensures efficiency by leveraging the properties of a heap to manage a dynamic set of elements efficiently.
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?