Lesson 8 of 40Core patterns
Stack
Use a last-in-first-out stack to match brackets, evaluate expressions and find the next greater element in O(n).
Your editor highlights a missing bracket, your browser's back button returns to the last page, and Ctrl+Z undoes the most recent edit. All three are stacks. In interviews the stack shows up whenever the most recent unfinished thing is the one you need next, and its clever cousin, the monotonic stack, solves "next greater element" problems that look like they need O(n²).
LIFO in one minute
A stack is last in, first out (LIFO). You push onto the top and pop from the top. You can also peek at the top without removing it. All three are O(1).
Push 1. It sits at the bottom.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.A Python list and a JS Array are perfect stacks because adding and removing at the end is O(1). Never use the front (pop(0), shift()), which is O(n).
Matching brackets
A string like ([]{}) is valid when every closing bracket matches the most recent unmatched opening bracket. "Most recent" is the signal: push openers, and when a closer arrives, it must match the top.
An opener. Push it.
Two ways to fail: a closer arrives when the stack is empty or its top does not match, or the string ends with openers still on the stack.
False only because of the final empty-stack check?Valid Parentheses
Given a string s made only of the characters ()[]{}, return true if every bracket is closed by the same type of bracket, in the right order. An opening bracket must be closed before any bracket opened earlier is closed.
"()[]{}" → true
"{[]}" → true
"([)]" → false (] closes while ( is still the latest open)Constraints
0 <= s.length <= 10^4scontains only the characters()[]{}.- An empty string counts as valid.
Evaluating expressions
Stacks are how calculators and compilers evaluate expressions. The simplest form is Reverse Polish Notation (RPN), where the operator comes after its two operands: 3 4 + means 3 + 4, and 2 3 4 * + means 2 + (3 × 4). Push numbers; on an operator, pop two, apply it, push the result.
Press Run (⌘ Enter) to see what happens.What does this print?
stack = []
for t in ["8", "3", "-", "2", "*"]:
if t in "+-*":
b = stack.pop()
a = stack.pop()
stack.append(a - b if t == "-" else a * b if t == "*" else a + b)
else:
stack.append(int(t))
print(stack)The monotonic stack
For each day's temperature, how many days until a warmer one? The brute force looks ahead from every day: O(n²). The trick is a stack of days still waiting for a warmer day, kept in decreasing temperature order (that is what "monotonic" means). When a warm day arrives, it answers every cooler day on top of the stack.
Day 0 has no answer yet. Push its index; it is waiting.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.while loop inside the for loop. Why is the monotonic stack still O(n)?Store indices, not values. The index gives you both the distance (i - j) and the value (temps[j]). For "next greater", keep the stack decreasing; for "next smaller", keep it increasing.
Daily Temperatures
Given a list of daily temperatures, return a list answer where answer[i] is how many days you have to wait after day i for a strictly warmer day. If no warmer day comes, answer[i] is 0.
[73, 74, 75, 71, 69, 72, 76, 73] → [1, 1, 4, 2, 1, 1, 0, 0]
[30, 40, 50, 60] → [1, 1, 1, 0]
[60, 50, 40] → [0, 0, 0]Constraints
1 <= temperatures.length <= 10^530 <= temperatures[i] <= 100
Complexity and common mistakes
Push, pop and peek are O(1). Bracket matching, RPN and monotonic stack problems are all O(n) time and O(n) space in the worst case (everything waiting on the stack at once).
- Popping an empty stack. Check
if stack(Python) orstack.length(JS) first. In Python,[].pop()raisesIndexError; in JS it quietly returnsundefined. - Forgetting the final check that the stack is empty in bracket matching.
- Swapping operands for
-and/: the first pop is the right-hand side. - Storing values instead of indices in a monotonic stack, then having no way to compute distances.
- Using
<=vs<carelessly. With equal temperatures,<means "strictly warmer". Read what the problem wants.
Which tool for each problem?
- stack
- Last in, first out. Push, pop and peek at the top, all O(1).
- LIFO
- Last in, first out: the most recently added item is removed first.
- monotonic stack
- A stack kept in increasing or decreasing order, popping anything that breaks the order. Solves next greater/smaller in O(n).
- Reverse Polish Notation
- Operators come after their operands (
3 4 +), so a stack evaluates it with no parentheses. - invariant
- A fact your loop keeps true at every step, like "the stack is in decreasing order".