roadmap/Stack

Topic 4 / 16

Stack

EasyLinear~3 days
Easy to grasp
progress0 / 13 solved

LIFO structure for matching, undo operations, and monotonic problems.

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.

  • โ—†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)
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.
Monotonic Stack
Daily Temperatures
PUSH
temperatures[]
73
0
74
1
75
2
71
3
69
4
72
5
76
6
73
7
stack (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
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.

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?

Check each question you can answer confidently before moving to the next topic.

Progress is saved on this device