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.

6 min readUpdated 2026-11-30
In This Lesson
  • 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 forward j = i + 1, i + 2, ... until temps[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

StructureOrderPython ContainerPushPopPeek
StackLIFO (Last-In, First-Out)list (stack = [])stack.append(x) (O(1))stack.pop() (O(1))stack[-1]
QueueFIFO (First-In, First-Out)collections.dequeq.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:

python
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 stack

Edge Cases Covered

  • Closing bracket when stack is empty (e.g., ")("): not stack catches it before calling stack.pop() (preventing IndexError).
  • Mismatched pair (e.g., "([)]"): stack.pop() returns '[', which does not match pairs[')'] == '(', returning False.
  • Unclosed leftovers (e.g., "((("): Loop finishes with items still on stack, so return not stack returns False.
  • Empty string "": Loop skips and return not stack returns True.

Pattern 2: Monotonic Stack ("Waiting for a Better Value")

Monotonic Decreasing Stack: Waiting for a Warmer Day

Waiting Stack (Decreasing)

75°71°69°

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 ansStack Indices After Step (Temps)
073None—[0] (73)
1740 (73 < 74)ans[0] = 1 - 0 = 1[1] (74)
2751 (74 < 75)ans[1] = 2 - 1 = 1[2] (75)
371None (75 >= 71)—[2, 3] (75, 71)
469None (71 >= 69)—[2, 3, 4] (75, 71, 69)
5724 (69 < 72), 3 (71 < 72)ans[4] = 1, ans[3] = 2[2, 5] (75, 72)
6765 (72 < 76), 2 (75 < 76)ans[5] = 1, ans[2] = 4[6] (76)
773None (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].

Two Classic Monotonic Stack Bugs
  1. Pushing values instead of indices: If you push t instead of i, you lose the ability to compute distances (i - prev_idx) and to write answers into ans[prev_idx]. Always push indices i!
  2. Using >= instead of > for strictly warmer: If today is 75 and tomorrow is also 75, tomorrow is not strictly warmer—so keep t > temps[stack[-1]] (only pop on strict inequality unless equal counts).
Decreasing vs Increasing Stack Cheat Rule
  • 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 ClueData StructureTime / Space
Matching brackets, HTML/XML tags, expression evaluationLIFO 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 StackO(n) / O(n)
Largest Rectangle in Histogram / Stock Span / Trapping Rain WaterMonotonic StackO(n) / O(n)

Try It Yourself in the Playground

Run Valid Parentheses, Daily Temperatures (Monotonic Stack), and Next Smaller Element below:

Python 3Try It Live: Stack Matching & Monotonic Stack
Output

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

Check Your Understanding

In daily_temperatures, how many times can any single index be popped from the monotonic stack?

Check Your Understanding

In is_valid_brackets, if the loop finishes and stack is still non-empty (e.g., '(()'), what should the function return?

Check Your Understanding

You want to find the Next Smaller Element to the right for each item in an array. Which invariant should your monotonic stack maintain?