Algo-Sim › Binary Search
Kth Smallest Element in a Sorted Matrix
Medium · Binary Search · step through it in Java, Python and C++ on your own input
Binary search on the value: count the cells ≤ mid with a staircase walk in O(n), and find the smallest value whose count reaches k.
Problem
In the n × n matrix every row and every column is sorted in ascending order. Return the kth smallest value in the whole matrix, counting duplicates (the kth in sorted order, not the kth distinct value). Use less than O(n²) memory.
Constraints
- 1 ≤ n ≤ 300
- -10⁹ ≤ matrix[i][j] ≤ 10⁹
- Rows and columns are sorted ascending
- 1 ≤ k ≤ n²
Edge cases to test
- k = 1 or k = n²
- Many equal values
- Negative values
Follow-up questions
- How does the heap approach compare?
- Pop the smallest k times from a min-heap of row heads: O(k log n). Value binary search is O(n log(max − min)), better when k is large.
- Why is the found value always in the matrix?
- The search returns the smallest value whose count is ≥ k; a value not in the matrix has the same count as the next smaller one, so it can’t be the smallest.
Solution
Java
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int lo = matrix[0][0], hi = matrix[n - 1][n - 1];
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
int count = 0, col = n - 1;
for (int row = 0; row < n; row++) {
while (col >= 0 && matrix[row][col] > mid) col--;
count += col + 1;
}
if (count < k) lo = mid + 1;
else hi = mid;
}
return lo;
}Python
def kth_smallest(matrix, k):
n = len(matrix)
lo, hi = matrix[0][0], matrix[-1][-1]
while lo < hi:
mid = lo + (hi - lo) // 2
count, col = 0, n - 1
for row in range(n):
while col >= 0 and matrix[row][col] > mid: col -= 1
count += col + 1
if count < k: lo = mid + 1
else: hi = mid
return loC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int kthSmallest(vector<vector<int>> &matrix, int k) {
int n = matrix.size();
int lo = matrix[0][0], hi = matrix[n - 1][n - 1];
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
int count = 0, col = n - 1;
for (int row = 0; row < n; row++) {
while (col >= 0 && matrix[row][col] > mid) col--;
count += col + 1;
}
if (count < k) lo = mid + 1;
else hi = mid;
}
return lo;
}
};
More Binary Search problems
- Binary Search (Easy)
- Search Insert Position (Easy)
- Sqrt(x) (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Find Minimum in Rotated Sorted Array (Medium)
- Search in Rotated Sorted Array (Medium)
- Find Peak Element (Medium)
- Single Element in a Sorted Array (Medium)
- Koko Eating Bananas (Medium)
- Allocate Minimum Pages (Hard)
- Median of Two Sorted Arrays (Hard)
- Time Based Key-Value Store (Medium)