Kth Smallest Element in a Sorted Matrix (LeetCode 378): Solution and Explanation
In an n by n matrix whose rows and columns are both sorted in ascending order, find the value that would be k-th if every element were placed into one sorted list. Duplicates count separately.
Watch it run step by step
Try your own input and write the code →Intuition
The obvious approach is to dump all n² values into a list, sort it, and return the element at index k - 1. That is O(n² log n) time and O(n²) memory, and it ignores that the matrix is already heavily sorted. A min-heap that merges the rows like k sorted lists does better, at O(k log n), but it can still approach n² log n when k is large.
A different angle is to search over values rather than positions. The answer lies somewhere between the smallest element, matrix[0][0], and the largest, matrix[n-1][n-1]. For any candidate value x, ask how many elements are less than or equal to x. That count only grows as x grows, so it is monotonic, and the answer is the smallest x whose count reaches k. Monotonic plus smallest is a binary search.
The remaining question is how to count fast, and the sorted rows and columns make that linear. Start at the top-right corner. In row r, move left while the value is greater than x; everything from column 0 to the current column is then at most x, which is c + 1 elements. Moving down a row, the boundary can only move left or stay, because columns are sorted downward, so the pointer never moves right. The whole count takes O(n) steps.
Why is the found value actually in the matrix? The binary search returns the smallest x with a count of at least k. If x were not present, then x - 1 would have the same count, contradicting minimality. So the result is always a real element.
Approach: Binary search on value range
- Set
l = matrix[0][0]andr = matrix[n - 1][n - 1], the smallest and largest values. - While
l <= r, takemid = (l + r) // 2. - Count elements at most
midwithcountLessEqual: for each row, move a column pointercleft whilematrix[r][c] > mid, then addc + 1. - If the count is at least k, record
res = midand search lower values withr = mid - 1. - Otherwise search higher values with
l = mid + 1. - Return
resonce the range is empty.
Step-by-step example
matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
- The value range is 1 to 15. For
mid= 8, row 0 contributes 2 (1 and 5) and rows 1 and 2 contribute 0. The count is 2, less than 8, sol= 9. - For
mid= 12, row 0 gives 3, row 1 gives 2 (10 and 11), and row 2 gives 1 (12). The count is 6, sol= 13. - For
mid= 14, the rows give 3, 3 and 2, a count of 8. That reaches k, sores= 14 andr= 13. - For
mid= 13, the rows again give 3, 3 and 2 because both 13s count. The count is 8, sores= 13 andr= 12. - Now
l= 13 is greater thanr= 12, so the search ends and returns 13.
Code: Python, Java, C++
1class Solution:
2 def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
3 n = len(matrix)
4 l, r = matrix[0][0], matrix[n - 1][n - 1]
5 res = -1
6
7 while l <= r:
8 mid = (l + r) // 2
9 if self.countLessEqual(matrix, mid) >= k:
10 res = mid
11 r = mid - 1
12 else:
13 l = mid + 1
14 return res
15
16 def countLessEqual(self, matrix, mid):
17 count = 0
18 c = len(matrix) - 1
19 for r in range(len(matrix)):
20 while c >= 0 and matrix[r][c] > mid:
21 c -= 1
22 count += (c + 1)
23 return count1class Solution {
2 public int kthSmallest(int[][] matrix, int k) {
3 int n = matrix.length;
4 int l = matrix[0][0], r = matrix[n - 1][n - 1];
5 int res = -1;
6
7 while (l <= r) {
8 int mid = l + (r - l) / 2;
9 if (countLessEqual(matrix, mid) >= k) {
10 res = mid;
11 r = mid - 1;
12 } else {
13 l = mid + 1;
14 }
15 }
16 return res;
17 }
18
19 private int countLessEqual(int[][] matrix, int mid) {
20 int count = 0, n = matrix.length, c = n - 1;
21 for (int r = 0; r < n; r++) {
22 while (c >= 0 && matrix[r][c] > mid) c--;
23 count += (c + 1);
24 }
25 return count;
26 }
27}1class Solution {
2public:
3 int kthSmallest(vector<vector<int>>& matrix, int k) {
4 int n = matrix.size();
5 int l = matrix[0][0], r = matrix[n - 1][n - 1];
6 int res = -1;
7
8 while (l <= r) {
9 int mid = l + (r - l) / 2;
10 if (countLessEqual(matrix, mid) >= k) {
11 res = mid;
12 r = mid - 1;
13 } else {
14 l = mid + 1;
15 }
16 }
17 return res;
18 }
19
20 int countLessEqual(vector<vector<int>>& matrix, int mid) {
21 int count = 0, n = matrix.size(), c = n - 1;
22 for (int r = 0; r < n; r++) {
23 while (c >= 0 && matrix[r][c] > mid) c--;
24 count += (c + 1);
25 }
26 return count;
27 }
28};Time and space complexity
O(n log(max - min))
The binary search runs over the value range, taking log(max - min) iterations, and each iteration counts in O(n) with the staircase walk.
O(1)
Only the search bounds and the counting pointers are stored.
Other approaches
Min-heap merge (time O(k log n), space O(n))
Push the first element of each row into a min-heap, then pop k times, each time pushing the next element from the popped element's row. It is intuitive when you think of rows as sorted lists and is fast for small k.
Flatten and sort (time O(n² log n), space O(n²))
Copy all n² values into one array and sort it. It is the easiest correct approach but ignores the structure and uses quadratic memory.
Common mistakes
- Binary searching over indices instead of values. The k-th element's position is not determined by a simple index formula in this matrix.
- Counting with
<instead of<=, which mishandles duplicates and can skip the true answer. - Resetting the column pointer to the last column for every row, which turns the O(n) count into O(n²).
- Computing the midpoint as
(l + r) // 2in Java or C++ with values near the integer limits, wherel + (r - l) / 2is safer.
Frequently asked questions
Why does binary search on values return an element that exists in the matrix?
The search finds the smallest value whose count of elements at or below it is at least k. If that value were missing from the matrix, the value one smaller would have the same count, which contradicts it being the smallest.
Heap or binary search for Kth Smallest Element in a Sorted Matrix?
A heap is O(k log n) and is simpler when k is small. Binary search on values is O(n log(max - min)) with constant extra space, which is better when k is large or memory is tight.
How do you count elements less than or equal to a value in O(n)?
Walk a pointer from the top-right corner. In each row, move left past values greater than the target, add the number of remaining columns, then go down a row without resetting the pointer.
Does this work if the matrix contains duplicates?
Yes. Duplicates are counted separately by the less-than-or-equal count, so the k-th smallest is found correctly even when the same value appears several times.