Design a stack class MinStack that supports: push(val) โ push element onto stack, pop() โ remove top element, top() โ get top element, getMin() โ retrieve the minimum element. Each operation must run in O(1) time.
โข -2ยณยน โค val โค 2ยณยน - 1โข pop, top, getMin called on non-empty stacksโข At most 3 ร 10โด calls total
02
Section Two ยท Approach 1
Brute Force โ Scan for Min O(n)
Use a regular stack. For getMin(), scan the entire stack to find the minimum. Push, pop, and top are O(1), but getMin is O(n).
Problem: getMin scans every element. By maintaining a second stack that tracks the running minimum, we get O(1) for all operations.
Operation
Time
push / pop / top
O(1)
getMin
O(n) โ scans stack
03
Section Three ยท Approach 2
Two Stacks โ O(1) All Operations
Maintain two stacks: a main stack for normal operations and a min stack that mirrors it, always holding the current minimum at the top. On push, push to main stack and push min(val, minStack.top) to the min stack. On pop, pop from both.
๐ก Mental model: Imagine two columns of sticky notes. The left column stores actual values. At the same height on the right column, you write "the smallest value in the left column from this point down." Every time you add or remove from the left, you update the right accordingly. Reading the minimum is just glancing at the top of the right column.
Algorithm
push(val): Push val onto main. Push min(val, minStack.peek()) onto minStack.
pop(): Pop from both stacks.
top(): Return main stack's top.
getMin(): Return minStack's top โ always the current min.
๐ฏ Why it works:
The min stack is synchronized with the main stack.
Its top always reflects the minimum of all elements currently in main.
When we pop from main, the next element's minimum is already stored in minStack โ no recomputation needed.
Both min entries are 1. After pop, min is still 1.
New min then pop
push(3), push(1), pop()
Min reverts to 3 after popping 1. MinStack handles this automatically.
Large negatives
push(-2ยณยน)
Integer.MIN_VALUE works โ no overflow in min comparison.
โ Common Mistake: Only pushing to the min stack when the value is a new minimum. This breaks on pop โ if the minimum value is popped, the min stack is shorter than the main stack and falls out of sync. Always push to both stacks on every push, and pop from both on every pop.