Online store~30 min2s · 256 MBtarget O(k log min(n, k)) time, O(min(n, k)) spaceclassic twin: lc-373k-way-merge · heaps
An online store sells phone cases and chargers. A shopper picks one case and one charger for a bundle, and the bundle costs the sum of the two prices.
The store lists the cases from the cheapest to the dearest, and so for the chargers. Each list can hold 100,000 items, which gives up to 10^10 bundles. The "best deals" box shows only the k cheapest bundles.
Write cheapest_pairs(first, second, k).
first holds the case prices and second the charger prices. Both are in non-decreasing order.first and one from second, and its total is their sum. Bundles that use different items count separately, even when the prices are equal.first comes first.k bundles as [case price, charger price] pairs. If there are fewer than k bundles, return all of them.Input: first = [1, 4, 7], second = [2, 3, 9], k = 5
Output: [[1, 2], [1, 3], [4, 2], [4, 3], [7, 2]]Think of the table of totals. Row i holds first[i] + second[0], first[i] + second[1], and so on, so every row is a sorted list. Merge the rows with a heap of their fronts. Each heap entry is a total, with its row and column.
| Pop | Pair | Total | Heap after the step, smallest total first |
|---|---|---|---|
| 1 | [1, 2] |
3 | 4 (row 0), 6 (row 1), 9 (row 2) |
| 2 | [1, 3] |
4 | 6 (row 1), 9 (row 2), 10 (row 0) |
| 3 | [4, 2] |
6 | 7 (row 1), 9 (row 2), 10 (row 0) |
| 4 | [4, 3] |
7 | 9 (row 2), 10 (row 0), 13 (row 1) |
| 5 | [7, 2] |
9 | 10 (row 0), 10 (row 2), 13 (row 1) |
After each pop, the next total of the same row is pushed. The first five pops give the five pairs.
Input: first = [1, 1, 2], second = [1, 2, 3], k = 3
Output: [[1, 1], [1, 1], [1, 2]]The two 1s in first make two different bundles with the same prices. The two cheapest bundles are both [1, 1], with total 2.
Input: first = [5], second = [1, 2], k = 4
Output: [[5, 1], [5, 2]]There are only two bundles, so both are returned.
1 ≤ length of first ≤ 10^5 and 1 ≤ length of second ≤ 10^50 ≤ first[i], second[j] ≤ 10^71 ≤ k ≤ 10^5There can be 10^10 bundles, so you cannot list them all, and you cannot sort them. But you only need the first k, and each row of the table of totals is sorted. A heap of the rows' fronts finds the cheapest k bundles without building the table.
The heap starts with at most k entries, because a row below the first k rows cannot hold one of the k cheapest bundles.