Online store~25 min2s · 256 MBtarget O(min(rows, k) + k log min(rows, k)) time, O(min(rows, k)) spaceclassic twin: lc-378k-way-merge · heaps
An online store shows a price grid for one product line. The rows are quality tiers and the columns are sizes. Prices never fall as you move right along a row or down a column.
For a "starting from" badge, your team lead wants the k-th lowest price in the whole grid. Many cells share a price, and each cell counts once. A grid can have 500 rows and 500 columns, which is 250,000 prices.
Write kth_in_grid(grid, k).
grid[r][c] is the price of tier r in size c. Every row is in non-decreasing order, and so is every column. Every row has the same length.k of that list. Position 1 is the lowest price.Input: grid = [[2, 4, 7], [3, 6, 9], [5, 8, 12]], k = 5
Output: 6Every row is a sorted list, so merge the rows with a heap of their current fronts. The heap starts with the first price of each row: 2, 3 and 5. Pop the smallest price, and push the next price of the same row.
| Pop | Price | Pushed next | Heap after the step, smallest first |
|---|---|---|---|
| 1 | 2 | 4 | 3, 4, 5 |
| 2 | 3 | 6 | 4, 5, 6 |
| 3 | 4 | 7 | 5, 6, 7 |
| 4 | 5 | 8 | 6, 7, 8 |
After 4 pops, the smallest price left in the heap, 6, is the 5th smallest price in the grid.
Input: grid = [[7]], k = 1
Output: 7A grid of one price: the answer is that price.
Input: grid = [[1, 1], [1, 1]], k = 3
Output: 1The sorted list is 1, 1, 1, 1. Equal prices count once for each cell, so the 3rd price is 1.
1 ≤ rows ≤ 500, 1 ≤ columns ≤ 5000 ≤ grid[r][c] ≤ 10^71 ≤ k ≤ rows × columnsCollecting and sorting every cell works for 250,000 prices, but it reads all of them and holds them all. The grid is already sorted along each row, so each row is a sorted list that a heap can merge.
Merging by scanning the front of every row costs about k × rows steps, which for k = 125,000 and 500 rows is more than 6 × 10^7. A heap of fronts costs only about log of the number of rows for each step.