Problem 378 · LeetCode 378(opens in a new tab)
Kth Smallest Element in a Sorted Matrix
MediumBinary search
You are given an n × n matrix whose rows and columns are both sorted from small to large, and an integer k. Return the k-th smallest value in the whole matrix.
Equal values each count, so this is the k-th entry of all n² values in sorted order, not the k-th distinct value. Aim for a solution that uses less than O(n²) extra memory.
Example 1
Input: matrix = [[2,6,8],[3,7,10],[5,9,14]], k = 5 Output: 7 Why: in order the values are 2,3,5,6,7,…; the 5th is 7
2 more examples and the constraints
Example 2
Input: matrix = [[1,2],[2,3]], k = 3 Output: 2 Why: sorted it is 1,2,2,3; both 2s count
Example 3
Input: matrix = [[-4]], k = 1 Output: -4 Why: the only value
Constraints
- n is the number of rows and of columns; 1 ≤ n ≤ 300
- −1,000,000,000 ≤ matrix[i][j] ≤ 1,000,000,000
- Every row and every column is in non-decreasing order
- 1 ≤ k ≤ n²
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy and sortO(n² log n)
- Merge rows with a heapO(k log n)
- Binary search on the valueO(n log R)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 300, k = n² | Verdict |
|---|---|---|---|
| Copy and sort | O(n² log n) | Too much memory | |
| Merge rows with a heap | O(k log n) | Fine when k is small | |
| Binary search on the value | O(n log R) | Best; no extra memory |
n = side of the matrix, k = rank asked for, R = largest − smallest value (log R ≤ 31).
Edge cases to test
- One cell. [[−4]] with k = 1 returns −4; the loop never runs.
- Duplicates. Equal values each count, so [[1,2],[2,3]] with k = 3 gives 2.
- k = 1 or k = n². The answer is the top-left or the bottom-right cell.
- Extreme values. −10⁹ and 10⁹ in one matrix: the midpoint sum needs 64 bits.
- Negative values. The midpoint must round down, not toward zero, or lo and hi can stall.
Common mistakes
- Counting only distinct values, so duplicates are skipped and the rank is off.
- Computing
(lo + hi) / 2in 32-bit ints, which overflows near ±10⁹. - Returning
midfrom inside the loop instead oflowhen it ends;midmay not be in the matrix.
How to talk through it
- 1Clarify. Do duplicates count separately? Is the matrix always square? Any memory limit?
- 2Give the baseline. Copy and sort is O(n² log n) time and O(n²) memory.
- 3Use the rows. Merging rows with a min-heap brings memory to O(n).
- 4Search the value. Count cells ≤ mid with a staircase in O(n), and binary search for the smallest mid with count ≥ k.
- 5Test out loud. Run the 1×1 case, a case with duplicates, and k = n².
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?