Parcel-delivery app~20 min2s · 256 MBtarget O(n log n) time, O(n) spacesorting
A parcel-delivery app loads a van at a hub. Each parcel has a delivery zone, a whole number from 0 to 99, and a weight in grams. Parcels arrive at the hub one by one.
The driver visits the zones in order, from zone 0 to zone 99. Inside a zone, the heaviest parcels come out first, and equal weights keep their arrival order. Your team lead asks: "Give me the arrival positions in loading order."
Write order_parcels(zones, weights).
i arrived at position i, counting from 0. It has the zone zones[i] and the weight weights[i].Input: zones = [2, 0, 2, 1, 0, 2], weights = [40, 15, 40, 90, 70, 10]
Output: [4, 1, 3, 0, 2, 5]Zone 0 holds positions 1 and 4. The heavier one, position 4 with 70 grams, comes first. Zone 1 holds position 3.
Zone 2 holds positions 0, 2 and 5. Positions 0 and 2 weigh 40 grams each, so position 0 comes first, then position 2, then position 5 with 10 grams.
| Position | Zone | Weight | Place in the order |
|---|---|---|---|
| 0 | 2 | 40 | 3 |
| 1 | 0 | 15 | 1 |
| 2 | 2 | 40 | 4 |
| 3 | 1 | 90 | 2 |
| 4 | 0 | 70 | 0 |
| 5 | 2 | 10 | 5 |
Input: zones = [], weights = []
Output: []There are no parcels, so the answer is an empty list.
Input: zones = [5, 5], weights = [8, 8]
Output: [0, 1]Same zone and same weight: the earlier arrival comes first.
0 ≤ zones.length = weights.length ≤ 100,000 (parcels)0 ≤ zones[i] ≤ 99 (zone)0 ≤ weights[i] ≤ 1,000,000,000 (grams)Insertion with a three-part test makes about n × n / 4 comparisons, which is 2,499,975,000 at n = 100,000. A sort by weight costs about n log n, and a counting pass over the 100 zones costs about 2n + 100 steps.