The Two Stack Approach
Use a `mainStack` to hold the actual elements, and an auxiliary `minStack` to keep track of the minimums. This avoids O(N) searching for the min.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Design a stack that supports push, pop, top, and retrieving the minimum element in constant O(1) time.
Use a `mainStack` to hold the actual elements, and an auxiliary `minStack` to keep track of the minimums. This avoids O(N) searching for the min.
Always push to the `mainStack`. Only push to the `minStack` if the new value is less than OR EQUAL to the current minimum (the top of the `minStack`).
Always pop from the `mainStack`. If the value popped is exactly equal to the top of the `minStack`, pop from the `minStack` as well, because we just removed the current minimum.