Parcel-delivery app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-735monotonic-stack · stacks
A parcel-delivery hub has a narrow sorting belt where parcels are pushed in from both ends. A positive number is a parcel that moves right, a negative number is a parcel that moves left, and its size is its weight. All parcels move at the same speed.
When two parcels meet head on, the lighter one is pushed off the belt. If they weigh the same, both are pushed off. Parcels that move in the same direction never meet. The parcels are listed from left to right, and a belt holds up to 100,000.
Write surviving_parcels(parcels).
parcels is a list of whole numbers that are not 0, in belt order from left to right. A positive number moves right, a negative number moves left, and the size is the weight.Input: parcels = [4, 7, -3, -7, 2, -9, 6, -5]
Output: [-9, 6]Keep the surviving parcels on a stack, in belt order. A right-mover joins the stack at once. A left-mover meets the right-movers on top of the stack, one after another. It stops when it leaves, ties, or has none left to meet.
| Parcel read | What happens | Stack after |
|---|---|---|
| 4 | joins the stack | 4 |
| 7 | joins the stack | 4, 7 |
| -3 | 7 is heavier than 3: the new parcel leaves | 4, 7 |
| -7 | 7 and 7 are equal: both leave | 4 |
| 2 | joins the stack | 4, 2 |
| -9 | 2 is lighter than 9: it leaves; 4 is lighter than 9: it leaves; joins the stack | -9 |
| 6 | joins the stack | -9, 6 |
| -5 | 6 is heavier than 5: the new parcel leaves | -9, 6 |
The parcels that remain are -9 and 6. The -9 cleared the 2 and the 4 and met nothing after that, so it is now the first on the belt. The 6 was left alone, because -5 is lighter.
Input: parcels = [8, -8]
Output: []The two parcels weigh the same, so both are pushed off. Nothing remains.
Input: parcels = [-5, 3]
Output: [-5, 3]The left-mover is on the left of the right-mover, so they move apart and never meet. Both stay.
1 ≤ number of parcels ≤ 10^51 ≤ weight ≤ 10^6: each number is non-zero, and its absolute value is the weightA plan that rescans from the left after every collision costs about n^2 / 8 steps when many right-movers are followed by many left-movers. That is 10^9 steps for 100,000 parcels, which is too slow.
So the work must be close to n steps in all. Each parcel should be handled a constant number of times, and each collision should be found at the top of a stack.