Maintained by Vikas Dulgunde, software engineer
You receive an n by n matrix. Both directions are sorted: scanning left to right across any row gives non-decreasing values, and scanning top to bottom down any column does the same. There is no single global sorted line through the grid, only this row and column structure.
Picture flattening every cell into one long ascending list. Your job is to return the element that lands in position k of that list, counting from 1. Duplicate values keep their slots, so if the same number appears several times it is counted each time rather than collapsed to one.
The diagonal sorting means the smallest value is always the top-left cell and the largest is always the bottom-right, but the ordering of everything in between is not obvious. A value high up in a later column can be smaller than a value low down in an earlier column, which is what makes the rank lookup interesting.
Return the single integer at rank k. The matrix can hold negative numbers, and k is guaranteed to be a valid rank between 1 and n squared.
Sorted in full the entries are 1,5,9,10,11,12,13,13,15. The 8th value in that order is 13 (the first of the two 13s), so duplicates are counted by position not by distinctness.
Sorted order is 1,3,5,6,7,11,12,14,14. Counting to position 5 gives 7. Note 11 in row 3 is smaller than 12 in row 2, so column order alone does not predict the rank.
A single-cell grid has exactly one element, which is both the minimum and the only rank available.
Visible test cases
Each row is already sorted, so this is close to merging n sorted lists and stopping at the k-th item rather than producing the whole merge.
A min-heap can track the current front of each row. Pop the smallest, then push the next cell from that same row so the heap always holds at most one candidate per started row.
If you want to beat the heap on memory, notice that for any candidate value v you can count how many entries are <= v in O(n) by walking from the bottom-left corner. That count is monotonic in v, which invites binary search on the value range.
Ignore the sorted structure entirely, collect every cell into one array, sort it, and index into rank k.
Treat the rows as sorted lists and merge them lazily with a min-heap, advancing only as far as rank k. The heap never holds more than one in-progress entry per row.
Search the numeric range from the top-left minimum to the bottom-right maximum. For a midpoint value, count entries less than or equal to it in linear time using the staircase from the bottom-left corner, and narrow the range until the smallest value with count >= k is found.