Problem 312993 · hard · Level 03 Linear Management & Searching

The k-th Lowest Spot on a Sorted Slope

binary search on the answer · matrices · staircase search

A surveyed hillside is the m x n grid grid of spot heights (below sea level is negative). The slope only ever rises: heights never decrease along a row from west to east, nor down a column from north to south. Return the k-th lowest height among all the cells, counting equal heights separately.

Examples

Input:  grid = [[2, 6, 8], [3, 7, 10], [5, 11, 14]], k = 6
Output: 8
Explanation: the heights in order are 2, 3, 5, 6, 7, 8, 10, 11, 14.

Input:  grid = [[-3, 0, 5]], k = 3
Output: 5

Input:  grid = [[1, 2], [1, 3]], k = 2
Output: 1

Constraints

  • 1 <= m, n <= 300, 1 <= k <= m * n
  • -10**9 <= grid[i][j] <= 10**9
  • Aim for O((m + n) log(max - min)) time. (Flattening and sorting still passes the tests; the point is to count instead of sorting.)

Goals

  • Count grid cells <= v with a staircase walk in O(rows + cols)
  • Binary search over values that may not appear in the grid
Starting Python…