Lightest Parcel on the Pile
Medium · Stack & Monotonic Stack · about 20 min
Parcels in a small depot are piled on top of each other: you can only add or remove the parcel on top. The depot software must also say, at any moment, how heavy the lightest parcel in the pile is, in O(1) time.
You get a list of operations as strings and run them in order on a pile that starts empty:
"push X": put a parcel weighingXon top (Xis an integer, possibly negative for a calibration tag)."pop": remove the top parcel. It prints nothing."top": print the weight of the top parcel."min": print the weight of the lightest parcel in the pile.
"pop", "top" and "min" are never used on an empty pile. Return the list of printed numbers, in order.
Example: parcel_stack_lightest(["push 5", "push 3", "min", "push 7", "min", "pop", "pop", "min", "top"]) → [3, 3, 5, 5]
Constraints: 0 to 100,000 operations; weights are between -1,000,000,000 and 1,000,000,000.
Hints
- Keeping one "lightest" variable fails when that parcel is popped. What would you need to remember to undo it?
- Let every level of the pile remember the lightest weight from the bottom up to that level.
- Push the pair (weight, smaller of weight and the lightest below it). min reads the top pair, and pop needs no extra work.
Learn the pattern first: the Stack & Monotonic Stack lesson.
More Stack & Monotonic Stack problems
- Config Bracket Check (Easy)
- Cancelling Beads (Easy)
- Calculator Tape (Easy)
- Banner Expander (Medium)
- Taller Friend at the Round Table (Medium)
- Scooter Convoys (Medium)
- Biggest Skyline Billboard (Hard)