Kth Smallest Element in a Sorted Matrix
Find the k-th smallest value in a matrix with sorted rows and columns, by guessing a value and counting how many cells are no bigger.
Given an n x n
Example 1
Output: 13
Explanation: in sorted order the values are 1, 5, 9, 10, 11, 12, 13, 13, 15; the 8th is 13.
Example 2
Output: -5
The Idea
Picture the nine numbers of Example 1 on cards, laid out in a 3 by 3 grid. Each row reads from small to large going right, and each column from small to large going down. Line all the cards up in order and you get 1, 5, 9, 10, 11, 12, 13, 13, 15. The 8th card in that line is 13. The two 13s take places 7 and 8, so 13 is both the 7th and the 8th smallest.
Lining up every card means sorting all n × n values, though, and the grid is already partly sorted. Can we use its order directly? Not by position: read row by row, the grid gives 1, 5, 9, 10, 11, 13, 12, 13, 15, and 12 comes after 13. The 8th cell of the grid says nothing about the 8th smallest value.
So turn the question round. Instead of asking which value is 8th, pick a value and ask how many cards are at most that value. The grid answers this quickly, starting from its bottom-left corner. Look at the picture below.
The picture counts the values at most 12 (the sign ≤ means "at most"). Step 1 starts on 12, which is small enough. The column above it is sorted, so 10 and 1 are smaller still, and all three count at once: +3. The walk then moves right, onto 13 in step 2.
13 is too big, and the values to its right in the bottom row only get bigger, so the walk moves up instead. In step 3, 11 counts together with the 5 above it, +2. Step 4 meets the other 13 and moves up, and step 5 counts 9, +1, before the walk leaves the grid on the right. The box shows the total: 3 + 2 + 1 = 6.
Each step moves up or right, so a walk visits at most 2n cells instead of all n × n. And 6 is fewer than 8, so the 8th smallest value must be bigger than 12. Counting at a bigger value can only give a bigger count: at 13 it reaches 8. So the answer is the smallest value whose count is at least k, and we can home in on it by guessing values and counting.
Solution Approach
Sorting every value would also work, but slowly. The faster way needs four decisions: which corner the count starts from, which values to guess from, how each count narrows the guesses, and why the value found is really in the matrix. A heap gives an optional alternative for small k.
The slow way
Why not just sort? Copy all n × n values into one list, sort it and take the value at index k - 1. That is correct, but a 1,000 by 1,000 matrix means sorting a million values, O(n² log n) time, plus a copy of all of them. One counting walk reads at most 2n cells and stores nothing.
Where the count starts
Why the bottom-left corner? From there the two moves go opposite ways: up leads to smaller values and right to larger ones. So every cell tells the walk which way to go. The top-right corner has the same property. From the top-left corner, both moves lead to larger values, so a cell that is small enough gives no direction.
The values to guess from
Where can the answer lie? The top-left cell is the smallest value in the matrix, because every other cell is to its right or below it, and the bottom-right cell is the largest. So the search keeps two bounds: lomatrix[0][0]himatrix[n - 1][n - 1]
Narrowing the guesses
What does one count tell us? Take the middle value midlohimidmidhimidlomid + 1
In Example 1, with k = 8, the range starts at 1 to 15. The guesses are 8 (count 2), 12 (count 6), 14 (count 8) and 13 (count 8). After the last one, lohi
The middle is computed as lo + (hi - lo) / 2(lo + hi) / 2(lo + hi) / 2lo = -5hi = -4hihi - lolo
Why the answer is in the matrix
The guesses can be values the matrix does not hold, like 14 above. Can the search end on one of them? No. The count only changes at values that appear in the matrix: between 13 and 14 no new cell joins, so 14 has the same count as 13. The smallest value whose count reaches k is therefore always a cell's value.
Optional: a min-heap instead
A min-heap is a collection that always hands out its smallest item first; Java's PriorityQueue
Java Solution
The method kthSmallest
- First, take
, the number of rows, and setn to the top-left valuelo andmatrix[0][0] to the bottom-right valuehi .matrix[n - 1][n - 1] - While
is less thanlo , guess the middle valuehi and count the values at mostmid = lo + (hi - lo) / 2 withmid .countAtMost - Inside
, which receivescountAtMost asmid , the walk starts withtarget on the last row androw on the first column. A cell at mostcol addstarget torow + 1 , for itself and the cells above it, and movescount right. A bigger cell movescol up. The walk stops when it leaves the matrix.row - Back in the loop, a count of at least
movesk down tohi ; a smaller count movesmid up tolo .mid + 1 - When
andlo meet,hi is the smallest value with a count of at leastlo , and the method returns it.k
The main
import java.util.ArrayList;
import java.util.List;
public class KthSmallestInSortedMatrix {
public static int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int lo = matrix[0][0]; // smallest value
int hi = matrix[n - 1][n - 1]; // largest value
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countAtMost(matrix, mid) >= k) {
hi = mid; // the k-th smallest is <= mid
} else {
lo = mid + 1; // fewer than k values are <= mid
}
}
return lo;
}
// Values <= target, counted from the bottom-left corner
static int countAtMost(int[][] matrix, int target) {
int n = matrix.length;
int count = 0;
int row = n - 1;
int col = 0;
while (row >= 0 && col < n) {
if (matrix[row][col] <= target) {
count += row + 1; // this cell and everything above it
col++;
} else {
row--; // this cell and everything right of it are too big
}
}
return count;
}
public static void main(String[] args) {
int[][] matrix = {{1, 5, 9}, {10, 11, 13}, {12, 13, 15}};
System.out.println(kthSmallest(matrix, 8));
System.out.println(kthSmallest(new int[][] {{-5}}, 1));
List<Integer> all = new ArrayList<>();
for (int k = 1; k <= 9; k++) {
all.add(kthSmallest(matrix, k));
}
System.out.println("k = 1 to 9: " + all);
System.out.println("values <= 12: " + countAtMost(matrix, 12)
+ ", values <= 14: " + countAtMost(matrix, 14));
int[][] wide = {{-1000000000, 0}, {0, 1000000000}};
System.out.println(kthSmallest(wide, 1) + " " + kthSmallest(wide, 3)
+ " " + kthSmallest(wide, 4));
}
}
Running it prints:
13
-5
k = 1 to 9: [1, 5, 9, 10, 11, 12, 13, 13, 15]
values <= 12: 6, values <= 14: 8
-1000000000 0 1000000000
Example 1 gives 13 and Example 2 gives -5. The line starting k = 1 to 9
The counts line shows 6 values at most 12, the total from the picture, and 8 at most 14. No cell holds 14, so its count equals the count at 13, and the search moves on past it to 13. The last line comes from the 2 by 2 matrix: k = 1, 3 and 4 give -1000000000, 0 and 1000000000, so the search works across negative values as well.
Complexity
Each guess costs one counting walk, and the number of guesses depends on the spread of the values, not on n.
- Time: O(n log(max - min)), where max - min is the bottom-right value minus the top-left value. Each guess halves that range, so there are about log(max - min) guesses, and each
walk moves at most n steps up and n steps right.countAtMost - Space: O(1). The search keeps
,lo andhi , the walk keeps a row, a column and a count, and the matrix is never copied.mid