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 matrix in which every row goes up from left to right and every column goes up from top to bottom, return the k-th smallest value in the whole matrix. Repeated values count separately: a value that appears twice takes two places in the order.

Example 1
Input: matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]], k = 8
Output: 13
Explanation: in sorted order the values are 1, 5, 9, 10, 11, 12, 13, 13, 15; the 8th is 13.
Example 2
Input: matrix = [[-5]], k = 1
Output: -5
Solution

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.

Counting the values at most 12 in the matrix 1, 5, 9 / 10, 11, 13 / 12, 13, 15. The walk starts at the bottom-left 12 and adds 3, moves up past 13, adds 2 at 11, moves up past 13, and adds 1 at 9: 6 values.

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: lo starts at matrix[0][0] and hi at matrix[n - 1][n - 1]. These bounds are values, not positions, so a guess may be a number that no cell holds.

Narrowing the guesses

What does one count tell us? Take the middle value mid between lo and hi. If at least k values are at most mid, the answer is mid or smaller, so hi moves down to mid. Otherwise the answer is bigger, and lo moves up to mid + 1. Each guess halves the range of values, the same halving as binary search on a sorted array, but over values.

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, lo and hi are both 13, and that is the answer.

The middle is computed as lo + (hi - lo) / 2, not (lo + hi) / 2. Java's integer division rounds toward zero, so for negative values (lo + hi) / 2 can round up. With lo = -5 and hi = -4, it gives -4. If the count at -4 is enough, hi stays -4 and the loop never ends. Since hi - lo is never negative, the other form always rounds down toward lo.

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 works this way. Put the first value of each row into it. Then take out the smallest value and put in the next value from the same row, k times. The k-th value taken out is the answer. That costs O((n + k) log n) time and O(n) space, which pays off when k is small.

Java Solution

The method kthSmallest works in these steps:

  1. First, take n, the number of rows, and set lo to the top-left value matrix[0][0] and hi to the bottom-right value matrix[n - 1][n - 1].
  2. While lo is less than hi, guess the middle value mid = lo + (hi - lo) / 2 and count the values at most mid with countAtMost.
  3. Inside countAtMost, which receives mid as target, the walk starts with row on the last row and col on the first column. A cell at most target adds row + 1 to count, for itself and the cells above it, and moves col right. A bigger cell moves row up. The walk stops when it leaves the matrix.
  4. Back in the loop, a count of at least k moves hi down to mid; a smaller count moves lo up to mid + 1.
  5. When lo and hi meet, lo is the smallest value with a count of at least k, and the method returns it.

The main method runs both examples, every k from 1 to 9 on Example 1, the counts at 12 and 14, and a 2 by 2 matrix with values from -1,000,000,000 to 1,000,000,000.

Java
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:

Output
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 rebuilds the sorted order of the cards, with 13 at both place 7 and place 8: the repeated value takes two places, as the problem asks.

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 countAtMost walk moves at most n steps up and n steps right.
  • Space: O(1). The search keeps lo, hi and mid, the walk keeps a row, a column and a count, and the matrix is never copied.

Find K-th Smallest Pair Distance uses the same idea: guess a value, then count how many items are at most that value.