Parcel-delivery app~20 min2s · 256 MBtarget O(n × prefix) time, O(n) spacehashing
An online shop ships its orders from one warehouse. Each order has a postcode, and the first few characters of a postcode name a shipping zone. The shop loads one truck for each zone.
The packing team wants the orders listed by zone. Zones are listed in the order in which they first appear, and the orders of a zone keep the order in which they arrived.
Write group_orders(order_ids, postcodes, prefix).
i has the id order_ids[i] and the postcode postcodes[i]. Orders are listed in the order they arrived.prefix characters of its postcode. If the postcode is shorter, the zone is the whole postcode.Input: order_ids = [101, 102, 103, 104, 105, 106], postcodes = ["ab12", "cd34", "ab99", "ab12", "ef01", "cd77"], prefix = 2
Output: [[101, 103, 104], [102, 106], [105]]The trace gives each order the group of its zone.
| i | Order | Postcode | Zone | Group |
|---|---|---|---|---|
| 0 | 101 | ab12 | ab | new group 0 |
| 1 | 102 | cd34 | cd | new group 1 |
| 2 | 103 | ab99 | ab | group 0 |
| 3 | 104 | ab12 | ab | group 0 |
| 4 | 105 | ef01 | ef | new group 2 |
| 5 | 106 | cd77 | cd | group 1 |
The zone ab first appears at order 101, cd at order 102, and ef at order 105. So the groups come in that order, and each keeps its orders in arrival order.
Input: order_ids = [101, 102, 103, 104, 105, 106], postcodes = ["ab12", "cd34", "ab99", "ab12", "ef01", "cd77"], prefix = 4
Output: [[101, 104], [102], [103], [105], [106]]With prefix = 4, the whole postcode is the zone. Only orders 101 and 104 share a zone, so only they are grouped.
Input: order_ids = [7, 8], postcodes = ["x1", "x1"], prefix = 10
Output: [[7, 8]]The prefix is longer than the postcodes, so the whole postcode is the zone. Both orders share it.
1 ≤ order_ids.length ≤ 100,000; postcodes has the same length; 1 ≤ order_ids[i] ≤ 1,000,000,000a-z and 0-91 ≤ prefix ≤ 10Searching the groups found so far for the zone of every order costs up to n × z steps, where z is the number of zones. That is about 5 × 10^9. A map from the zone to its group finds the group in one step, so one pass over the orders is enough.