Topic 4 / 16
Stack
EasyLinear~3 days
Easy to grasp
progress0 / 13 solved
LIFO structure for matching, undo operations, and monotonic problems.
Prerequisites
Unlocks
Concept
A stack is a LIFO (Last-In-First-Out) structure. Push to add, pop to remove from the top. It models 'most recent unresolved state' โ perfect for matching open/close pairs, undo history, and processing nested structures. Monotonic stacks (elements in sorted order) efficiently find next-greater or next-smaller elements.
When to use this pattern
- โMatching brackets, parentheses, or tags
- โUndo/redo or history navigation
- โExpression evaluation (infix, postfix)
- โNext greater/smaller element problems
- โDFS iteratively (instead of recursive call stack)
Common patterns
Matching pairs
Push open brackets; pop and verify on close brackets.
Monotonic stack (increasing)
Pop elements smaller than current โ find next greater element.
Monotonic stack (decreasing)
Pop elements larger than current โ find next smaller element.
Min stack
Track running minimum with an auxiliary stack.
Visual walkthrough
Monotonic Stack
Daily Temperatures
temperatures[]
73
074
175
271
369
472
576
673
7stack (indices)
empty
Start. Stack holds indices of "unresolved" temperatures.
We want: for each day, how many days until a warmer day?
step 1/17
Brute force โ optimal thinking
Brute force
For each element, scan forward to find the next greater โ O(nยฒ).
Observation
Once we find a greater element, everything smaller we passed is resolved.
Optimization
Maintain a monotonically decreasing stack. When a larger element arrives, pop and assign answers to everything it's greater than.
Final complexity
O(n) โ each element pushed and popped exactly once.
Quick Recall Check
What ordering property does a stack enforce?
In a monotonic decreasing stack, what happens when a larger element arrives?
What is the time complexity of finding the next greater element using a monotonic stack?
Am I ready to move on?
Check each question you can answer confidently before moving to the next topic.
Progress is saved on this device