Online store~25 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-1834heaps · sorting
An online store has one packing station with one packer. Orders arrive during the day, and the packer packs one order at a time, without stopping until it is done.
Your team lead asks: "Pack the shortest waiting order first, so that fewer customers wait long. What is the order of packing?" You know when each order arrives and how long it takes to pack.
Write packing_order(arrival, packing).
0 to n - 1. Order i arrives at time arrival[i] and takes packing[i] time units to pack. The orders are not sorted by arrival.Input: arrival = [1, 2, 3, 4], packing = [4, 3, 1, 2]
Output: [0, 2, 3, 1]The table shows the time the packer becomes free, the orders waiting then with their packing times, and the order packed.
| Free at time | Waiting orders (packing time) | Packed |
|---|---|---|
| 0 | none, wait until time 1 | none |
| 1 | 0 (4) | 0 |
| 5 | 1 (3), 2 (1), 3 (2) | 2 |
| 6 | 1 (3), 3 (2) | 3 |
| 8 | 1 (3) | 1 |
Input: arrival = [1, 10], packing = [2, 2]
Output: [0, 1]The packer is idle from time 3 to time 10, then packs order 1.
Input: arrival = [1, 1, 1], packing = [5, 5, 5]
Output: [0, 1, 2]All orders wait with the same packing time, so the smaller number goes first each time.
1 ≤ length of arrival ≤ 100,000, and packing has the same length.1 ≤ arrival[i], packing[i] ≤ 10^7For 100,000 orders, looking at every order for each choice is 100,000 × 100,000 = 10,000,000,000 checks. The time limit allows about a few hundred million simple steps.
Sorting by arrival and keeping the waiting orders in a heap costs about 100,000 × 17 = 1.7 million steps.