Stack
A stack gives you the most recent unfinished thing in O(1). That fits two kinds of problems: matching things that nest, and answering “what is the next bigger value?” for every element in a single pass.
When to reach for it
Section titled “When to reach for it”- The input has nested or paired structure: brackets, tags, undo history, expression evaluation.
- You must undo or reverse the most recent unresolved item.
- The question is “next greater / next smaller element” or “how many days until…”.
- A nested loop scans right from each index looking for the first value that beats it.
- A design problem needs an extra query (min, max) in O(1) alongside push and pop.
Template
Section titled “Template”# Plain LIFO matching: push openers, pop on closers.stack = []for item in items: if is_opener(item): stack.append(item) elif not stack or not matches(stack.pop(), item): return Falsereturn not stack # nothing left unmatched
# Monotonic stack: indices whose answer is still unknown.stack = [] # values at these indices never increasefor i, x in enumerate(nums): while stack and nums[stack[-1]] < x: # x is the answer for them j = stack.pop() answer[j] = i - j stack.append(i)Each element is pushed once and popped at most once, so the monotonic version is O(n) even though it has a nested loop. Flip the comparison for “next smaller”.
Problems in this guide
Section titled “Problems in this guide”- Valid Parentheses — push openers, pop and compare on closers
- Min Stack — store the running minimum next to each value
- Daily Temperatures — monotonic stack of indices waiting for a warmer day