2. Linear Patterns, Stacks & Queues
Stacks, Queues (deque) & Monotonic Stack Patterns
Master LIFO stacks and FIFO queues in Python, solve nested bracket matching, and unlock O(n) Next Greater Element and Daily Temperatures using a monotonic stack.
- Use Python list as an O(1) LIFO stack and collections.deque as an O(1) FIFO queue
- Solve matching/nesting problems cleanly with a stack
- Apply a monotonic stack to find Next Greater Elements in O(n) time
Stacks (Last-In, First-Out) and Queues (First-In, First-Out) look deceptively simple, yet one specialized variant—the Monotonic Stack—transforms notoriously tricky O(n²) array problems into sleek O(n) solutions.
Why It Matters: The Problem with Brute Force
Suppose you are given daily temperatures [73, 74, 75, 71, 69, 72, 76, 73] and asked: "For each day, how many days until a warmer temperature?"
- Brute force: For every index
i, scan forwardj = i + 1, i + 2, ...untiltemps[j] > temps[i]. On a decreasing array like[90, 89, 88, ..., 1], every day scans to the end →O(n²)time. - Monotonic Stack: Keep a stack of unresolved day indices in strictly decreasing temperature order. As soon as a warmer day arrives, resolve all cooler waiting days in one pop loop. Every index is pushed once and popped at most once →
O(n)time,O(n)space.
Python Stack vs Queue Cheat Sheet
| Structure | Order | Python Container | Push | Pop | Peek |
|---|---|---|---|---|---|
| Stack | LIFO (Last-In, First-Out) | list (stack = []) | stack.append(x) (O(1)) | stack.pop() (O(1)) | stack[-1] |
| Queue | FIFO (First-In, First-Out) | collections.deque | q.append(x) (O(1)) | q.popleft() (O(1)) | q[0] |
Never use list.pop(0) as a queue—shifting elements makes every dequeue O(n)!
Pattern 1: Matching & Nesting with a LIFO Stack
Whenever you validate nested structures (brackets, HTML tags, undo/redo, function call frames), the most recently opened item must be closed first:
def is_valid_brackets(s: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
stack: list[str] = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stackEdge Cases Covered
- Closing bracket when stack is empty (e.g.,
")("):not stackcatches it before callingstack.pop()(preventingIndexError). - Mismatched pair (e.g.,
"([)]"):stack.pop()returns'[', which does not matchpairs[')'] == '(', returningFalse. - Unclosed leftovers (e.g.,
"((("): Loop finishes with items still onstack, soreturn not stackreturnsFalse. - Empty string
"": Loop skips andreturn not stackreturnsTrue.
Pattern 2: Monotonic Stack ("Waiting for a Better Value")
Waiting Stack (Decreasing)
72° Arrives → Pops 69° & 71°!
75° stays waiting; stack becomes [75°, 72°]
Indices wait on the stack in decreasing temperature order; when a warmer day (72) arrives, cooler indices (69, 71) pop in O(1) each.
Mental Model & Step-by-Step Dry-Run Trace
Imagine people standing in a line holding signs with their temperatures. Whenever a newcomer arrives who is warmer than the person at the top of the waiting stack, that waiting person finally gets their answer (new_index - waiting_index) and steps out of line!
Trace daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73]):
Day (i) | Temp (t) | Popped Indices (temps[prev] < t) | Updates to ans | Stack Indices After Step (Temps) |
|---|---|---|---|---|
0 | 73 | None | — | [0] (73) |
1 | 74 | 0 (73 < 74) | ans[0] = 1 - 0 = 1 | [1] (74) |
2 | 75 | 1 (74 < 75) | ans[1] = 2 - 1 = 1 | [2] (75) |
3 | 71 | None (75 >= 71) | — | [2, 3] (75, 71) |
4 | 69 | None (71 >= 69) | — | [2, 3, 4] (75, 71, 69) |
5 | 72 | 4 (69 < 72), 3 (71 < 72) | ans[4] = 1, ans[3] = 2 | [2, 5] (75, 72) |
6 | 76 | 5 (72 < 76), 2 (75 < 76) | ans[5] = 1, ans[2] = 4 | [6] (76) |
7 | 73 | None (76 >= 73) | — | [6, 7] (76, 73) |
Indices [6, 7] remain on the stack at the end, keeping their default 0 in ans = [1, 1, 4, 2, 1, 1, 0, 0].
- Pushing values instead of indices: If you push
tinstead ofi, you lose the ability to compute distances (i - prev_idx) and to write answers intoans[prev_idx]. Always push indicesi! - Using
>=instead of>for strictly warmer: If today is75and tomorrow is also75, tomorrow is not strictly warmer—so keept > temps[stack[-1]](only pop on strict inequality unless equal counts).
- Looking for Next Greater (warmer, taller, bigger): maintain a monotonically decreasing stack; pop while
curr > stack_top. - Looking for Next Smaller (cheaper, shorter, histogram boundaries): maintain a monotonically increasing stack; pop while
curr < stack_top.
Pattern Recognition: When to Reach for Stack / Queue / Monotonic Stack
| Interview Prompt Clue | Data Structure | Time / Space |
|---|---|---|
| Matching brackets, HTML/XML tags, expression evaluation | LIFO Stack (list) | O(n) / O(n) |
First-come-first-served simulation, BFS levels, sliding max (deque) | FIFO Queue (deque) | O(n) / O(n) |
| "Next greater/smaller element to the right/left" | Monotonic Stack | O(n) / O(n) |
| Largest Rectangle in Histogram / Stock Span / Trapping Rain Water | Monotonic Stack | O(n) / O(n) |
Try It Yourself in the Playground
Run Valid Parentheses, Daily Temperatures (Monotonic Stack), and Next Smaller Element below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why does daily_temperatures push the index i onto the stack instead of pushing the temperature value t?
Quick Checkpoints
In daily_temperatures, how many times can any single index be popped from the monotonic stack?
In is_valid_brackets, if the loop finishes and stack is still non-empty (e.g., '(()'), what should the function return?
You want to find the Next Smaller Element to the right for each item in an array. Which invariant should your monotonic stack maintain?