Ctrl K

K-th Smallest in a Sorted Grid

Medium
You get a square table grid of size n × n in which every row and every column is sorted in non-decreasing order. You also get a number rank. Return the number that would stand in position rank if you wrote out all n² numbers of the table in ascending order (counting from 1). Repeated values take separate positions. Try to use less than O(n²) extra memory, without copying the whole table.
Example 1
grid=[[2, 4, 8], [3, 6, 9], [7, 10, 14]], rank=5 → 7

All numbers in ascending order: 2, 3, 4, 6, 7, 8, 9, 10, 14. The fifth is 7.

Example 2
grid=[[1, 1], [1, 5]], rank=3 → 1

The three 1s fill positions one to three: repeated values are counted separately.

Example 3
grid=[[-4]], rank=1 → -4
Constraints
  • 1 ≤ n ≤ 300
  • -10⁹ ≤ grid[i][j] ≤ 10⁹
  • Every row and every column is sorted in non-decreasing order
  • 1 ≤ rank ≤ n²
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Dimmest Rows EasyNearest k Values MediumRanked Prime Ratios MediumRoute With the Highest Bottleneck MediumTop Three While Typing Medium
loading Python…
Input
grid=[[2, 4, 8], [3, 6, 9], [7, 10, 14]], rank=5
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 89 tests on the server, hidden ones included.