Min Stack
Design a stack that supports retrieving the minimum in O(1).
Pattern fit
The simplest solution keeps a second stack of running minimums, which is a good reminder that stack questions are often about storing extra structural history.
Key observation
Each push must also record what the minimum becomes at that depth.
Target complexity
O(1) / O(n)
How to break down the solution cleanly
The simplest solution keeps a second stack of running minimums, which is a good reminder that stack questions are often about storing extra structural history.
Each push must also record what the minimum becomes at that depth.
Decide what unresolved property the stack maintains.
Push indices while the monotonic invariant holds.
Reference implementation
Python# Generic pattern template
stack = []
for i, value in enumerate(nums):
while stack and nums[stack[-1]] < value:
prev_index = stack.pop()
# value is the next greater for prev_index
stack.append(i)
Common pitfalls
Only storing a new min when the value is smaller and failing duplicate minimums.
Trying to recompute the minimum after pop.
Common follow-ups
How would you compress duplicates in the min stack?
What changes if you also need max in O(1)?
Continue with related problems
Build repeatable depth inside the Monotonic Stack cluster before moving on.