Stacks — last in, first out
The LIFO abstract data type, its array and linked-list implementations, amortised resizing, the call stack, bracket matching, expression evaluation and monotonic stacks — from first principles to interview-ready patterns.
AChapter introduction
Prerequisites
You should be comfortable with Python lists and indexing, writing small classes, for/while loops, simple recursion (a function that calls itself), and basic Big-O notation. The chapters on Time & Space Complexity and Arrays & Hashing cover everything needed; in particular, knowing that a Python list is a dynamic array will make Section F much easier.
Learning objectives
After completing this chapter you will be able to:
- Define a stack as an abstract data type, state the LIFO rule, and name its operations and error conditions (underflow, overflow).
- Implement a stack from scratch twice — on a resizing array and on a singly linked list — and explain exactly what happens in memory on every
pushandpop. - Prove that a doubling array gives amortised O(1) push, and explain why it must shrink at one-quarter (not one-half) full.
- Explain how the call stack makes function calls and recursion work, and why deep recursion overflows.
- Solve the classic stack problems: balanced brackets, postfix evaluation, infix-to-postfix conversion (shunting-yard), min-stack, and queue-from-two-stacks.
- Recognise the monotonic stack pattern (“next greater element”, “largest rectangle”) and argue its O(n) running time.
- Choose correctly between
list,collections.dequeandqueue.LifoQueuein Python.
BFundamental understanding
What is a stack?
Picture a spring-loaded pile of plates in a cafeteria. You can only put a clean plate on top, and you can only take the top plate. The plate you put down last is the first one taken. A stack is a collection that enforces exactly this discipline. Sedgewick and Wayne define it as a collection “based on the last-in-first-out (LIFO) policy”, and CLRS define it by its delete operation: the element removed is always the one most recently inserted. [1][2]
•
push(x): S ← ⟨s1, …, sk, x⟩;
•
pop(): if k = 0 signal underflow; otherwise return sk and set S ← ⟨s1, …, sk−1⟩;
•
peek() / top(): return sk without removing it; is_empty(): test k = 0; size(): return k.
The defining axiom is pop(push(S, x)) = (S, x): a pop undoes the most recent push. [2][19]
Two words describe the error states. Popping or peeking an empty stack is underflow; pushing onto a stack that has a fixed maximum size and is already full is overflow. [19][2] A stack backed by a growable array or a linked list never overflows in the ADT sense — it simply asks for more memory — but the call stack of a running program does have a fixed size, which is where the famous “stack overflow” error comes from (Section F.5). [20]
An abstract data type, not a memory layout
“Stack” names a behaviour, not a storage scheme. Any structure that can add and remove at one end in constant time can implement it: an array whose last used slot is the top, or a linked list whose head node is the top. Both are standard textbook implementations. [1][2] In Python, the built-in list already behaves as a stack through append() and argument-less pop(), which the official tutorial describes as using a list as a stack. [4]
Why does this concept exist?
Many computations are nested: a function calls a function that calls a function; a bracket opens inside another bracket; an HTML tag contains other tags; an edit is undone after a later edit was undone. Nested structure always closes in the reverse order it opened. A stack is the data structure whose removal order is the reverse of its insertion order, so it is the natural memory for “what am I in the middle of, and what do I return to next?”. That is why stacks appear in compilers, interpreters, processors and operating systems. [20][15]
A little history
Alan Turing used the terms “bury” and “unbury” for calling and returning from subroutines in his 1946 design for the ACE computer. Klaus Samelson and Friedrich L. Bauer developed the stack principle (German Kellerprinzip, “cellar principle”) for translating arithmetic formulas, filed a patent on it in 1957, and Bauer received the IEEE Computer Pioneer Award in 1988 for the invention of the stack principle. [19] In 1961 Edsger Dijkstra described the shunting-yard algorithm, which uses an operator stack to convert ordinary infix formulas into postfix order for the ALGOL 60 compiler. [21][18] Today stacks are built into hardware: the x86 instruction set has push, pop, call and ret instructions that operate on a stack in memory. [14]
Fundamental principles
- Restricted access is a feature. By forbidding access to anything but the top, a stack can make every operation O(1) and makes programs easier to reason about: no index bookkeeping, no searching. [2]
- Reversal. Pushing a sequence and popping it all gives the sequence back reversed. Every stack algorithm exploits this: matching the most recently opened bracket, returning to the most recent caller, undoing the most recent edit.
- Deferred work. A stack stores work you have started but cannot finish yet (an open bracket waiting for its partner, a caller waiting for a return value, an operator waiting for its right operand). The top is always the most urgent pending item. [17]
CThe problem statement
The “most recent unfinished item” problem
Stacks solve a family of problems rather than one. A representative member, used throughout this chapter, is bracket matching:
| Component | Specification |
|---|---|
| Input | A string s of length n over the characters ( ) [ ] { } (and possibly others to ignore). |
| Output | True if every closing bracket closes the most recently opened, still-unclosed bracket of the same type, and no bracket is left open; otherwise False. |
| Typical constraints | LeetCode 20 “Valid Parentheses” uses 1 ≤ n ≤ 104; an O(n) single pass is expected. |
| Key observation | “Most recently opened, still unclosed” is precisely the top of a stack of open brackets. |
Why the naive approach is inefficient
A natural first idea is to repeatedly find and delete an adjacent matching pair such as () or [] until nothing changes. Each scan is O(n), each scan may remove only one pair, and building the shortened string costs another O(n); for an input such as ((((…)))) that is n/2 rounds, so Θ(n2) work. Counting brackets with a single integer is O(n) but wrong once there are several bracket types: ([)] has balanced counts for both types yet is not properly nested. (Our own worked example; both claims are checked by the lab in Section E.)
Limitations of other approaches
A plain array with an index lets you reach any element, but then you must manage that index yourself and nothing stops code from reading the wrong slot. A queue removes the oldest item, which is the wrong order for nesting: the bracket that must close first is the newest one. A recursive-descent parser does work, but only because recursion uses the call stack implicitly — which means it is still a stack, with a hard depth limit (Python’s default recursion limit is 1000 frames). [8]
How a stack improves the solution
Scan once. Push every opening bracket. On a closing bracket, pop and check that the popped opener matches; at the end, require the stack to be empty. Every character is pushed at most once and popped at most once, so the algorithm is Θ(n) time and O(n) space in the worst case (all openers). The same skeleton — push what is unfinished, pop when it is finished — evaluates expressions, converts infix to postfix, and drives depth-first search. [17][24]
DVisual whiteboard explanations
All diagrams in this chapter use one colour language. Learn it once and every picture reads the same way:
- Three items were pushed in the order 3, 7, 5. The first one pushed (3) sits at the bottom.
- Left:
push(9)enters through the only opening and lands on 5, becoming the new top. - Right: on the same stack,
pop()removes 5 — the most recent push — and 7 becomes the top (yellow).peek()would read the top without removing it.
- Array-backed: items live in contiguous slots 0…n−1 with the bottom at index 0. The size
n = 4doubles as the index of the next free slot, so the top isdata[n−1]and a push writesdata[n]. - The array has capacity 8 but only 4 slots are in use; the spare room makes most pushes a single write.
- Linked list: each node holds a value and a pointer to the node below it. The list’s head is the top, so push and pop only ever touch the head.
- Start empty:
top = −1(array view) orhead = None(list view). - Each push places the new item above the old top; the top pointer moves up by one.
pop()returns 5 — the last item pushed — and the top drops back to 7.push(9)reuses the slot that 5 vacated.
- push(9): ① create node 9; ② set
node.next = head(purple); ③ sethead = node(yellow). Order matters — doing ③ first would lose the rest of the list. - pop(): remember
node = head, sethead = head.next, returnnode.value. The old node is no longer referenced and is reclaimed by the garbage collector.
EInteractive lab
The labs below are fully working. Change the inputs, step forwards and backwards, and read the state panel. Labs 2–5 preview algorithms explained in detail in Sections F, I and N; feel free to come back to them later.
FInternal working
F.1 Memory representation of an array-backed stack
An array-backed stack keeps two pieces of state: a block of slots data and a count n. Items occupy data[0..n−1] with the bottom at index 0, so the top is data[n−1] and the next push writes data[n]. Keeping the top at the end of the array is essential: adding or removing at the end moves nothing, whereas adding at the front would shift every element. Python’s documentation states the consequence for lists directly — append is O(1) amortised and pop(k) costs O(n−k), so pop() from the end is O(1) while pop(0) is O(n). [6][4]
In CPython a list is exactly this structure: a contiguous array of pointers to objects, plus a size and an allocated capacity. list.append is therefore a stack push and list.pop() a stack pop. [10][4]
F.2 Execution flow of push and pop (array)
- push(x): if
n == capacity, allocate a new array of twice the capacity and copy thenitems (the only expensive step); writedata[n] = x; incrementn. - pop(): if
n == 0, raise an underflow error; decrementn; readx = data[n]; clear the slot (data[n] = None) so the stack does not keep a dead object alive; ifnhas fallen to a quarter of the capacity, shrink to half; returnx. - peek(): if
n == 0, raise; returndata[n−1]. Nothing changes.
The doubling-on-full and halving-at-one-quarter policy is the one used by Sedgewick and Wayne’s ResizingArrayStack. [1] Clearing the popped slot matters in garbage-collected languages: if the array still points at a popped object, that object cannot be reclaimed even though the program can no longer reach it through the stack (Java programmers call this loitering).
- The array has capacity 4 and holds 4 items, so
push(2)finds no room. - A new block of capacity 8 is allocated and the 4 items are copied across (4 purple arrows = 4 units of extra work).
- 2 is written into slot 4; the old block is released.
- The next three pushes (slots 5–7) cost one write each — the copying is “paid back” over them.
F.3 What CPython actually does
CPython does not double. Its list_resize over-allocates by about one eighth of the requested size plus a small constant, rounded to a multiple of 4; the source comment gives the growth pattern “0, 4, 8, 16, 24, 32, 40, 52, 64, 76, …”. [10] Any constant-factor growth (here about 1.125×) still gives amortised O(1) appends — only the constant changes. [2] You can watch it yourself: running sys.getsizeof after each append on CPython 3.11 shows capacity jumps at lengths 1, 5, 9 and 17, to 4, 8, 16 and 24 slots — matching the comment. (Measured by us.)
F.4 Execution flow of push and pop (linked list)
- push(x):
head = Node(x, head)— the new node’snextis the old head, then the head moves to the new node. - pop(): if
head is None, raise;node = head;head = node.next; returnnode.value.
Sedgewick and Wayne’s linked-list Stack implements push and pop by inserting and removing at the beginning of the list, exactly as above. [1] No step depends on the number of nodes, so both are Θ(1) in the worst case. The price is one extra pointer per item and an allocation for every push. [2]
F.5 The call stack: the stack you use without noticing
Every running program has a call stack. When a function is called, a stack frame is pushed holding its return address, parameters and local variables; when it returns, the frame is popped and execution resumes at the saved return address. [20] The operating-systems textbook OSTEP describes the stack as the part of a process’s address space used “to keep track of where it is in the function call chain” and to hold local variables, parameters and return values. [15] On x86, call pushes the return address and the stack grows toward lower addresses. [14]
maincallsfact(3): a frame withn = 3is pushed. It cannot finish untilfact(2)returns, so it waits.fact(2)andfact(1)are pushed in turn.fact(1)is the base case and returns 1 immediately.- Frames pop in reverse order:
fact(2)computes 2 × 1 = 2, thenfact(3)computes 3 × 2 = 6, and control returns tomain.
RecursionError instead of overflowing the C stack. [8]
Interpreters use stacks too. CPython compiles Python to bytecode that operates on a value stack — the dis documentation calls it STACK and says its top “corresponds to STACK[-1]”. [9] Every Java Virtual Machine frame “contains a last-in-first-out (LIFO) stack known as its operand stack”, and WebAssembly instructions likewise “interact with an implicit stack”. [12][13]
F.6 Edge cases
| Situation | Correct behaviour |
|---|---|
| Pop or peek on an empty stack (underflow) | Raise an exception (Python’s list.pop() raises IndexError) or return a sentinel by documented contract; never return garbage. [19] |
| Push on a full fixed-capacity stack (overflow) | Raise, block (as queue.LifoQueue(maxsize) does by default), or grow. [7] |
Storing None as a value | Do not use None both as data and as the “empty” signal; test emptiness with len() or is_empty(). |
| Shrinking | Shrink at one-quarter, not one-half, full; otherwise alternating push/pop at the boundary causes a copy on every operation (Section G.3). [1] |
| Iteration order | Iterating a Python list used as a stack goes bottom → top; iterate reversed(stack) for pop order. |
| Concurrency | Separate peek-then-pop calls are not atomic across threads; use queue.LifoQueue (internally locked) or your own lock. [7] |
| Very deep recursion | Convert to an explicit stack (Section I.9) rather than raising the recursion limit; a too-high limit can crash the interpreter. [8] |
GMathematical foundation
G.1 The LIFO axioms
A stack is fully specified by equations relating its operations (an algebraic specification): for every stack S and item x, top(push(S, x)) = x, pop(push(S, x)) = S, isEmpty(new()) = true and isEmpty(push(S, x)) = false; top(new()) and pop(new()) are errors (underflow). Any implementation satisfying these equations is a correct stack. [19]
G.2 Invariant for the array implementation
None. With shrinking, also n ≥ capacity/4 whenever n > 0.Proof sketch. The empty constructor establishes it. push only writes slot n (which is free, after growing if needed) then increments n, so the prefix property and the “free slots are None” property both hold afterwards. pop decrements n, reads the old top and sets it to None, restoring both properties. Resizing copies exactly the prefix. Hence each method preserves the invariant, and the axioms of G.1 follow from it.
G.3 Amortised analysis of the doubling array
Count one unit for each element write, including copies. Starting from capacity 1, the i-th push copies i − 1 items when i − 1 is a power of two, and otherwise copies nothing. For n pushes:
This is the aggregate method. The accounting method gives the same bound: charge each push 3 units — 1 pays for its own write and 2 are saved; when a full array of size m doubles, the m/2 items pushed since the last resize have saved m units, exactly enough to copy all m items. CLRS present both methods, including this dynamic-table example. [2][3]
ResizingArrayStack, and CLRS analyse the same contraction rule for dynamic tables. [1][2]Growth by a constant amount (say +10 slots) is not enough: then a resize happens every 10 pushes and copies Θ(n) items, so n pushes cost Θ(n2). Lab 6 below lets you compare the two policies.
G.4 The “pushed once, popped once” argument
Many stack algorithms have a loop like while stack and condition: stack.pop() inside a for loop, which looks quadratic. It is not: each element is pushed exactly once, so it can be popped at most once, so the total number of pops over the entire run is at most n. Summing, the whole algorithm does O(n) pushes + O(n) pops + O(n) loop tests. CLRS use the same argument for a stack with a MULTIPOP(k) operation: any sequence of n push/pop/multipop operations costs O(n), so O(1) amortised each, even though one multipop can cost Θ(n). [2] The potential function is simply Φ = number of items on the stack. [2]
G.5 Correctness of bracket matching
Define a string to be balanced if it is empty, or XY for balanced X, Y, or (X) / [X] / {X} for balanced X. Invariant of the checker: after reading a prefix p, the stack holds, bottom to top, exactly the opening brackets of p that are not yet closed, in the order they were opened. A closing bracket is legal iff it matches the latest unclosed opener — the top — so the pop-and-compare test is both necessary and sufficient; and the whole string is balanced iff no opener remains, i.e. the stack ends empty.
G.6 How many orders can a stack produce?
Push the numbers 1, 2, …, n in order, popping whenever you like and writing down each popped value. Not every permutation is reachable — with n = 3 you cannot output 3 1 2. The number of reachable output orders is the Catalan number Cn = (2n choose n)/(n+1) (1, 2, 5, 14, 42, …), because a valid push/pop sequence is exactly a balanced bracket string of n pairs. This question was posed by Knuth in 1968, and the related stack-sortable permutations are counted by the same numbers. [23]
HOperations and complexity analysis
Assumptions: n = number of items currently on the stack. “Resizing array” means doubling when full and halving at one-quarter full. Copying one item and allocating one node are O(1). Python costs are those documented for CPython’s list and collections.deque. [6][5]
| Operation | Best case | Average case | Worst case | Auxiliary space |
|---|---|---|---|---|
| push — resizing array | Θ(1) | Θ(1) amortised | Θ(n) (the push that triggers a resize) | Θ(n) temporarily during a resize |
| pop — resizing array | Θ(1) | Θ(1) amortised | Θ(n) (the pop that triggers a shrink) | O(1) (Θ(n) during a shrink) |
| push / pop — linked list | Θ(1) | Θ(1) | Θ(1) | O(1) (one node per push) |
| peek / is_empty / size | Θ(1) | Θ(1) | Θ(1) | O(1) |
| search for a value (not a stack operation) | Θ(1) (at the top) | Θ(n) | Θ(n) | O(1) |
| Any sequence of m operations (either implementation) | Θ(m) | Θ(m) | Θ(m) | Θ(max size) |
| Storage for n items | array: between n and 4n slots (with quarter-shrink); list: n nodes × (value + pointer + object header) | — | ||
| Balanced brackets / postfix eval / shunting-yard | Θ(n) | Θ(n) | Θ(n) | O(n) |
| Monotonic stack (next greater, histogram) | Θ(n) | Θ(n) | Θ(n) | O(n) |
Reasoning behind each entry
Array push/pop. Without a resize, a push or pop is one write and one counter update: Θ(1). A resize copies all n items, so the worst single operation is Θ(n) — that is a true worst case, which matters for latency-sensitive code. Averaged over any sequence of operations the cost is O(1) (Section G.3). This is why Python documents list.append as amortised O(1), noting that an individual operation may occasionally be O(n) when storage is resized. [6][2]
Linked-list push/pop. A constant number of pointer assignments and one allocation: Θ(1) in the worst case (assuming allocation is O(1)). [2]
Big-O, Ω and Θ here. Every stack operation must do at least a constant amount of work, so each is Ω(1); combined with the O(1) bounds they are Θ(1) (amortised for arrays). Stack-based scanning algorithms must read all n inputs (Ω(n)) and do O(n) work by the pushed-once argument, hence Θ(n).
Recurrence view of recursion. A recursive call stack of depth d uses Θ(d) space. For fact(n), T(n) = T(n−1) + Θ(1) gives Θ(n) time and Θ(n) stack space; naive fib(n) takes exponential time but its stack depth is only n, because at any moment only one root-to-leaf path of the recursion tree is on the stack (try Lab 5).
Time–space trade-offs
A doubling array may hold up to twice as many slots as items when growing (and up to four times after shrinks, with the quarter rule), but every slot is just a reference and the slots are contiguous, which is cache-friendly. A linked list uses exactly n nodes but each node carries a pointer plus allocator and object overhead, and nodes are scattered in memory. In practice array-backed stacks are usually faster; linked stacks win when you need a hard O(1) worst case per operation, or when many stacks share structure (persistent stacks, Section N). [1]
Theory versus actual Python behaviour
list:appendamortised O(1);pop()O(1);pop(0)andinsert(0, x)O(n) — so the top must be the end of the list. [6][4]collections.deque: appends and pops from either side with “approximately the same O(1) performance”; indexed access is O(1) at the ends but O(n) in the middle. [5]queue.LifoQueue: a LIFO queue with locking for multi-producer, multi-consumer threads. The locks make it much slower than a list for single-threaded use. [7]- Recursion: CPython limits interpreter stack depth (default 1000; read it with
sys.getrecursionlimit()) to prevent an overflow of the C stack from crashing Python. [8]
IPython implementation
Every code block in this section and in Sections M and P was run with CPython 3.11; the outputs shown are the real outputs.
I.1 Array-backed stack from scratch
Python’s list already resizes itself, so to see the mechanism we manage a fixed block of slots manually and never call append on it.
class ArrayStack:
"""LIFO stack on a manually resized array (doubling / quarter-full halving)."""
def __init__(self, capacity=1):
self._data = [None] * capacity # fixed block of slots
self._n = 0 # number of items; top is _data[_n - 1]
def __len__(self):
return self._n
def is_empty(self):
return self._n == 0
def _resize(self, capacity):
new = [None] * capacity # allocate a new block...
for i in range(self._n): # ...and copy the n live items: Θ(n)
new[i] = self._data[i]
self._data = new
def push(self, item):
if self._n == len(self._data): # full -> double
self._resize(2 * len(self._data))
self._data[self._n] = item
self._n += 1
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack") # underflow
self._n -= 1
item = self._data[self._n]
self._data[self._n] = None # avoid loitering: drop the reference
if 0 < self._n <= len(self._data) // 4: # quarter full -> halve
self._resize(len(self._data) // 2)
return item
def peek(self):
if self.is_empty():
raise IndexError("peek from empty stack")
return self._data[self._n - 1]
def capacity(self):
return len(self._data)
def __repr__(self):
return f"ArrayStack({self._data[:self._n]}, cap={len(self._data)})"
Line-by-line notes
self._data = [None] * capacity— a block of slots, standing in for a raw array;self._nis both the size and the index of the next free slot._resize— the only Θ(n) code path: allocate, copy the live prefix, swap the reference.push— grow before writing when full, then write slotnand increment.pop— check for underflow first, decrement, read, clear the slot, then maybe shrink. The0 < nguard keeps the capacity ≥ 1.- Errors use
IndexError, the same exceptionlist.pop()raises on an empty list, so the class is a drop-in replacement.
Sample run and dry-run table
s = ArrayStack()
for x in [10, 20, 30, 40, 50]:
s.push(x)
print(s) # ArrayStack([10, 20, 30, 40, 50], cap=8)
print([s.pop() for _ in range(4)], s) # [50, 40, 30, 20] ArrayStack([10], cap=2)
try:
ArrayStack().pop()
except IndexError as e:
print("underflow:", e) # underflow: pop from empty stack
| Operation | Resize? | Items copied | Live items (bottom → top) | n | capacity | Returns |
|---|---|---|---|---|---|---|
| push(10) | — | 0 | [10] | 1 | 1 | — |
| push(20) | grow 1 → 2 | 1 | [10, 20] | 2 | 2 | — |
| push(30) | grow 2 → 4 | 2 | [10, 20, 30] | 3 | 4 | — |
| push(40) | — | 0 | [10, 20, 30, 40] | 4 | 4 | — |
| push(50) | grow 4 → 8 | 4 | [10, 20, 30, 40, 50] | 5 | 8 | — |
| pop() | — | 0 | [10, 20, 30, 40] | 4 | 8 | 50 |
| pop() | — | 0 | [10, 20, 30] | 3 | 8 | 40 |
| pop() | shrink 8 → 4 (n = 2 ≤ 8/4) | 2 | [10, 20] | 2 | 4 | 30 |
| pop() | shrink 4 → 2 (n = 1 ≤ 4/4) | 1 | [10] | 1 | 2 | 20 |
I.2 Linked-list stack from scratch
class _Node:
__slots__ = ("value", "next") # no per-instance __dict__: smaller nodes
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedStack:
"""LIFO stack on a singly linked list; the head node is the top."""
def __init__(self):
self._head = None
self._n = 0
def __len__(self):
return self._n
def is_empty(self):
return self._head is None
def push(self, item):
self._head = _Node(item, self._head) # new node points at old top
self._n += 1
def pop(self):
if self._head is None:
raise IndexError("pop from empty stack")
node = self._head
self._head = node.next # unlink the old top
self._n -= 1
return node.value
def peek(self):
if self._head is None:
raise IndexError("peek from empty stack")
return self._head.value
def __iter__(self): # top -> bottom
node = self._head
while node:
yield node.value
node = node.next
def __repr__(self):
return "top -> " + " -> ".join(map(str, self)) + " -> None"
ls = LinkedStack()
for x in "ABC":
ls.push(x)
print(ls) # top -> C -> B -> A -> None
print(ls.pop(), ls.peek()) # C B
_Node(item, self._head) evaluates self._head before the assignment, so the new node captures the old top and the pointer update is safe in one line. __slots__ is a Python-specific memory optimisation; it removes the per-object attribute dictionary.
I.3 Built-in Python alternatives
from collections import deque
from queue import LifoQueue
st = [] # 1. list: the idiomatic stack
st.append(1); st.append(2)
assert st[-1] == 2 # peek (IndexError if empty)
assert st.pop() == 2 # pop (IndexError if empty)
assert st == [1] # emptiness test is simply `if not st:`
d = deque() # 2. deque: O(1) at both ends, no big resize copies
d.append(1); d.append(2)
assert d.pop() == 2
q = LifoQueue() # 3. thread-safe, blocking LIFO queue
q.put(1); q.put(2)
assert q.get() == 2
| Choice | push / pop / peek | Strengths | Use when |
|---|---|---|---|
list | append / pop() / [-1] | Fastest in practice, contiguous, idiomatic; documented as a stack in the Python tutorial. [4] | Default choice for single-threaded code. |
collections.deque | append / pop() / [-1] | O(1) at both ends; supports maxlen (bounded history). [5] | You also need the other end (e.g. a bounded undo history that drops the oldest entry). |
queue.LifoQueue | put / get / — | Internal locking; blocking with timeouts; optional maxsize. [7] | Producer/consumer threads sharing a LIFO work pool. |
| Custom class | your API | Explicit errors, invariants, instrumentation. | Teaching, or when you need a restricted interface. |
I.4 Balanced brackets
def is_balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch) # remember the unfinished opener
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False # nothing to close, or wrong type
return not stack # leftovers are unclosed openers
print([is_balanced(t) for t in ["{[()()]}", "([)]", "((", "", "())"]])
# [True, False, False, True, False]
| Char | Action | Stack after (bottom → top) |
|---|---|---|
{ | push | { |
[ | push | { [ |
( | push | { [ ( |
) | pop ( — matches | { [ |
( | push | { [ ( |
) | pop ( — matches | { [ |
] | pop [ — matches | { |
} | pop { — matches | (empty) → True |
Edge cases handled: a closer with an empty stack ("())"), a wrong closer ("([)]"), leftover openers ("((") and the empty string (balanced by definition). Θ(n) time, O(n) space.
I.5 Min-stack: O(1) minimum
Store, next to each item, the minimum of the stack up to and including that item. Popping then restores the previous minimum automatically. CP-Algorithms describes exactly this pair-storing technique. [16]
class MinStack:
def __init__(self):
self._s = [] # (value, minimum of stack up to here)
def push(self, x):
m = x if not self._s else min(x, self._s[-1][1])
self._s.append((x, m))
def pop(self):
return self._s.pop()[0]
def top(self):
return self._s[-1][0]
def get_min(self):
return self._s[-1][1]
ms = MinStack()
for x in [5, 3, 7, 3, 1]:
ms.push(x)
print(ms.get_min()); ms.pop(); print(ms.get_min()); ms.pop(); print(ms.get_min())
# 1 then 3 then 3 (the duplicate 3 is why we store per-item minima)
I.6 Expressions: shunting-yard and postfix evaluation
Postfix (reverse Polish) notation puts each operator after its operands — 3 4 2 * + means 3 + 4 × 2 — and needs no parentheses. It is evaluated with one operand stack: push numbers; on an operator pop two operands, apply, push the result. [1] Dijkstra’s shunting-yard algorithm converts infix to postfix with an operator stack, popping operators of higher (or equal, for left-associative operators) precedence before pushing a new one; it runs in O(n). [21][17]
import operator
OPS = {"+": operator.add, "-": operator.sub, "*": operator.mul,
"/": lambda a, b: int(a / b), "^": operator.pow} # / truncates toward 0
PREC = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
RIGHT_ASSOC = {"^"}
def tokenize(expr):
tokens, num = [], ""
for ch in expr:
if ch.isdigit():
num += ch
else:
if num:
tokens.append(num)
num = ""
if ch in PREC or ch in "()":
tokens.append(ch)
elif not ch.isspace():
raise ValueError(f"unexpected character {ch!r}")
if num:
tokens.append(num)
return tokens
def to_postfix(tokens):
out, ops = [], []
for t in tokens:
if t.isdigit():
out.append(t) # operands go straight out
elif t == "(":
ops.append(t)
elif t == ")":
while ops and ops[-1] != "(":
out.append(ops.pop())
if not ops:
raise ValueError("mismatched ')'")
ops.pop() # discard "("
else:
while (ops and ops[-1] != "(" and
(PREC[ops[-1]] > PREC[t] or
(PREC[ops[-1]] == PREC[t] and t not in RIGHT_ASSOC))):
out.append(ops.pop()) # stronger operators first
ops.append(t)
while ops:
if ops[-1] == "(":
raise ValueError("mismatched '('")
out.append(ops.pop())
return out
def eval_postfix(tokens):
st = []
for t in tokens:
if t in OPS:
if len(st) < 2:
raise ValueError("not enough operands")
b, a = st.pop(), st.pop() # order matters: a op b
st.append(OPS[t](a, b))
else:
st.append(int(t))
if len(st) != 1:
raise ValueError("too many operands")
return st[0]
for e in ["3+4*2", "(1+2)*(3+4)", "2^3^2", "8-3-2", "(5+3)*2-4/2"]:
p = to_postfix(tokenize(e))
print(e, "->", " ".join(p), "=", eval_postfix(p))
# 3+4*2 -> 3 4 2 * + = 11
# (1+2)*(3+4) -> 1 2 + 3 4 + * = 21
# 2^3^2 -> 2 3 2 ^ ^ = 512
# 8-3-2 -> 8 3 - 2 - = 3
# (5+3)*2-4/2 -> 5 3 + 2 * 4 2 / - = 14
Dry run: shunting-yard on (5+3)*2-4/2
| Token | Action | Operator stack | Output |
|---|---|---|---|
| ( | push | ( | |
| 5 | output | ( | 5 |
| + | top is “(”, push | ( + | 5 |
| 3 | output | ( + | 5 3 |
| ) | pop to “(” | 5 3 + | |
| * | push | * | 5 3 + |
| 2 | output | * | 5 3 + 2 |
| − | pop * (higher), push − | − | 5 3 + 2 * |
| 4 | output | − | 5 3 + 2 * 4 |
| / | − is lower, push | − / | 5 3 + 2 * 4 |
| 2 | output | − / | 5 3 + 2 * 4 2 |
| end | pop all | 5 3 + 2 * 4 2 / − |
Dry run: evaluating 5 3 + 2 * 4 2 / −
| Token | 5 | 3 | + | 2 | * | 4 | 2 | / | − |
|---|---|---|---|---|---|---|---|---|---|
| Stack after | 5 | 5 3 | 8 | 8 2 | 16 | 16 4 | 16 4 2 | 16 2 | 14 |
I.7 Monotonic stack: next greater element
Keep a stack of indices whose values are decreasing from bottom to top — elements still waiting for a larger value to their right. When a new value x arrives, every waiting element smaller than x has just found its answer: pop them all, then push x. This is the sequential stack algorithm for the all nearest smaller (or larger) values problem, which runs in linear time. [22]
def next_greater(nums):
ans = [-1] * len(nums)
st = [] # indices; values decreasing bottom->top
for i, x in enumerate(nums):
while st and nums[st[-1]] < x:
ans[st.pop()] = x # x is the first greater to the right
st.append(i)
return ans # leftovers keep -1
print(next_greater([4, 5, 2, 25, 7, 3, 8])) # [5, 25, 25, -1, 8, 8, -1]
| i | x | Popped (index→answer) | Stack after (indices) | Values on stack |
|---|---|---|---|---|
| 0 | 4 | — | [0] | 4 |
| 1 | 5 | 0→5 | [1] | 5 |
| 2 | 2 | — | [1, 2] | 5 2 |
| 3 | 25 | 2→25, 1→25 | [3] | 25 |
| 4 | 7 | — | [3, 4] | 25 7 |
| 5 | 3 | — | [3, 4, 5] | 25 7 3 |
| 6 | 8 | 5→8, 4→8 | [3, 6] | 25 8 |
Seven pushes and five pops in total — never more than one pop per element, so Θ(n) overall (Section G.4).
I.8 A queue from two stacks
class TwoStackQueue:
def __init__(self):
self._in, self._out = [], []
def enqueue(self, x):
self._in.append(x)
def dequeue(self):
if not self._out:
while self._in: # reverse 'in' into 'out'; each item moves once
self._out.append(self._in.pop())
if not self._out:
raise IndexError("dequeue from empty queue")
return self._out.pop()
q = TwoStackQueue()
for x in [1, 2, 3]:
q.enqueue(x)
print(q.dequeue()); q.enqueue(4)
print(q.dequeue(), q.dequeue(), q.dequeue()) # 1 then 2 3 4
Two reversals restore FIFO order. Each element is pushed onto _in once, moved once, and popped from _out once, so every operation is O(1) amortised although a single dequeue may be Θ(n). [16]
I.9 Replacing recursion with an explicit stack
Depth-first search is naturally recursive; replacing the call stack with your own stack removes the recursion-depth limit. Sedgewick and Wayne set exactly this as an exercise (a nonrecursive DFS “with an explicit stack instead of recursion”). [24]
def dfs_iterative(graph, start):
seen, order, st = set(), [], [start]
while st:
v = st.pop()
if v in seen:
continue # a vertex can be pushed more than once
seen.add(v)
order.append(v)
for w in reversed(graph[v]): # reversed: neighbours pop in list order
if w not in seen:
st.append(w)
return order
g = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": [], "E": []}
print(dfs_iterative(g, "A")) # ['A', 'B', 'D', 'C', 'E']
def factorial_explicit(n):
st, result = [], 1
while n > 1: # "call" phase: push pending multiplications
st.append(n)
n -= 1
while st: # "return" phase: pop and combine
result *= st.pop()
return result
print(factorial_explicit(5)) # 120
DFS with this “push all neighbours, skip if seen” style is O(V + E) time and O(E) stack space in the worst case (a vertex may sit on the stack several times).
I.10 Comparison of implementations
| Implementation | push | pop | Memory per item | Notes |
|---|---|---|---|---|
ArrayStack (I.1) | O(1) amortised, Θ(n) worst | O(1) amortised | 1 reference (+ unused capacity) | Shows resizing explicitly; slower than list because the loop runs in Python. |
LinkedStack (I.2) | Θ(1) worst | Θ(1) worst | a node object: value + next + header | No copies ever; more allocation and memory. |
list | O(1) amortised | O(1) | 1 reference (+ ~12% slack) | Resizing implemented in C; best default. [6][10] |
deque | O(1) | O(1) | about 1 reference | Both ends O(1); slow middle indexing. [5] |
LifoQueue | O(1) + lock | O(1) + lock | list inside | Thread-safe, blocking. [7] |
JReal-world applications
J.1 Operating systems and hardware: the call stack
Every thread of every process has a stack region in its address space holding the frames of active function calls; OSTEP lists code, heap and stack as the three main regions, with heap and stack placed at opposite ends so they can grow toward each other. [15] The processor supports it directly: on x86, push decrements the stack pointer and stores, pop loads and increments, and call pushes the return address. [14] Stack overflow — exceeding the fixed stack size, usually through runaway recursion — is a classic crash; the JVM reports it as StackOverflowError. [12][20]
- The heap grows from just after the code; the stack grows from the opposite end toward it (on x86, toward lower addresses).
- Each call pushes a frame (return address, parameters, locals); each return pops it. The stack pointer marks the top.
J.2 Language runtimes and virtual machines
Many virtual machines are stack machines: instructions take operands from, and push results onto, an operand stack instead of naming registers. CPython’s bytecode works this way (dis documents each instruction by its effect on STACK), the JVM gives each frame a LIFO operand stack, and WebAssembly instructions interact with an implicit stack of values, labels and activation frames. [9][12][13] Stack code is compact and easy to generate from a parse tree — it is postfix notation.
J.3 Compilers, parsers, editors and linters
Parsing nested syntax is a stack problem: expression parsers use operator and operand stacks to honour precedence and associativity in O(n), and Dijkstra designed shunting-yard for an ALGOL 60 compiler. [17][21] The same bracket-matching logic runs in code editors (highlighting the matching bracket), linters, JSON/XML/HTML validators (matching open and close tags), and template engines.
J.4 Search and backtracking
Depth-first search, maze solving, flood fill, topological sorting and backtracking solvers (Sudoku, N-queens, regex engines with backtracking) all explore the most recently discovered option first — a stack, explicit or via recursion. [24] Large-scale systems prefer the explicit stack so that input size cannot crash the process through recursion depth. [8]
J.5 Databases: nested savepoints
SQL savepoints nest like a stack. In PostgreSQL, ROLLBACK TO SAVEPOINT s “implicitly destroys all savepoints that were established after” s — rolling back to a point discards everything pushed after it. [25]
J.6 Web and backend applications: undo/redo and navigation
deque(maxlen=…) caps memory by silently dropping the oldest history. Backend request handling uses the same nesting idea — middleware layers and with-blocks are entered in one order and exited in the reverse order. The coding problem P.3 #3 builds this editor.KComparison with alternatives
| Structure | Removal order | Insert / remove | Random access | Choose it when… |
|---|---|---|---|---|
| Stack | LIFO — newest first | O(1) at the top | No (by design) | Work is nested; you must return to the most recent unfinished item; undo; DFS. |
| Queue | FIFO — oldest first | O(1) at the ends (rear in, front out) | No | Fairness/arrival order matters; BFS; job pipelines. [1] |
| Deque | Either end | O(1) at both ends [5] | O(1) at ends, O(n) middle | You need stack and queue behaviour together (sliding-window maximum, bounded history). |
| Priority queue (heap) | Smallest/largest key first | O(log n) | Only the min/max | Order depends on a priority, not on arrival time. |
| Dynamic array (plain list) | Any | O(1) amortised at end, O(n) elsewhere [6] | O(1) | You need indexing or iteration in the middle, not just the top. |
| Recursion (implicit stack) | LIFO | Call / return | No | Depth is small and bounded; code clarity matters more than depth limits. [8] |
- Stack: one opening — the item to leave is item 4, the newest.
- Queue: enter at the rear, leave at the front — item 1, the oldest, leaves first.
- Deque: both ends open for both operations; it can act as either.
Java’s cautionary tale
java.util.Stack extends Vector, so it inherits methods that break the LIFO discipline (such as inserting at an arbitrary index), and every method is synchronised. Its own documentation now says the Deque interface provides “a more complete and consistent set of LIFO stack operations” that should be used in preference. [11] The lesson carries over to Python: expose the restricted interface you mean, even if the storage underneath is more capable.
When to avoid a stack
- You need to look up or remove items other than the newest — use a list, dict or set.
- Items must be served in arrival order — use a queue (
collections.dequewithpopleft). [4] - Items must be served by priority — use
heapq. - Many threads share it and you need blocking — use
queue.LifoQueue, not a bare list. [7]
LCommon mistakes and misconceptions
L.1 Using the front of a list as the top
stack.insert(0, x) # push: shifts every element
top = stack.pop(0) # pop: shifts every elementstack.append(x) # push at the end
top = stack.pop() # pop from the endinsert(0, x) and pop(0) move all n elements. [5][6]
L.2 Popping or peeking without checking for empty
for ch in s:
if ch == "(":
st.append(ch)
else:
st.pop() # IndexError on empty
return len(st) == 0for ch in s:
if ch == "(":
st.append(ch)
elif not st:
return False # underflow = invalid input
else:
st.pop()
return not stL.3 Forgetting the final emptiness check
Returning True at the end of a bracket checker without testing not stack accepts "((". Every stack-validation algorithm has two failure points: during the scan and at the end.
L.4 Reversing operands in postfix evaluation
a, b = st.pop(), st.pop()
st.append(a - b)b, a = st.pop(), st.pop()
st.append(a - b) # 8 - 3 = 5Addition and multiplication hide this bug because they are commutative; subtraction, division and powers expose it. Also note Python’s // floors toward −∞, whereas many problems (e.g. LeetCode 150) require truncation toward zero: use int(a / b).
L.5 Peeking with stack[-1] on an empty list — or worse, stack[0]
stack[-1] on an empty list raises IndexError; that is good. stack[0] is the bottom, not the top — a silent logic error that passes tests with one-element stacks.
L.6 Complexity misconceptions
- “A while-loop inside a for-loop is O(n²).” Not for monotonic stacks: total pops ≤ total pushes = n (Section G.4).
- “append is always O(1).” It is O(1) amortised; a single append that triggers a resize is O(n). Fine for throughput, sometimes not for hard real-time latency. [6]
- “Recursion uses no memory.” Each active call holds a frame: depth d costs Θ(d) space. [20]
- “Shrink when half empty.” Causes thrashing; shrink at one-quarter (Section G.3). [1]
L.7 Boundary errors in monotonic stacks
Whether the pop condition is < or <= decides how equal values are treated. For “next strictly greater” pop while nums[top] < x; with <= an equal value would wrongly become the answer. In the histogram problem, forgetting the final sentinel bar of height 0 leaves bars on the stack that are never measured.
L.8 Terminology confusion
“The stack” (call-stack memory) versus “the heap” (dynamically allocated memory) are memory regions; they are unrelated to the heap data structure (priority queue). “Protocol stack” and “tech stack” mean layers, not a LIFO structure.
L.9 Interview mistakes
- Not saying out loud what the stack stores (values? indices? pairs?) and what invariant it keeps — interviewers grade the invariant.
- Storing values when the answer needs distances: store indices for “how many days until…” problems.
- Raising
sys.setrecursionlimitto “fix” deep recursion — the docs warn a too-high limit can crash Python. Convert to an explicit stack instead. [8] - Forgetting the empty-input and single-element cases in a dry run.
MInterview preparation
M.1 Recognising a stack problem
| Signal in the problem statement | Pattern | What the stack holds |
|---|---|---|
| Brackets, tags, nested structure, “valid”, “decode k[…]” | Matching / nesting | Unclosed openers or saved outer context |
| Expressions, calculators, RPN | Operand / operator stacks | Numbers, operators, saved (result, sign) |
| “Next greater/smaller”, “days until warmer”, “span”, “visible people” | Monotonic stack | Indices of unresolved elements |
| “Largest rectangle”, “trapping rain water”, “maximal rectangle” | Monotonic stack with widths | Indices with increasing heights |
| “Undo”, “backspace”, “simplify path”, “collisions”, “remove adjacent” | Simulation by cancellation | Surviving items so far |
| “Get min in O(1)”, “queue with stacks” | Design / augmentation | Pairs, or two stacks |
| DFS, backtracking, “iterative” version of recursion | Explicit call stack | Pending states |
M.2 Common interview questions (conceptual)
- What is the difference between a stack and a queue? Give one algorithm that needs each.
- How would you implement a stack with O(1) worst-case push? (Linked list; or a dynamic array with incremental copying — Section N.)
- Why is
list.appendamortised O(1)? What growth policy makes it so? - How do you implement a queue with two stacks, and what is the amortised cost?
- Explain what happens in memory when a recursive function recurses too deeply.
- Why is the monotonic-stack solution linear even though it has a nested loop?
M.3 Coding exercises
Easy
E1. Valid Parentheses Easy — LeetCode 20
Hint
Map each closer to its opener. Two places can fail: during the scan and at the end.Optimised solution
Identical to is_balanced in Section I.4. Θ(n) time, O(n) space.
E2. Implement Queue using Stacks Easy — LeetCode 232
Hint
Only move items from the in-stack to the out-stack when the out-stack is empty.Optimised solution
class MyQueue:
def __init__(self):
self.inp, self.out = [], []
def push(self, x):
self.inp.append(x)
def _move(self):
if not self.out:
while self.inp:
self.out.append(self.inp.pop())
def pop(self):
self._move()
return self.out.pop()
def peek(self):
self._move()
return self.out[-1]
def empty(self):
return not self.inp and not self.out
q = MyQueue(); q.push(1); q.push(2)
assert q.peek() == 1 and q.pop() == 1 and not q.empty()
O(1) amortised per operation, O(n) space. [16]
E3. Backspace String Compare Easy — LeetCode 844
Hint
Build each final string with a stack:# pops (if possible), anything else pushes.Optimised solution
def backspace_compare(s, t):
def build(x):
st = []
for ch in x:
if ch == "#":
if st:
st.pop()
else:
st.append(ch)
return st
return build(s) == build(t)
assert backspace_compare("ab#c", "ad#c") and not backspace_compare("a#c", "b")
Θ(n + m) time, O(n + m) space. (A two-pointer scan from the right achieves O(1) space.)
Medium
M1. Min Stack Medium — LeetCode 155
Hint
Store the running minimum alongside every element.Optimised solution
See MinStack in Section I.5. Every operation Θ(1); space Θ(n).
M2. Evaluate Reverse Polish Notation Medium — LeetCode 150
Hint
The first pop is the right operand. Division truncates toward zero.Optimised solution
def eval_rpn(tokens):
st = []
for t in tokens:
if t in {"+", "-", "*", "/"}:
b, a = st.pop(), st.pop()
if t == "+": st.append(a + b)
elif t == "-": st.append(a - b)
elif t == "*": st.append(a * b)
else: st.append(int(a / b)) # truncate toward zero
else:
st.append(int(t))
return st[0]
assert eval_rpn(["4", "13", "5", "/", "+"]) == 6
assert eval_rpn(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]) == 22
Θ(n) time, O(n) space.
M3. Daily Temperatures Medium — LeetCode 739
Hint
Next-greater with a monotonic stack — but store indices, because the answer is a distance.Optimised solution
def daily_temperatures(temps):
ans, st = [0] * len(temps), []
for i, t in enumerate(temps):
while st and temps[st[-1]] < t:
j = st.pop()
ans[j] = i - j
st.append(i)
return ans
assert daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
Θ(n) time (each index pushed and popped at most once), O(n) space.
M4. Asteroid Collision Medium — LeetCode 735
Hint
A collision happens only when the stack top moves right (> 0) and the incoming asteroid moves left (< 0). Keep popping while the incoming one wins.Optimised solution
def asteroid_collision(asteroids):
st = []
for a in asteroids:
alive = True
while alive and a < 0 and st and st[-1] > 0:
if st[-1] < -a:
st.pop() # top explodes, keep checking
elif st[-1] == -a:
st.pop(); alive = False # both explode
else:
alive = False # incoming explodes
if alive:
st.append(a)
return st
assert asteroid_collision([5, 10, -5]) == [5, 10]
assert asteroid_collision([10, 2, -5]) == [10]
assert asteroid_collision([-2, -1, 1, 2]) == [-2, -1, 1, 2]
Θ(n) time, O(n) space.
Hard
H1. Largest Rectangle in Histogram Hard — LeetCode 84
Hint 1
For each bar, the widest rectangle of exactly its height extends to the nearest shorter bar on each side.Hint 2
Keep indices of increasing heights. When a shorter bar arrives, the popped bar’s right limit is the current index and its left limit is the new stack top.Optimised solution
def largest_rectangle(heights):
st, best = [], 0 # indices of increasing heights
for i, h in enumerate(heights + [0]): # sentinel 0 flushes the stack
while st and heights[st[-1]] > h:
height = heights[st.pop()]
left = st[-1] + 1 if st else 0
best = max(best, height * (i - left))
st.append(i)
return best
assert largest_rectangle([2, 1, 5, 6, 2, 3]) == 10
Θ(n) time, O(n) space. (Note heights[st[-1]] never reads the sentinel because the sentinel index is pushed last and the loop ends.)
H2. Basic Calculator Hard — LeetCode 224
Hint
Only + and − and parentheses. On “(”, push the result so far and the sign in front of the parenthesis, then restart; on “)”, combine.Optimised solution
def calculate(s):
st, res, num, sign = [], 0, 0, 1
for ch in s:
if ch.isdigit():
num = num * 10 + int(ch)
elif ch in "+-":
res += sign * num
num, sign = 0, (1 if ch == "+" else -1)
elif ch == "(":
st.append((res, sign)) # save the outer context
res, sign = 0, 1
elif ch == ")":
res += sign * num
num = 0
prev_res, prev_sign = st.pop()
res = prev_res + prev_sign * res
return res + sign * num
assert calculate("(1+(4+5+2)-3)+(6+8)") == 23
assert calculate("-(2+3)") == -5
Θ(n) time, O(depth) space. Unary minus works because a leading “−” sets sign = −1 before a number or parenthesis.
More practice: 71 Simplify Path, 394 Decode String, 901 Online Stock Span, 42 Trapping Rain Water, 32 Longest Valid Parentheses, 85 Maximal Rectangle.
★Practice problems
Ask what the stack holds and when an item is popped. Many of these are monotonic-stack problems. There are 23 problems, grouped by level and topic: 5 easy, 15 medium and 3 hard. Each link opens the problem on the platform where you can submit and test your solution. Tick a problem when you have solved it, and use “My solution” to save your code, approach, complexity and notes to revise later.
Basic6 problems
Direct applications of this chapter’s core idea.
Stack
Last-in, first-out: matching, evaluation and monotonic stacks.
Intermediate13 problems
The pattern combined with one more idea, or applied to a less obvious setup.
Stack
Last-in, first-out: matching, evaluation and monotonic stacks.
Advanced4 problems
Harder variants that need the full toolkit and careful invariants.
Stack
Last-in, first-out: matching, evaluation and monotonic stacks.
NAdvanced concepts
N.1 Monotonic stacks in depth
A monotonic stack keeps its contents sorted (increasing or decreasing) by popping anything that would break the order before each push. Four variants cover most problems: next greater to the right (decreasing stack, scan left→right), next smaller to the right (increasing stack), and the same two “to the left” (read the stack top after popping, before pushing). The underlying problem is called all nearest smaller values; it is solved in linear time sequentially, and Berkman, Schieber and Vishkin showed how to solve it efficiently in parallel. [22]
- Bars 2 (index 2) and 5 (index 1) both wait on the stack until 25 arrives and pops them together.
- 7 and 3 wait under 25 until 8 arrives; 8 pops 3 and 7 but not 25.
- 25 and 8 never find a greater value to their right: answer −1.
N.2 Queues and deques from stacks; min-queue
The two-stack queue (Section I.8) combined with the min-stack (I.5) gives a queue that reports its minimum in O(1) amortised: keep a min-stack for input and one for output, and the answer is the smaller of their two minima. This is the basis of the sliding-window minimum in CP-Algorithms. [16]
N.3 Worst-case O(1) array stacks
Amortised bounds allow an occasional Θ(n) push. Real-time systems can avoid it by incremental copying: when the array becomes half full, allocate the bigger array and copy two old items on every subsequent push, so the copy finishes before the old array fills. Each push then does O(1) work in the worst case, at the cost of keeping two arrays during the transition. (A standard de-amortisation technique; we present it as a design sketch.)
N.4 Persistent (immutable) stacks
Because a linked stack’s push never modifies existing nodes, an old head still describes the old stack after a push. Many versions can share their common tail: pushing 4 onto 3→2→1 and pushing 9 onto the same 3→2→1 gives two stacks that share three nodes. Functional languages implement their basic list type this way (a “cons list”), and undo histories can keep every version in O(1) extra space per operation.
N.5 Two stacks in one array, and stack machines
Two stacks can share one fixed array by growing toward each other from opposite ends — exactly the arrangement of heap and stack in a process address space (Figure J.1) — and overflow happens only when the total size exceeds the array. [15] Going further, an entire computer can be organised around a stack: the JVM and WebAssembly define their semantics this way, and compilers translate expression trees into stack code by a postorder traversal. [12][13]
N.6 Stacks and formal languages
A finite automaton plus one unbounded stack is a pushdown automaton, the machine model for context-free languages such as balanced brackets and programming-language grammars — the formal reason why nesting needs a stack, and why a regular expression without extensions cannot check balanced parentheses of arbitrary depth. Bauer and Samelson’s term Kellerautomat (“cellar automaton”) is a historical name for this machine. [19]
ONotebook-ready summary
First, the whole idea on one page — copy this sheet into your notebook. The detailed revision notes follow it.
A collection where you only touch the top. The last item pushed is the first popped: LIFO — Last In, First Out.
pop() → remove & return top
peek() → look at top
Empty pop / peek = underflow → raise an error.
st.append(x) # push
st.pop() # pop
st[-1] # peek
if not st: # empty?
unfinished thing
nesting closes in reverse order of opening
push 3, push 7, push 5, pop, push 9:
pop() returned 5 — the last one in.
open → push · close → pop & must match · end → stack empty
Each item is pushed once and popped at most once ⇒ stack scans are O(n).
| push / pop (list) | O(1)* |
| peek / empty | O(1) |
| search | O(n) |
| space | O(n) |
* amortised (resize = O(n) once in a while)
- O(1) operations.
- Natural for nesting, undo and recursion.
- Simple: a Python list is enough.
- 🧩Valid brackets / tags.
- 🧮Expression evaluation (RPN).
- 📈Next greater (monotonic).
- ↩️Undo / redo, DFS, call stack.
- Never
pop(0)— O(n). - Check empty before pop.
- RPN: first pop = right operand.
- Deep recursion → explicit stack.
Detailed revision notes
1 · Definition
- ADT, sequence with one open end (top). LIFO.
- Axioms:
top(push(S,x)) = x,pop(push(S,x)) = S. - Underflow = pop/peek empty. Overflow = push on full fixed-size stack.
2 · Picture to draw
3 · Implementations
- Array:
data[0..n−1], top =data[n−1]; double when full, halve at ¼. - Linked list: head = top; push =
head = Node(x, head).
4 · Complexity
| Op | Array | Linked |
|---|---|---|
| push | O(1) amortised, O(n) worst | Θ(1) |
| pop | O(1) amortised | Θ(1) |
| peek / size | Θ(1) | Θ(1) |
| n pushes total | < 3n writes | n allocations |
5 · Python syntax
list:append,pop(),[-1](default)deque: same + O(1) left end,maxlenLifoQueue:put/get, thread-safe- recursion limit:
sys.getrecursionlimit()= 1000
6 · Patterns
- Brackets: push open, pop+match on close, empty at end.
- RPN: num → push; op →
b=pop(); a=pop(); push(a op b). - Shunting-yard: pop ops with higher (or equal & left-assoc) precedence first.
- Monotonic:
while st and nums[st[-1]] < x: ans[st.pop()] = x. - Min-stack: store
(x, min_so_far). Queue = 2 stacks.
7 · Applications
- Call stack (frames), CPython / JVM / Wasm stack machines
- Parsers, editors, validators · DFS / backtracking · undo · SQL savepoints
8 · Interview takeaways
- Say what the stack stores and its invariant.
- Indices, not values, when the answer is a distance.
- Nested loop is still O(n): pushed once, popped once.
PKnowledge assessment
Attempt everything before opening the answer key at the end of this section.
P.1 Conceptual questions
- Why must an array-backed stack keep its top at the end of the array rather than at index 0?
- A stack doubles when full. Why is shrinking at one-half full a bad idea, and what rule fixes it?
- Give one situation where a linked-list stack is preferable to an array-backed one, and one where the opposite holds.
- The monotonic-stack algorithm has a
whileloop inside aforloop. Prove it runs in O(n). - You push 1, 2, 3 in that order and may pop at any time, writing down each popped value. Which of these outputs are possible:
1 3 2,3 1 2,2 3 1? Justify.
P.2 Dry-run exercises
- Starting from an empty
ArrayStack()(capacity 1), apply: push a, push b, push c, pop, pop, push d. Given, capacity and contents after each step. - Evaluate the postfix expression
2 3 4 * + 5 −, showing the stack after every token. - Compute the stock span (number of consecutive days up to and including today with price ≤ today’s) for prices
[100, 80, 60, 70, 60, 75, 85]using a stack of(price, span)pairs. Show the stack after each day.
P.3 Coding problems
- Remove adjacent duplicates. Repeatedly remove pairs of equal adjacent letters:
"abbaca" → "ca"(cf. LeetCode 1047). O(n). - Decode string.
"3[a2[c]]" → "accaccacc"(cf. LeetCode 394). - Undo/redo editor. Implement
type(s),undo()andredo()on a text buffer; a newtypeafter an undo must discard the redo history.
P.4 Practical engineering scenario
Your team runs an HTTP API that accepts user-uploaded JSON documents and validates them before storing them. A security review finds that a document consisting of 200,000 nested [ characters crashes a worker process, because the validator is a recursive-descent parser. Propose a fix. Explain why the crash happens, how you would restructure the validator, what limits you would impose, and what the time and memory costs of your design are.
P.5 Answer key
Conceptual answers
- Adding or removing at the end of an array touches one slot; at index 0 every other element must shift, costing Θ(n) per operation. Python documents
pop(0)/insert(0, x)as O(n) for this reason. [5] - At exactly half full, push → grow (copy n), pop → shrink (copy n), push → grow… every operation becomes Θ(n). Halving only at one-quarter full leaves the new array half full, so Ω(capacity) operations separate any two resizes and the amortised cost stays O(1). [1][2]
- Linked: hard real-time code that cannot tolerate a Θ(n) resize pause, or persistent stacks sharing structure. Array: almost everything else — better cache locality and less memory per item, which is why Python’s
listis the default stack. - Each index is pushed exactly once (one push per iteration of the
for) and every iteration of thewhilepops one index. An index cannot be popped more often than it was pushed, so totalwhileiterations ≤ n. Total work = O(n) pushes + O(n) pops + O(n) failed tests = O(n). 1 3 2: push 1, pop 1, push 2, push 3, pop 3, pop 2 ✓.2 3 1: push 1, push 2, pop 2, push 3, pop 3, pop 1 ✓.3 1 2✗: to output 3 first, 1 and 2 must both be on the stack with 2 above 1, so 2 must come out before 1. In general a stack cannot produce the pattern “high, low, middle” (231-style patterns in the related sorting problem); the reachable count is the Catalan number C3 = 5 of the 6 orders. [23]
Dry-run answers (verified by running code)
-
Step n capacity Contents Note push a 1 1 [a] push b 2 2 [a, b] grow 1→2, copy 1 push c 3 4 [a, b, c] grow 2→4, copy 2 pop → c 2 4 [a, b] 2 ≤ 4/4? no pop → b 1 2 [a] 1 ≤ 4/4 → shrink 4→2 push d 2 2 [a, d] room available, no resize - 2 → [2]; 3 → [2, 3]; 4 → [2, 3, 4]; * → [2, 12]; + → [14]; 5 → [14, 5]; − → [9]. Result 9.
-
Spans:
Day Price Popped Span Stack after (price, span) 0 100 — 1 (100,1) 1 80 — 1 (100,1) (80,1) 2 60 — 1 (100,1) (80,1) (60,1) 3 70 (60,1) 2 (100,1) (80,1) (70,2) 4 60 — 1 (100,1) (80,1) (70,2) (60,1) 5 75 (60,1) (70,2) 4 (100,1) (80,1) (75,4) 6 85 (75,4) (80,1) 6 (100,1) (85,6) [1, 1, 1, 2, 1, 4, 6].
Coding answers
# 1. Remove adjacent duplicates
def remove_adjacent_duplicates(s):
st = []
for ch in s:
if st and st[-1] == ch:
st.pop() # the pair cancels
else:
st.append(ch)
return "".join(st)
# 2. Decode string
def decode_string(s):
st, cur, k = [], "", 0
for ch in s:
if ch.isdigit():
k = k * 10 + int(ch)
elif ch == "[":
st.append((cur, k)); cur, k = "", 0 # save outer context
elif ch == "]":
prev, times = st.pop()
cur = prev + cur * times
else:
cur += ch
return cur
# 3. Undo / redo editor
class UndoRedo:
def __init__(self):
self.text, self.undo_st, self.redo_st = "", [], []
def type(self, s):
self.undo_st.append(self.text)
self.text += s
self.redo_st.clear() # new edit invalidates redo history
def undo(self):
if self.undo_st:
self.redo_st.append(self.text)
self.text = self.undo_st.pop()
def redo(self):
if self.redo_st:
self.undo_st.append(self.text)
self.text = self.redo_st.pop()
assert remove_adjacent_duplicates("abbaca") == "ca"
assert decode_string("3[a2[c]]") == "accaccacc"
ed = UndoRedo(); ed.type("a"); ed.type("b"); ed.undo(); ed.type("c"); ed.undo(); ed.redo()
assert ed.text == "ac"
Complexities: (1) Θ(n) time and space; (2) time proportional to the output length, stack O(nesting depth); (3) each operation O(1) stack work, but storing whole snapshots costs O(length of text) per edit — store reversible commands (inserted text + position) instead for large documents.
Engineering scenario — model answer
Why it crashes. Each [ makes the recursive parser call itself, pushing one frame on the call stack. 200,000 levels exceed Python’s recursion limit (default 1000, giving RecursionError) or, if someone raised the limit, overflow the C stack and kill the process — the Python docs warn that a too-high limit can crash the interpreter. [8][20] Either way an attacker controls the depth: a denial-of-service vector.
Fix. Rewrite the validator as an iterative parser with an explicit stack of open containers ([ or { plus parser state such as “expecting key”). Open → push, close → pop and check the type matches, end → stack empty — the bracket algorithm of Section I.4 generalised. The explicit stack lives on the heap, so depth no longer threatens the process.
Limits. Still cap nesting depth (for example 512 levels) and total document size, and reject early with HTTP 400/413; legitimate documents are rarely deeply nested, and the cap bounds memory per request. Stream the input so validation memory is O(depth) rather than O(size).
Costs. One pass over the input: Θ(n) time; stack memory O(d) with d ≤ the depth cap; each push/pop O(1) amortised with a Python list.
QReferences and further reading
- R. Sedgewick, K. Wayne, “Bags, Queues, and Stacks,” §1.3 of Algorithms, 4th ed., Princeton University (book site). LIFO definition, linked-list stack (push/pop at the head), ResizingArrayStack doubling when full and halving at one-quarter full, Dijkstra’s two-stack expression evaluation (Sections B, D, F, G, H, K, L).
- T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022 — Ch. 10 (stacks and queues) and the chapter on amortised analysis (MULTIPOP stack, dynamic tables). Stack definition, O(1) operations, underflow/overflow, aggregate/accounting/potential methods, table expansion and contraction (Sections B, F, G, H).
- E. Demaine et al., MIT OpenCourseWare 6.006 Introduction to Algorithms (Spring 2020), Lecture 2: Data Structures and Dynamic Arrays. Dynamic arrays and their amortised analysis (Section G).
- Python Software Foundation, The Python Tutorial, §5.1.1 “Using Lists as Stacks” and §5.1.2 “Using Lists as Queues”. append/pop as a LIFO stack; front inserts/pops are slow (Sections B, F, H, I, K).
- Python Software Foundation, collections.deque. Thread-safe O(1) appends/pops at both ends; list pop(0)/insert(0, v) cost O(n); O(n) middle indexing (Sections H, I, K, L, P).
- Python Software Foundation, “Time complexity of operations on built-in types”, Python 3 documentation. list append O(1) amortised, pop(k) O(n−k), resizing note (Sections F, H, I, K, L).
- Python Software Foundation, queue — A synchronized queue class (LifoQueue). LIFO queue with locking for multi-producer/multi-consumer use (Sections F, H, I, K).
- Python Software Foundation, sys.getrecursionlimit / sys.setrecursionlimit. Interpreter stack depth limit preventing C-stack overflow; warning that a too-high limit can crash (Sections C, F, H, J, L, P).
- Python Software Foundation, dis — Disassembler for Python bytecode. CPython bytecode described in terms of the interpreter stack STACK, top = STACK[-1] (Sections F, J).
- CPython developers, Objects/listobject.c (list_resize), GitHub. List over-allocation and its growth pattern 0, 4, 8, 16, 24, 32, 40, 52, 64, 76, … (Sections F, I).
- Oracle, java.util.Stack (Java SE 21 API). Stack extends Vector; Deque recommended for LIFO operations (Section K).
- Oracle, The Java Virtual Machine Specification, SE 21, Ch. 2 (§2.5.2 JVM stacks, §2.6.2 operand stacks). Per-frame LIFO operand stack; StackOverflowError (Sections F, J, N).
- WebAssembly Community Group, WebAssembly Core Specification — Runtime Structure. Instructions operate on an implicit stack of values, labels and activations (Sections F, J, N).
- D. Evans, “Guide to x86 Assembly,” CS216, University of Virginia. Hardware stack grows down; push/pop semantics; call pushes the return address (Sections B, F, J).
- R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, “The Abstraction: Address Spaces,” Operating Systems: Three Easy Pieces, University of Wisconsin–Madison. Stack region tracks the call chain, locals, parameters and return values; heap and stack at opposite ends growing toward each other (Sections B, F, J, N).
- CP-Algorithms, “Minimum Stack / Minimum Queue”. Min-stack via (value, min) pairs; queue from two stacks in O(1) on average; minimum queue (Sections I, M, N).
- CP-Algorithms, “Expression parsing”. Two-stack O(n) expression evaluation with precedence, unary operators and right-associativity (Sections B, C, I, J).
- E. W. Dijkstra, “Algol 60 translation,” Mathematisch Centrum report MR 35, 1961 (scan, E. W. Dijkstra Archive, University of Texas at Austin; identification via [21]). Original description of the shunting-yard algorithm (Sections B, J).
- Wikipedia contributors, “Stack (abstract data type)” (secondary overview; history cross-checked with its cited sources). Turing’s bury/unbury, Samelson–Bauer 1957 patent, Bauer’s 1988 Computer Pioneer Award, push/pop/peek terminology, underflow/overflow (Sections B, F, G, N).
- Wikipedia contributors, “Call stack” (secondary). Stack frames hold return addresses, parameters and locals; stack overflow (Sections B, F, J, L, P).
- Wikipedia contributors, “Shunting yard algorithm” (secondary). Invented by Dijkstra, published November 1961; produces postfix; O(n) (Sections B, I, J).
- Wikipedia contributors, “All nearest smaller values” (secondary; cites Berkman, Schieber & Vishkin 1993). Linear-time stack algorithm behind monotonic stacks; parallel algorithms (Sections I, N).
- Wikipedia contributors, “Stack-sortable permutation” (secondary; cites Knuth 1968). Catalan-number counts, 231-avoidance (Sections G, P).
- R. Sedgewick, K. Wayne, “Undirected Graphs,” §4.1 of Algorithms, 4th ed., Princeton University. Depth-first search; nonrecursive DFS with an explicit stack (Sections C, I, J).
- PostgreSQL Global Development Group, ROLLBACK TO SAVEPOINT, PostgreSQL documentation. Rolling back to a savepoint destroys all later savepoints (Section J).
Practice problem sources
LeetCode problems 20, 32, 42, 71, 84, 85, 150, 155, 224, 232, 394, 735, 739, 844, 901 and 1047 are linked at their point of use in Sections M and P. Problem statements are owned by their respective sites.