Parcel-delivery app~12 min2s · 256 MBtarget O(n) time, O(1) spacetwo-pointers
A parcel hub loads trucks in shipping batches. The belt delivers parcel ids in order, and each batch is batch parcels long, except that the last batch may be shorter.
The truck is loaded from the back, so each batch must be printed in reverse order. The label printer has memory for the list only, so the edit must happen in the list itself.
Write reverse_batches(parcels, batch).
parcels[i] is the id of the i-th parcel on the belt.parcels into consecutive batches of batch parcels. The last batch holds the parcels that remain.Input: parcels = [4, 8, 15, 16, 23, 42, 7], batch = 3
Output: [15, 8, 4, 42, 23, 16, 7]Swap the two ends of each batch and move inwards.
| Batch | Places | Before | After |
|---|---|---|---|
| 1 | 0 to 2 | [4, 8, 15] | [15, 8, 4] |
| 2 | 3 to 5 | [16, 23, 42] | [42, 23, 16] |
| 3 | 6 to 6 | [7] | [7] |
The last batch has one parcel, and a batch of one parcel stays as it is.
Input: parcels = [5], batch = 4
Output: [5]The only batch is shorter than batch, and it holds one parcel.
Input: parcels = [1, 2, 3, 4], batch = 1
Output: [1, 2, 3, 4]Every batch holds one parcel, so nothing changes.
1 ≤ parcels.length ≤ 100,000 (parcels on the belt)1 ≤ parcels[i] ≤ 1,000,000,000 (parcel ids)1 ≤ batch ≤ 100,000 (a batch can be longer than the list)A batch can hold up to 100,000 parcels. Reversing it by moving each parcel to the front of the batch with adjacent swaps costs about n × n / 2 swaps, which is 5 × 10^9 at n = 100,000. Two pointers that swap the ends cost about n / 2 swaps in all.