Stacks (DSA #4)
Press Ctrl-Z and the last edit disappears; press it again and the edit before that disappears. Your browser’s back button does the same. Both are showing you a stack: the most recently added item is the first one used. That last-in-first-out order is trivial to state and surprisingly powerful — it underlies parsing, expression evaluation, recursion, and a whole family of “next greater element” problems.
This chapter covers the stack’s interface, its two implementations, and the four patterns worth internalizing. Cross-reference: Min Stack shows the design question of tracking a running minimum.
LIFO: the interface
A stack supports three operations, all \(O(1)\):
- push(x) — add to the top.
- pop() — remove and return the top.
- peek() — look at the top without removing.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=1.9cm, minimum height=0.62cm, font=\small}]
\node[c, fill=blue!12] (a) at (0,0) {3};
\node[c, fill=blue!12] (b) at (0,0.62) {7};
\node[c, fill=orange!35, very thick] (c) at (0,1.24) {1};
\draw[->, thick] (1.5,1.55) -- (0.95,1.40) node[midway, above, font=\scriptsize] {push/pop};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-0.45) {only the top is accessible};
\end{tikzpicture}
Because only the top matters, you can build a stack on an array (push/pop at the end) or on a linked list (push/pop at the head). Both give \(O(1)\).
stack = []
stack.append(3) # push
stack.append(7)
top = stack[-1] # peek -> 7
stack.pop() # pop -> 7
Application 1: balanced parentheses
Scan the string; push every opening bracket; on a closing one, check that it matches the top and pop. At the end the stack must be empty.
PAIRS = {")": "(", "]": "[", "}": "{"}
def is_balanced(s):
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in PAIRS:
if not stack or stack.pop() != PAIRS[ch]:
return False
return not stack # leftover opens = unbalanced
This is the parser skeleton: the stack remembers “what still needs closing”, and LIFO guarantees the innermost bracket closes first. The same shape validates XML/HTML tags and evaluates expressions.
Application 2: expression evaluation
Postfix (reverse Polish) notation removes parentheses entirely: operands push, operators pop two and push the result.
def eval_rpn(tokens):
stack = []
for tok in tokens:
if tok in "+-*/":
b, a = stack.pop(), stack.pop() # order matters
stack.append(eval_operation(a, b, tok))
else:
stack.append(int(tok))
return stack[0]
print(eval_rpn(["2", "1", "+", "3", "*"])) # (2 + 1) * 3 = 9
The subtlety: subtraction and division are not commutative, so you must pop the right operand first (b) and the left second (a).
Application 3: the call stack and recursion
Every function call pushes a frame; returning pops it. Recursion is literally the language using a stack, which is why an iterative version can replace it with an explicit one.
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
# each call pushes a frame until n == 1, then they pop back
A deep recursion can overflow the call stack; converting it to an explicit stack trades the language’s stack for your heap.
Application 4: monotonic stack
The real superpower. To find the next greater element for each item, keep a stack of indices whose answer is still unknown, in decreasing value order. When a new value is larger than the stack’s top, it is the answer for that top.
def next_greater(nums):
res = [-1] * len(nums)
stack = [] # indices, decreasing values
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
res[stack.pop()] = x # x is the next greater for that index
stack.append(i)
return res
print(next_greater([2, 1, 2, 4, 3])) # [4, 2, 4, -1, -1]
Each index is pushed and popped at most once, so the whole pass is \(O(n)\) despite the inner while — the amortized argument from Chapter 1. The same skeleton solves largest rectangle in histogram, daily temperatures, and stock span.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.72cm, minimum height=0.66cm, font=\small\bfseries},
a/.style={->, thick}]
\foreach \v [count=\i from 0] in {2,1,2,4,3} {
\node[c, fill=blue!10] at (\i*0.8,0) {\v};
\node[font=\scriptsize\ttfamily] at (\i*0.8,-0.55) {\i};
}
\draw[a, red!70!black] (0.8,0.7) .. controls (1.6,1.4) .. (2.4,0.7);
\draw[a, red!70!black] (2.4,0.7) .. controls (2.8,1.4) .. (3.2,0.7);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (1.6,-1.0) {a rising value resolves every shorter stack top at once};
\end{tikzpicture}
Design application: min stack
A stack that also returns its minimum in \(O(1)\) cannot afford to scan. Keep a second stack where each entry is the minimum so far. Cross-reference: the full treatment is in Min Stack.
class MinStack:
def __init__(self):
self.data, self.mins = [], []
def push(self, x):
self.data.append(x)
self.mins.append(x if not self.mins else min(x, self.mins[-1]))
def pop(self):
self.mins.pop()
return self.data.pop()
def get_min(self):
return self.mins[-1]
The invariant: self.mins[-1] always equals the minimum of everything currently in self.data.
Pitfalls
- Popping an empty stack. Guard with a length check; the “valid parentheses” bug is often a missing
if not stack. - Wrong operand order in RPN. Pop the right operand first;
a - bis notb - a. - Using a stack when you need FIFO. BFS needs a queue (Chapter 5); using a stack turns it into DFS.
- Forgetting the amortized argument. The monotonic
whileloop looks \(O(n^2)\) but is \(O(n)\); each element enters and leaves once. - Mixing up peek semantics. Decide whether
peek/topthrows or returnsNoneon empty, and be consistent.
Why does the monotonic-stack loop still run in \(O(n)\)? When must you use a stack instead of a queue?
ASolution
Because each index is pushed once and popped at most once, so the total work of the inner while across the whole scan is bounded by \(n\). Use a stack when order should be last-in-first-out — parsing, undo, next-greater problems — and a queue when it should be first-in-first-out, as in BFS.
Next: Queues and Deques (DSA #5) — first-in-first-out, and the sliding-window trick that comes with it.