Kth Smallest Element in a Sorted Matrix
1 approach, code in every language
Problem description
You are given an n x n grid of integers where each individual row reads in non-decreasing order from left to right, and each individual column reads in non-decreasing order from top to bottom. Note that this ordering guarantee applies within rows and within columns, not across the flattened grid as a whole.
Given a value k, return the k-th smallest number when all of the grid's entries are considered together. Duplicate values count as distinct positions, so the k-th smallest refers to the k-th entry in sorted order, not the k-th unique value.
Example 1
Input: matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]], k = 8
Output: 13
Sorted, the entries are 1, 5, 9, 10, 11, 12, 13, 13, 15. The eighth value in that order is 13.
Example 2
Input: matrix = [[-5]], k = 1
Output: -5
The grid holds a single value, so the first smallest element is that value.
Constraints
n == matrix.length == matrix[i].length1 <= n <= 300-10^9 <= matrix[i][j] <= 10^91 <= k <= n^2
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Kth Smallest Drift Reading is our own problem on the technique behind Kth Smallest Element in a Sorted Matrix: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free