Kth Smallest Element in a Sorted Matrix
Medium
Topics
grid is an n by n matrix with every row sorted ascending and every column sorted ascending. Return the k-th smallest element, counting duplicates separately.
So in a matrix whose values are 1, 1, 2, the second smallest is 1 and not 2.
LeetCode names the argument matrix; the harness here calls it grid.
Example 1
13. Rows increase left to right and columns increase top to bottom, which is weaker than it sounds — the cells read row by row are not a sorted sequence, because a row can start below where the row above it ended. The value appears in 2 cells, and duplicates are counted separately, so the ranking runs over cells rather than over distinct values.Input: grid = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: Sorted the values run 1,5,9,10,11,12,13,13,15, and the eighth is 13 — the second of the two 13s.
Example 2
Input: grid = [[-5]], k = 1 Output: -5 Explanation: A single cell.
Example 3
Input: grid = [[1,2],[1,3]], k = 2 Output: 1 Explanation: Both 1s count, so the second smallest is the other 1 rather than 2.
Constraints
- n == grid.length == grid[i].length
- 1 <= n <= 300
- -10^9 <= grid[i][j] <= 10^9
- Each row and each column is sorted ascending
- 1 <= k <= n * n
Editorial — intuition, approach, complexity and pitfalls
Intuition
Collecting every value and sorting it is correct and spends n^2 log n on a matrix that is already mostly ordered. Two better routes exist and they are worth contrasting, because they answer different shapes of the same question.
The first keeps a running frontier of the smallest unexamined cell from each row, and pulls the smallest k times. Each pull replaces the taken cell with its right-hand neighbour. That costs k log n and is the right answer when k is small.
The second stops looking for the element and searches for its value instead. Pick a candidate value and count how many cells are less than or equal to it; that count rises as the candidate rises, which is what makes the value searchable over the numeric range between the smallest and largest entries.
Counting cells at or below a value is where the two sortings pay off: walk from the bottom-left corner, step right when the cell is small enough and up when it is not, and the whole count takes 2n steps. The smallest candidate whose count reaches k is the answer, and because the candidate converges onto an actual matrix entry, duplicates are handled without any special care.
Approach
- Set the search range to the smallest entry, at the top-left, and the largest, at the bottom-right.
- Take a candidate value in the middle of that range.
- Count the cells at or below the candidate: start at the bottom-left, step right while the cell is at or below it, adding the whole column above, and step up otherwise.
- If the count is at least
k, the answer is at or below the candidate, so narrow the top of the range to it. Otherwise move the bottom above it. - When the range closes, it has closed on an actual matrix entry, which is the answer.
Walkthrough
grid = [[ 1, 5, 9],
[10,11,13],
[12,13,15]]
k = 8
sorted values: 1,5,9,10,11,12,13,13,15
^ 8th = 13
searching for the VALUE, range [1, 15]
candidate 8: count cells <= 8
from bottom-left (2,0)=12 > 8, step up
(1,0)=10 > 8, step up
(0,0)=1 <= 8, count += 1, step right
(0,1)=5 <= 8, count += 1, step right
(0,2)=9 > 8, step up -> off the top
count 2 < 8, so the answer is above 8
candidate 12: count cells <= 12
walking the staircase gives 6
6 < 8, answer is above 12
candidate 13: count cells <= 13
gives 8
8 >= 8, so the answer is at or below 13
range closes on 13
answer 13
why duplicates need no special handling
the count is "cells at or below", which counts BOTH 13s.
The search closes on the smallest value whose count
reaches k, and that value is always a real entry.Complexity
- Time — O(n log(max - min)): each candidate is counted in 2n steps, and the numeric range halves each time.
- Space — O(1): no structure beyond a few indices.
Common Pitfalls
- Treating the matrix as one sorted sequence read row by row. The rows are sorted individually but do not run on from each other.
- Counting distinct values instead of cells, which gives
2for the second smallest of1,1,2rather than1. - Counting cells strictly below the candidate rather than at or below, which lands one off whenever the answer is duplicated.
- Returning the candidate from the middle of the range rather than the value the range closed on. Mid is often not a matrix entry.
- Starting the staircase walk at a corner where a comparison does not eliminate a whole row or column.
Full Solution — all languages
class Solution:
def kthSmallest(self, grid, k):
n = len(grid)
def count_at_or_below(value):
# Staircase walk from the bottom-left: 2n steps, not n^2.
total, r, c = 0, n - 1, 0
while r >= 0 and c < n:
if grid[r][c] <= value:
total += r + 1 # this cell and everything above it
c += 1
else:
r -= 1
return total
lo, hi = grid[0][0], grid[n - 1][n - 1]
while lo < hi:
mid = lo + (hi - lo) // 2
if count_at_or_below(mid) >= k:
hi = mid
else:
lo = mid + 1
# The range closes on an actual matrix entry.
return loimport java.util.*;
class Solution {
public int kthSmallest(int[][] grid, int k) {
int n = grid.length;
int lo = grid[0][0], hi = grid[n - 1][n - 1];
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// Staircase walk from the bottom-left: 2n steps, not n^2.
int total = 0, r = n - 1, c = 0;
while (r >= 0 && c < n) {
if (grid[r][c] <= mid) {
total += r + 1;
c++;
} else r--;
}
if (total >= k) hi = mid;
else lo = mid + 1;
}
return lo;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int kthSmallest(vector<vector<int>>& grid, int k) {
int n = (int)grid.size();
auto countAtOrBelow = [&](int value) {
int total = 0, r = n - 1, c = 0;
while (r >= 0 && c < n) {
if (grid[r][c] <= value) {
total += r + 1;
c++;
} else r--;
}
return total;
};
int lo = grid[0][0], hi = grid[n - 1][n - 1];
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countAtOrBelow(mid) >= k) hi = mid;
else lo = mid + 1;
}
return lo;
}
};/**
* @param {number[][]} grid
* @param {number} k
* @return {number}
*/ var kthSmallest = function(grid, k) {
const n = grid.length;
const countAtOrBelow = (value) => {
let total = 0, r = n - 1, c = 0;
while (r >= 0 && c < n) {
if (grid[r][c] <= value) {
total += r + 1;
c++;
} else r--;
}
return total;
};
let lo = grid[0][0], hi = grid[n - 1][n - 1];
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (countAtOrBelow(mid) >= k) hi = mid;
else lo = mid + 1;
}
return lo;
};