Skip to content

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).

15 min read0/4 questions

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, push 2, push 3, then pop
  1. 3 ← top
  2. 2
  3. 1 ← bottom

Push 1. It sits at the bottom.

1/4
Python
stack = []stack.append(1) # pushstack.append(2)stack.append(3)print(stack[-1]) # peek: 3print(stack.pop()) # pop: 3print(stack) # [1, 2]print(len(stack) == 0) # is it empty?
Output
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.

Checking ([]{})
(
0
↑i
[
1
]
2
{
3
}
4
)
5
stack = (

An opener. Push it.

1/6

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.

Quick check
Which string makes a correct bracket checker return False only because of the final empty-stack check?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

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^4
  • s contains only the characters ()[]{}.
  • An empty string counts as valid.
def is_valid(s: str) -> bool: # Push opening brackets; each closing bracket must match the latest one. pass

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.

Python
def eval_rpn(tokens): stack = [] for t in tokens: if t in "+-*/": b = stack.pop() # popped second, used second a = stack.pop() if t == "+": stack.append(a + b) elif t == "-": stack.append(a - b) elif t == "*": stack.append(a * b) else: stack.append(int(a / b)) # truncate toward zero else: stack.append(int(t)) return stack[0] print(eval_rpn(["2", "3", "4", "*", "+"]))print(eval_rpn(["4", "13", "5", "/", "+"]))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Days until warmer: [73, 74, 75, 71, 69, 72, 76, 73]
73
0
↑i
74
1
75
2
71
3
69
4
72
5
76
6
73
7
stack (days) = [0]answer = [0,0,0,0,0,0,0,0]

Day 0 has no answer yet. Push its index; it is waiting.

1/6
Python
def days_until_warmer(temps): answer = [0] * len(temps) stack = [] # indices, temperatures decreasing for i, t in enumerate(temps): while stack and temps[stack[-1]] < t: j = stack.pop() answer[j] = i - j stack.append(i) return answer print(days_until_warmer([73, 74, 75, 71, 69, 72, 76, 73]))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
There is a while loop inside the for loop. Why is the monotonic stack still O(n)?
Need a nudge? A hint rules out a wrong answer.

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.

ChallengeMedium

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^5
  • 30 <= temperatures[i] <= 100
def daily_temperatures(temperatures: list[int]) -> list[int]: # Keep a stack of days still waiting for a warmer day. pass

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) or stack.length (JS) first. In Python, [].pop() raises IndexError; in JS it quietly returns undefined.
  • 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.
Match the pairs0/4 matched

Which tool for each problem?

Choose an item, then its match on the other side.
Key terms
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".
Interview pattern: Stack31 problemsSpot it: Matching brackets · undo · next greater element · evaluate expressions