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^2See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI