Problem 435473 · medium · Level 04 Non-Linear Data Structures

The k-th Coldest Sensor in the Cold Store

heaps · k-way merge · matrix · kth element

Temperature sensors in a cold store sit on a rectangular grid, and their integer readings form grid. The store gets warmer towards the loading door, so the readings never fall from left to right along a row, nor from top to bottom down a column. Return the k-th coldest reading, counting equal readings separately (the 2nd coldest of [[1, 2], [1, 3]] is 1).

Examples

Input:  grid = [[1, 4, 7],
                [2, 5, 8],
                [3, 6, 9]], k = 5
Output: 5

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

Constraints

  • 1 <= rows, cols <= 1000, rows * cols <= 10**5, values in [-10**9, 10**9]
  • 1 <= k <= rows * cols
  • Target complexity: O(k log(min(k, rows))).

Goals

  • Treat each sorted row as a stream and merge them with a heap
  • Seed with only as many rows as k requires
  • Stop after exactly k extractions
Starting Python…