Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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)
.
Example 1:
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
Example 2:
Input: matrix = [[-5]], k = 1
Output: -5
Constraints:
n == matrix.length == matrix[i].length
1 <= n <= 300
-109 <= matrix[i][j] <= 109
matrix
are guaranteed to be sorted in non-decreasing order.1 <= k <= n2
Follow up:
O(1)
memory complexity)?O(n)
time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.public class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
for(int j = 0; j <= n-1; j++) pq.offer(new Tuple(0, j, matrix[0][j]));
for(int i = 0; i < k-1; i++) {
Tuple t = pq.poll();
if(t.x == n-1) continue;
pq.offer(new Tuple(t.x+1, t.y, matrix[t.x+1][t.y]));
}
return pq.poll().val;
}
}
class Tuple implements Comparable<Tuple> {
int x, y, val;
public Tuple (int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}
@Override
public int compareTo (Tuple that) {
return this.val - that.val;
}
}
class Solution
{
public:
int kthSmallest(vector<vector<int>>& matrix, int k)
{
int n = matrix.size();
int le = matrix[0][0], ri = matrix[n - 1][n - 1];
int mid = 0;
while (le < ri)
{
mid = le + (ri-le)/2;
int num = 0;
for (int i = 0; i < n; i++)
{
int pos = upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
num += pos;
}
if (num < k)
{
le = mid + 1;
}
else
{
ri = mid;
}
}
return le;
}
};
class Solution(object):
def kthSmallest(self, matrix, k):
lo, hi = matrix[0][0], matrix[-1][-1]
while lo<hi:
mid = (lo+hi)//2
if sum(bisect.bisect_right(row, mid) for row in matrix) < k:
lo = mid+1
else:
hi = mid
return lo
In our experience, we suggest you solve this Kth Smallest Element in a Sorted Matrix LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Kth Smallest Element in a Sorted Matrix LeetCode Solution
I hope this Kth Smallest Element in a Sorted Matrix LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>