Parcel-delivery app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-75three-way-partition · two-pointers
On a delivery loading belt, every parcel has a priority class: 0 for express, 1 for standard and 2 for economy. Before the trucks load, the belt controller regroups the parcels. Express parcels must come first and economy parcels last.
The controller has a swap arm that can exchange any two parcels on the belt. Each pass over the belt takes one full turn, so the controller must finish in a single pass. Its memory holds only a few counters, so it cannot keep a second copy of the belt.
Write group_classes(classes).
classes[i] is the priority class of the parcel at position i: 0 is express, 1 is standard and 2 is economy.0 comes first, then every 1, then every 2.Input: classes = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]| Step | low, mid, high before | classes[mid] | What happens | low, mid, high after | Belt after |
|---|---|---|---|---|---|
| 1 | 0, 0, 5 | 2 | economy: swap positions 0 and 5 | 0, 0, 4 | 0, 0, 2, 1, 1, 2 |
| 2 | 0, 0, 4 | 0 | express: swap positions 0 and 0 | 1, 1, 4 | 0, 0, 2, 1, 1, 2 |
| 3 | 1, 1, 4 | 0 | express: swap positions 1 and 1 | 2, 2, 4 | 0, 0, 2, 1, 1, 2 |
| 4 | 2, 2, 4 | 2 | economy: swap positions 2 and 4 | 2, 2, 3 | 0, 0, 1, 1, 2, 2 |
| 5 | 2, 2, 3 | 1 | standard: mid moves on | 2, 3, 3 | 0, 0, 1, 1, 2, 2 |
| 6 | 2, 3, 3 | 1 | standard: mid moves on | 2, 4, 3 | 0, 0, 1, 1, 2, 2 |
Six parcels take six steps. After step 1, the parcel that came back from position 5 is express, and step 2 checks it before mid moves.
Input: classes = [0, 2, 0, 2]
Output: [0, 0, 2, 2]No parcel is standard, so the standard block stays empty.
Input: classes = [1]
Output: [1]One parcel is already grouped.
1 ≤ classes.length ≤ 10^5classes[i] is 0, 1 or 2At this size, a sort in O(n log n) and a count in O(n) both fit the time limit easily. So time is not what rules them out here. The rules are: one pass, and memory for a few counters only.
A count needs a second pass to write the classes back, and a general sort makes many passes. Aim for one pass with three pointers and O(1) extra memory.