[LeetCode] Kth Smallest Element in a Sorted Matrix

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, 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).

  • Time : (logn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int l = matrix[0][0], r = matrix.back().back(), n = matrix.size();
while(l < r) {
int m = l + (r - l) / 2, cnt = 0;
for(int i = 0; i < n; i++) {
cnt += upper_bound(matrix[i].begin(), matrix[i].end(), m) - matrix[i].begin();
}
if(cnt < k) l = m + 1;
else r = m;
}
return l;
}
};
  • Time : O(nk)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
for(int i = 0; i < n; i++) {
reverse(matrix[i].begin(), matrix[i].end());
}
while(k--) {
int selectedI = INT_MAX, mi = INT_MAX;
for(int i = 0; i < n; i++) {
if(matrix[i].empty()) continue;
if(matrix[i].back() < mi) {
mi = matrix[i].back();
selectedI = i;
}
}
if(!k) return mi;
matrix[selectedI].pop_back();
}
return -1;
}
};
  • Time : O(klogn)
  • Space : O(k)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
multimap<int, pair<int, int>> mm;
for(int i = 0; i < matrix.size(); i++)
mm.insert({matrix[i][0], {i,0}});
while(k--) {
auto mi = mm.begin();
if(!k) return mi->first;

int n = mi->second.first, m = mi->second.second + 1;
if(matrix[n].size() > m)
mm.insert({matrix[n][m], {n,m}});
mm.erase(mi);
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/kth-smallest-element-in-a-sorted-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.