Stacks & expression problems
Implement a stack and use it for bracket matching, expression evaluation and undo history.
By Invicly Tech, , in Data Structures & Algorithms. About 10 minutes to read.
In short
A stack is last-in, first-out: you push onto the top and pop from the top. It models nested structure, such as brackets, function calls and undo history. Any recursive algorithm can be rewritten with an explicit stack.
Think of it like this: A stack of plates: you always take the one you put down last.
Explained simply
A stack is a pile where you only touch the top. You put a new item on top (push), and you take the top item off (pop). The last thing you put in is the first thing you get back, which is called LIFO: last in, first out.
Stacks appear wherever things are nested or need to be undone in reverse order. The back button in a browser, the undo history in an editor, and matching brackets in code all follow the same rule: the most recent open thing must be dealt with first.
Your computer uses a stack every time a function calls another function. The call stack remembers where each function should continue when the inner one returns. That is why very deep recursion can crash a program: the call stack runs out of room.
In Python you do not need a special class. A normal list is a fine stack: append pushes onto the end, pop removes from the end, and stack[-1] peeks at the top. All three are fast.
Press Play on a diagram to walk through it one step at a time.
- 1'('
Push. Stack: (
- 2'['
Push. Stack: ( [
- 3']'
Top is [, pop. Stack: (
- 4')'
Top is (, pop. Stack empty.
- 5End
Empty stack means valid.
- Editor to Undo stack: Type A: push A1Type A: push A
- Editor to Undo stack: Type B: push B2Type B: push B
- Undo stack to Editor: Undo: pop B, revert it3Undo: pop B, revert it
- Editor to Redo stack: Push B onto redo4Push B onto redo
- Redo stack to Editor: Redo: pop B, apply again5Redo: pop B, apply again
- Editor to Undo stack: Push B back onto undo6Push B back onto undo
- Editor to Redo stack: New edit C: clear redo7New edit C: clear redo
In depth
Why the end of a Python list is the top
A Python list is a dynamic array: one block of memory holding pointers to its items. append writes into the next free slot, and when the block is full, CPython allocates a bigger one (roughly one eighth larger plus a little) and copies everything over. Copies are rare enough that the average cost per append is O(1), which is called amortised O(1). pop() from the end is O(1) and never copies.
The front of the list is a different story. pop(0) and insert(0, x) must shift every other pointer by one slot, so they are O(n). Use the end as the top and the stack is fast; use the front and every operation slows down as the stack grows.
If you need a stack that several threads share, queue.LifoQueue adds locking. For algorithms, a list is the right choice.
- push: append, amortised O(1)
- pop: pop(), O(1)
- peek: stack[-1], O(1)
- empty check: if not stack
Evaluating postfix expressions
In postfix notation, also called reverse Polish notation, operators come after their operands: 3 4 + means 3 + 4. There are no brackets and no precedence rules, because the order is already fixed.
One stack evaluates it in a single left-to-right pass. When you read a number, push it. When you read an operator, pop two numbers, apply the operator, and push the result. At the end, the stack holds exactly one value: the answer. If you ever need to pop from an empty stack, or more than one value remains at the end, the expression was malformed.
Order matters for minus and divide. The first value you pop is the right operand and the second is the left one, so for 8 2 - you pop 2, then 8, and compute 8 - 2. The whole evaluation is O(n) time and O(n) space for n tokens.
- 15 1 2
Push all three. Stack: 5 1 2
- 2+
Pop 2 and 1, push 3. Stack: 5 3
- 34 *
Push 4, then pop 4 and 3, push 12. Stack: 5 12
- 4+
Pop 12 and 5, push 17. Stack: 17
- 53 -
Push 3, then pop 3 and 17, push 14
- 6End
One value left: the answer is 14
From normal notation to postfix: the shunting-yard idea
People write infix expressions like 3 + 4 * 2, where precedence decides the order. Dijkstra's shunting-yard algorithm converts them to postfix with one stack for operators.
Read tokens left to right. Numbers go straight to the output. For an operator, first pop to the output every operator on the stack with higher or equal precedence (equal, because + - * / are left-associative), then push the new one. An opening bracket is pushed. A closing bracket pops operators to the output until the matching opening bracket, which is then discarded. At the end, pop everything that is left.
So 3 + 4 * 2 becomes 3 4 2 * +, and (3 + 4) * 2 becomes 3 4 + 2 *. Each token is pushed and popped at most once, so the conversion is O(n). Calculators and many expression parsers work this way.
- Numbers: straight to output
- Operator: pop higher or equal precedence first
- Right-associative ^ pops only strictly higher precedence
Replacing recursion with an explicit stack
A recursive function stores its unfinished work on the call stack. You can store that work on your own list instead. The pattern: push the starting item; while the stack is not empty, pop an item, process it, and push the sub-items it would have recursed on.
Why bother? CPython's default recursion limit is 1000 frames, and each frame costs far more memory than a list entry. A deeply nested structure, a long chain in a graph, or a degenerate tree can trigger RecursionError, while the explicit stack only grows a list on the heap. Raising the limit with sys.setrecursionlimit is possible but can crash the interpreter if the real C stack overflows.
One thing changes: items come off in reverse order of pushing. If processing order matters, as in preorder tree traversal, push the right child before the left so the left is handled first.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Implement a stack on a list~45m
- 2Match brackets with a stack~45m
- 3Evaluate postfix expressions~45m
- 4Replace recursion with an explicit stack~45m
Key points
- push, pop and peek: O(1) with a Python list using append and pop.
- Bracket matching is O(n) time and O(n) space.
- Postfix expressions evaluate with one stack in a single pass.
- The call stack is a stack; deep recursion can overflow it.
Key terms
Tap a card to flip it. 0/4 known
Examples
def is_valid(s): # O(n)
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
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
print(is_valid('([]{})'), is_valid('(]')) # True FalseA postfix calculator
Input tokens: 5 1 2 + 4 * + 3 -. Step 1: push numbers. Step 2: on an operator, pop the right operand first, then the left, and push the result. Step 3: the last value on the stack is the answer, 14. Division uses int(a / b), which truncates toward zero like most calculator problems expect, while Python's // rounds toward minus infinity (-7 // 2 is -4, but int(-7 / 2) is -3).
def eval_postfix(tokens): # O(n) time, O(n) space
ops = {'+': lambda a, b: a + b, '-': lambda a, b: a - b,
'*': lambda a, b: a * b, '/': lambda a, b: int(a / b)}
stack = []
for tok in tokens:
if tok in ops:
b = stack.pop() # right operand comes off first
a = stack.pop()
stack.append(ops[tok](a, b))
else:
stack.append(int(tok))
return stack.pop()
print(eval_postfix("5 1 2 + 4 * + 3 -".split())) # 14Summing a deeply nested list without recursion
A recursive sum over nested lists crashes with RecursionError once nesting passes about 1000 levels. Step 1: put the outer list on a stack. Step 2: pop an item; if it is a list, push its elements; otherwise add it to the total. Step 3: repeat until the stack is empty. The test builds 10,000 levels of nesting, and the explicit stack handles it easily in O(n) time.
def total(nested):
stack, s = [nested], 0
while stack:
item = stack.pop()
if isinstance(item, list):
stack.extend(item)
else:
s += item
return s
deep = [1]
for _ in range(10_000):
deep = [deep, 1]
print(total(deep)) # 10001Quick reference
- Python stack: append to push, pop() to pop, stack[-1] to peek, all O(1)
- Never use pop(0) or insert(0, x) for a stack: both are O(n)
- Postfix: number -> push; operator -> pop right, pop left, push result
- Shunting-yard turns infix into postfix in O(n) with one operator stack
- CPython's default recursion limit is 1000; an explicit stack has no such limit
- Undo and redo: two stacks; a new edit clears the redo stack
- Min stack: store (value, min so far) pairs for O(1) get_min
Common mistakes
- Popping from an empty stack instead of returning invalid.
- Forgetting to check the stack is empty at the end.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Reverse a string using a stack (not slicing).
- Exercise 2medium
Design a MinStack with push, pop, top and get_min, all O(1).
- Exercise 3hard
Convert a tokenised infix expression with + - * / and brackets into postfix (shunting-yard).
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use a list or collections.deque as a stack in Python?
- Both give O(1) push and pop at the end. A list is the usual choice; deque helps only if you also need fast operations at the front.
- What is a stack overflow?
- It happens when the call stack runs out of space, usually because of very deep or endless recursion. In Python you see RecursionError when the recursion limit is reached.
- Is a stack the same as the stack memory in a program?
- They are related. The call stack is a stack data structure that the runtime uses to store function frames; the idea of last in, first out is the same.
- Can a stack be built on a linked list?
- Yes. Push and pop at the head of a singly linked list are both O(1). In Python a list is usually faster in practice.