Parcel-delivery app~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-86linked-lists · three-way-partition
A parcel-delivery app models a sorting belt as a chain of nodes, one node for each parcel. Each node holds the parcel's weight in grams.
Before loading, the belt must put every parcel lighter than a limit in front of the others. Inside each group the parcels keep the order they had on the belt, because the labelling that follows depends on it. The belt can hold up to 100,000 parcels.
Write partition_parcels(head, pivot).
head is the first node of the belt, or null when the belt is empty. Each node's val is a weight.pivot is the limit. A parcel is light when its weight is less than pivot. A weight equal to pivot is not light.The tests give head as the list of values from the head, and read your answer the same way.
Input: head = [5, 1, 8, 3, 9, 2], pivot = 5
Output: [1, 3, 2, 5, 8, 9]| Step | Parcel | Goes to | Light chain | Heavy chain |
|---|---|---|---|---|
| [1] | empty | empty | ||
| [3] | 5 | heavy | empty | 5 |
| [3] | 1 | light | 1 | 5 |
| [3] | 8 | heavy | 1 | 5 → 8 |
| [3] | 3 | light | 1 → 3 | 5 → 8 |
| [3] | 9 | heavy | 1 → 3 | 5 → 8 → 9 |
| [3] | 2 | light | 1 → 3 → 2 | 5 → 8 → 9 |
| [4] | the heavy tail is cut; light joins heavy: 1 → 3 → 2 → 5 → 8 → 9 |
The light parcels 1, 3 and 2 keep their order. So do 5, 8 and 9. The parcel of weight 5 is not light, because 5 is not less than 5.
Input: head = [4, 4, 4], pivot = 4
Output: [4, 4, 4]Nothing is lighter than 4, so the belt keeps its order.
Input: head = [1, 2, 3], pivot = 9
Output: [1, 2, 3]Every parcel is light, so the second group is empty.
0 ≤ number of nodes ≤ 10^51 ≤ node.val ≤ 10^61 ≤ pivot ≤ 10^6Reading the parcels by position, once for each group, costs a walk for every position: about n² / 2 hops for each group. That is 10^10 hops in all at this size.
Moving every parcel to one of two chains in a single walk costs 10^5 hops.