Data StructureData StructureA way of organising data in memory so that certain operations, like lookup, insert or remove, are fast.e.g. Arrays, hash tables, stacks, trees
DSA Learning Studio · Chapter 07 · Linear Data Structures

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.

Difficulty: Beginner → Intermediate (advanced section: Upper-intermediate) Reading time: ~80 minutes (+ 30 min exercises) Language: Python 3.8+ 6 interactive labs

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:

  1. Define a stack as an abstract data type, state the LIFO rule, and name its operations and error conditions (underflow, overflow).
  2. 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 push and pop.
  3. Prove that a doubling array gives amortised O(1) push, and explain why it must shrink at one-quarter (not one-half) full.
  4. Explain how the call stack makes function calls and recursion work, and why deep recursion overflows.
  5. Solve the classic stack problems: balanced brackets, postfix evaluation, infix-to-postfix conversion (shunting-yard), min-stack, and queue-from-two-stacks.
  6. Recognise the monotonic stack pattern (“next greater element”, “largest rectangle”) and argue its O(n) running time.
  7. Choose correctly between list, collections.deque and queue.LifoQueue in Python.
The one-sentence promise A stack lets you add and remove items at one end only — the top — and in exchange both operations cost O(1), and the item you get back is always the one you most recently saved. That “most recent first” order is exactly what nesting, undoing and returning from function calls need. [1][2]
How the visuals in this chapter are made This environment has no image-generation model, so every “whiteboard” illustration is drawn in code: a small sketch renderer produces hand-drawn-style strokes and handwriting labels as SVG from the actual data of each example. That keeps every index, value and pointer exactly correct while still looking like marker on a whiteboard. All six interactive labs are fully working.

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]

Formal definition A stack is an abstract data type (ADT) holding a finite sequence S = ⟨s1, s2, …, sk⟩, where sk is the top, with the operations
• 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]
Simple English definition A stack is a pile where you only ever touch the top. Put things on the top (push), take things off the top (pop), or look at the top (peek). Whatever went in last comes out first.

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

  1. 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]
  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.
  3. 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:

ComponentSpecification
InputA string s of length n over the characters ( ) [ ] { } (and possibly others to ignore).
OutputTrue 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 constraintsLeetCode 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]

Real-world analogy: the stack of trays and the pile of open tabs Imagine reading a document that links to a definition, which links to an example, which links to a footnote. You keep each page open as you go deeper. When you finish the footnote you close it and land back on the example, then the definition, then the document — the reverse of the order you opened them. Your mental “where was I?” list is a stack: open = push, finish = pop, and the page you return to is always the top. (Illustrative analogy.)

DVisual whiteboard explanations

All diagrams in this chapter use one colour language. Learn it once and every picture reads the same way:

Blue — stored data, array slots, memory blocks Green — push / successful operation / result Red — pop / removal / error (underflow, mismatch) Yellow/orange — the top pointer / current element Purple — links, next-pointers, call frames, copies Black — labels and definitions
Figure D.1 · Concept introductionOnly the top is reachable
stored itemtop itempush enters at the toppop leaves from the top
  1. Three items were pushed in the order 3, 7, 5. The first one pushed (3) sits at the bottom.
  2. Left: push(9) enters through the only opening and lands on 5, becoming the new top.
  3. 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.
Technical interpretation: the container has exactly one opening. No operation can reach 7 or 3 without first popping everything above them — that restriction is what makes the order LIFO and every operation O(1). [1]
Figure D.2 · Memory representationTwo ways to store the same stack
occupied slot / node valuetopfree slot (capacity not yet used)next pointerwhere the next push writes
  1. Array-backed: items live in contiguous slots 0…n−1 with the bottom at index 0. The size n = 4 doubles as the index of the next free slot, so the top is data[n−1] and a push writes data[n].
  2. The array has capacity 8 but only 4 slots are in use; the spare room makes most pushes a single write.
  3. 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.
Technical interpretation: both layouts give O(1) push/pop. The array wins on memory locality and per-item overhead; the linked list never needs to copy, so every single operation is O(1) in the worst case, not just on average. [1][2]
Figure D.3 · Step-by-step executionpush 3, push 7, push 5, pop, push 9
just pushedjust popped (returned)unchangedtop pointer
  1. Start empty: top = −1 (array view) or head = None (list view).
  2. Each push places the new item above the old top; the top pointer moves up by one.
  3. pop() returns 5 — the last item pushed — and the top drops back to 7.
  4. push(9) reuses the slot that 5 vacated.
Technical interpretation: after any sequence of operations the stack content equals the pushes that have not yet been “cancelled” by a later pop — like matched parentheses, where each pop matches the nearest unmatched push to its left.
Figure D.4 · Before-and-after comparisonPointer changes in a linked-list push and pop
existing nodenew nodenext pointerhead (= top)unlinked node
  1. push(9): ① create node 9; ② set node.next = head (purple); ③ set head = node (yellow). Order matters — doing ③ first would lose the rest of the list.
  2. pop(): remember node = head, set head = head.next, return node.value. The old node is no longer referenced and is reclaimed by the garbage collector.
Technical interpretation: each operation changes a constant number of pointers, independent of the list length — Θ(1) in the worst case. [1][2]

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.

Lab 1 · Stack playgroundPush, pop and peek — watch three views of the same stack
The stack (ADT view)
Array-backed: data[0 … capacity−1]
Linked list: head = top
Lab 2 · Balanced bracketsStep through the stack-based checker
Input (current character in yellow)
Stack of open brackets
Lab 3 · ExpressionsInfix → postfix (shunting-yard), then evaluate the postfix
Integers, + − * / ^ and parentheses. / truncates toward zero; ^ is right-associative.
Tokens
Operator stack
Postfix output
Lab 4 · Monotonic stackNext greater element in one pass
Stack (indices, bottom → top):
Lab 5 · The call stackWatch frames being pushed and popped by recursion
Call stack (top = running)
Event log

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)

  1. push(x): if n == capacity, allocate a new array of twice the capacity and copy the n items (the only expensive step); write data[n] = x; increment n.
  2. pop(): if n == 0, raise an underflow error; decrement n; read x = data[n]; clear the slot (data[n] = None) so the stack does not keep a dead object alive; if n has fallen to a quarter of the capacity, shrink to half; return x.
  3. peek(): if n == 0, raise; return data[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).

Figure F.1 · Internal workingGrowing a full array: allocate, copy, write
live itemscopy during resizethe new pushold block (freed)free slots
  1. The array has capacity 4 and holds 4 items, so push(2) finds no room.
  2. A new block of capacity 8 is allocated and the 4 items are copied across (4 purple arrows = 4 units of extra work).
  3. 2 is written into slot 4; the old block is released.
  4. The next three pushes (slots 5–7) cost one write each — the copying is “paid back” over them.
Technical interpretation: a resize costs Θ(n), but it happens only when n reaches a power of two, so n pushes cost fewer than 3n writes in total — amortised O(1) per push (proved in Section G). [2][1]

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)

  1. push(x): head = Node(x, head) — the new node’s next is the old head, then the head moves to the new node.
  2. pop(): if head is None, raise; node = head; head = node.next; return node.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]

Figure F.2 · Step-by-step executionThe call stack while computing fact(3)
suspended frame (waiting)running frame (top)frame returning a valuebase case
  1. main calls fact(3): a frame with n = 3 is pushed. It cannot finish until fact(2) returns, so it waits.
  2. fact(2) and fact(1) are pushed in turn. fact(1) is the base case and returns 1 immediately.
  3. Frames pop in reverse order: fact(2) computes 2 × 1 = 2, then fact(3) computes 3 × 2 = 6, and control returns to main.
Technical interpretation: recursion depth d means d frames live at once — O(d) memory even if the function itself allocates nothing. Python caps the depth (default 1000) and raises 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

SituationCorrect 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 valueDo not use None both as data and as the “empty” signal; test emptiness with len() or is_empty().
ShrinkingShrink 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 orderIterating a Python list used as a stack goes bottom → top; iterate reversed(stack) for pop order.
ConcurrencySeparate peek-then-pop calls are not atomic across threads; use queue.LifoQueue (internally locked) or your own lock. [7]
Very deep recursionConvert 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

Representation invariant0 ≤ n ≤ capacity; the stack’s contents bottom→top are exactly data[0], …, data[n−1]; and every slot data[i] with i ≥ n holds 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:

T(n) = n + Σj=0⌊log₂(n−1)⌋ 2j  <  n + 2n = 3n   ⟹   T(n)/n < 3 = O(1) amortised

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]

Why shrink at a quarter, not a half?If the array halved as soon as it became half full, then at n = capacity/2 the sequence push, pop, push, pop, … would grow and shrink on every operation, each costing Θ(n) — Θ(n) per operation forever. Halving only at one-quarter leaves the new array half full, so at least capacity/4 operations must happen before the next resize, and the amortised cost stays O(1). This is exactly the policy of 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]

OperationBest caseAverage caseWorst caseAuxiliary 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 itemsarray: 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).

Lab 6 · Time-complexity visualisationThe cost of every push: doubling vs growing by a constant
Each bar is one push. Blue = the write itself (1 unit); red = items copied during a resize. The dashed green line is the running average cost per push.

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: append amortised O(1); pop() O(1); pop(0) and insert(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._n is 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 slot n and increment.
  • pop — check for underflow first, decrement, read, clear the slot, then maybe shrink. The 0 < n guard keeps the capacity ≥ 1.
  • Errors use IndexError, the same exception list.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
OperationResize?Items copiedLive items (bottom → top)ncapacityReturns
push(10)—0[10]11—
push(20)grow 1 → 21[10, 20]22—
push(30)grow 2 → 42[10, 20, 30]34—
push(40)—0[10, 20, 30, 40]44—
push(50)grow 4 → 84[10, 20, 30, 40, 50]58—
pop()—0[10, 20, 30, 40]4850
pop()—0[10, 20, 30]3840
pop()shrink 8 → 4 (n = 2 ≤ 8/4)2[10, 20]2430
pop()shrink 4 → 2 (n = 1 ≤ 4/4)1[10]1220

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
Choicepush / pop / peekStrengthsUse when
listappend / pop() / [-1]Fastest in practice, contiguous, idiomatic; documented as a stack in the Python tutorial. [4]Default choice for single-threaded code.
collections.dequeappend / 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.LifoQueueput / get / —Internal locking; blocking with timeouts; optional maxsize. [7]Producer/consumer threads sharing a LIFO work pool.
Custom classyour APIExplicit 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]
CharActionStack 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

TokenActionOperator stackOutput
(push(
5output(5
+top is “(”, push( +5
3output( +5 3
)pop to “(”5 3 +
*push*5 3 +
2output*5 3 + 2
−pop * (higher), push −−5 3 + 2 *
4output−5 3 + 2 * 4
/− is lower, push− /5 3 + 2 * 4
2output− /5 3 + 2 * 4 2
endpop all5 3 + 2 * 4 2 / −

Dry run: evaluating 5 3 + 2 * 4 2 / −

Token53+2*42/−
Stack after55 388 21616 416 4 216 214

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]
ixPopped (index→answer)Stack after (indices)Values on stack
04—[0]4
150→5[1]5
22—[1, 2]5 2
3252→25, 1→25[3]25
47—[3, 4]25 7
53—[3, 4, 5]25 7 3
685→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

ImplementationpushpopMemory per itemNotes
ArrayStack (I.1)O(1) amortised, Θ(n) worstO(1) amortised1 reference (+ unused capacity)Shows resizing explicitly; slower than list because the loop runs in Python.
LinkedStack (I.2)Θ(1) worstΘ(1) worsta node object: value + next + headerNo copies ever; more allocation and memory.
listO(1) amortisedO(1)1 reference (+ ~12% slack)Resizing implemented in C; best default. [6][10]
dequeO(1)O(1)about 1 referenceBoth ends O(1); slow middle indexing. [5]
LifoQueueO(1) + lockO(1) + locklist insideThread-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]

Figure J.1 · Real-world applicationWhere the call stack lives in a process
code / static dataheap (malloc / new)stack framesstack pointer (top)overflow if they meet
  1. The heap grows from just after the code; the stack grows from the opposite end toward it (on x86, toward lower addresses).
  2. Each call pushes a frame (return address, parameters, locals); each return pops it. The stack pointer marks the top.
Technical interpretation: allocation on the stack is just moving one pointer, which is why local variables are so cheap — and why their lifetime ends when the function returns. Exact layouts vary by OS and architecture; the figure follows OSTEP’s simplified model. [15][14]

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

Engineering illustration (our example)A text editor or design tool keeps two stacks of states (or of reversible commands). Every edit pushes onto the undo stack and clears the redo stack; undo pops from undo and pushes onto redo; redo does the reverse. A bounded 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

StructureRemoval orderInsert / removeRandom accessChoose it when…
StackLIFO — newest firstO(1) at the topNo (by design)Work is nested; you must return to the most recent unfinished item; undo; DFS.
QueueFIFO — oldest firstO(1) at the ends (rear in, front out)NoFairness/arrival order matters; BFS; job pipelines. [1]
DequeEither endO(1) at both ends [5]O(1) at ends, O(n) middleYou need stack and queue behaviour together (sliding-window maximum, bounded history).
Priority queue (heap)Smallest/largest key firstO(log n)Only the min/maxOrder depends on a priority, not on arrival time.
Dynamic array (plain list)AnyO(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)LIFOCall / returnNoDepth is small and bounded; code clarity matters more than depth limits. [8]
Figure K.1 · Comparison with alternative approachesStack vs queue vs deque
insertremovestored items (numbers = arrival order)
  1. Stack: one opening — the item to leave is item 4, the newest.
  2. Queue: enter at the rear, leave at the front — item 1, the oldest, leaves first.
  3. Deque: both ends open for both operations; it can act as either.
Technical interpretation: the structures differ only in which end removals come from. That single choice decides whether a graph search is depth-first (stack) or breadth-first (queue).

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.deque with popleft). [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

✘ Incorrect (O(n) per operation)
stack.insert(0, x)   # push: shifts every element
top = stack.pop(0)   # pop:  shifts every element
✔ Correct (O(1) amortised)
stack.append(x)      # push at the end
top = stack.pop()    # pop from the end

insert(0, x) and pop(0) move all n elements. [5][6]

L.2 Popping or peeking without checking for empty

✘ Crashes on ")("
for ch in s:
    if ch == "(":
        st.append(ch)
    else:
        st.pop()           # IndexError on empty
return len(st) == 0
✔ Guarded
for ch in s:
    if ch == "(":
        st.append(ch)
    elif not st:
        return False       # underflow = invalid input
    else:
        st.pop()
return not st

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

✘ “8 3 −” gives −5
a, b = st.pop(), st.pop()
st.append(a - b)
✔ The first pop is the RIGHT operand
b, a = st.pop(), st.pop()
st.append(a - b)   # 8 - 3 = 5

Addition 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.setrecursionlimit to “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 statementPatternWhat the stack holds
Brackets, tags, nested structure, “valid”, “decode k[…]”Matching / nestingUnclosed openers or saved outer context
Expressions, calculators, RPNOperand / operator stacksNumbers, operators, saved (result, sign)
“Next greater/smaller”, “days until warmer”, “span”, “visible people”Monotonic stackIndices of unresolved elements
“Largest rectangle”, “trapping rain water”, “maximal rectangle”Monotonic stack with widthsIndices with increasing heights
“Undo”, “backspace”, “simplify path”, “collisions”, “remove adjacent”Simulation by cancellationSurviving items so far
“Get min in O(1)”, “queue with stacks”Design / augmentationPairs, or two stacks
DFS, backtracking, “iterative” version of recursionExplicit call stackPending states

M.2 Common interview questions (conceptual)

  1. What is the difference between a stack and a queue? Give one algorithm that needs each.
  2. How would you implement a stack with O(1) worst-case push? (Linked list; or a dynamic array with incremental copying — Section N.)
  3. Why is list.append amortised O(1)? What growth policy makes it so?
  4. How do you implement a queue with two stacks, and what is the amortised cost?
  5. Explain what happens in memory when a recursive function recurses too deeply.
  6. 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

HintMap 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

HintOnly 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

HintBuild 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

HintStore 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

HintThe 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

HintNext-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

HintA 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 1For each bar, the widest rectangle of exactly its height extends to the nearest shorter bar on each side.
Hint 2Keep 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

HintOnly + 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.

Level
Difficulty
0 / 23 solved
Saved in this browser

Basic6 problems

Direct applications of this chapter’s core idea.

Stack

Last-in, first-out: matching, evaluation and monotonic stacks.

  1. Implement Stack using Array⤢EASYGeeksforGeeks
  2. Implement Stack using Linked List⤢EASYGeeksforGeeks
  3. Valid Parentheses⤢EASYLeetCode
  4. Implement Stack using Queues⤢EASYLeetCode
  5. Next Greater Element I⤢EASYLeetCode
  6. Min Stack⤢MEDIUMLeetCode

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.

  1. Next Greater Element to the Right⤢MEDIUMGeeksforGeeks
  2. Next Greater Element to the Left⤢MEDIUMGeeksforGeeks
  3. Next Smaller Element to the Right⤢MEDIUMGeeksforGeeks
  4. Next Smaller Element to the Left⤢MEDIUMGeeksforGeeks
  5. Daily Temperatures⤢MEDIUMLeetCode
  6. Stock Span Problem⤢MEDIUMGeeksforGeeks
  7. Next Greater Element II⤢MEDIUMLeetCode
  8. Evaluate Reverse Polish Notation⤢MEDIUMLeetCode
  9. Asteroid Collision⤢MEDIUMLeetCode
  10. Decode String⤢MEDIUMLeetCode
  11. Remove K Digits⤢MEDIUMLeetCode

Advanced4 problems

Harder variants that need the full toolkit and careful invariants.

Stack

Last-in, first-out: matching, evaluation and monotonic stacks.

  1. Sum of Subarray Minimums⤢MEDIUMLeetCode
  2. Largest Rectangle in Histogram⤢HARDLeetCode
  3. Maximum Frequency Stack⤢HARDLeetCode
  4. Robot Collisions⤢HARDLeetCode

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]

Figure N.1 · Execution diagramNext greater element: every bar points right to its answer
input valuearrow to next greateranswerno greater value (−1)
  1. Bars 2 (index 2) and 5 (index 1) both wait on the stack until 25 arrives and pops them together.
  2. 7 and 3 wait under 25 until 8 arrives; 8 pops 3 and 7 but not 25.
  3. 25 and 8 never find a greater value to their right: answer −1.
Technical interpretation: arrows never cross over a taller bar — that is why a stack, which only exposes its most recent element, is enough to find them. Seven pushes, five pops: linear time.

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.

Stacks
What is it?

A collection where you only touch the top. The last item pushed is the first popped: LIFO — Last In, First Out.

Operations
push(x) → put on top
pop() → remove & return top
peek() → look at top

Empty pop / peek = underflow → raise an error.

Python
st = []
st.append(x)  # push
st.pop()      # pop
st[-1]       # peek
if not st:   # empty?
Visual Intuition
top = the most recent
unfinished thing

nesting closes in reverse order of opening

Example

push 3, push 7, push 5, pop, push 9:

after

pop() returned 5 — the last one in.

Bracket check

open → push · close → pop & must match · end → stack empty

★ Key Takeaway

Each item is pushed once and popped at most once ⇒ stack scans are O(n).

Complexity
push / pop (list)O(1)*
peek / emptyO(1)
searchO(n)
spaceO(n)

* amortised (resize = O(n) once in a while)

Benefits
  • O(1) operations.
  • Natural for nesting, undo and recursion.
  • Simple: a Python list is enough.
Use Cases
  • 🧩Valid brackets / tags.
  • 🧮Expression evaluation (RPN).
  • 📈Next greater (monotonic).
  • ↩️Undo / redo, DFS, call stack.
Watch out
  • 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

OpArrayLinked
pushO(1) amortised, O(n) worstΘ(1)
popO(1) amortisedΘ(1)
peek / sizeΘ(1)Θ(1)
n pushes total< 3n writesn allocations

5 · Python syntax

  • list: append, pop(), [-1] (default)
  • deque: same + O(1) left end, maxlen
  • LifoQueue: 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

  1. Why must an array-backed stack keep its top at the end of the array rather than at index 0?
  2. A stack doubles when full. Why is shrinking at one-half full a bad idea, and what rule fixes it?
  3. Give one situation where a linked-list stack is preferable to an array-backed one, and one where the opposite holds.
  4. The monotonic-stack algorithm has a while loop inside a for loop. Prove it runs in O(n).
  5. 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

  1. Starting from an empty ArrayStack() (capacity 1), apply: push a, push b, push c, pop, pop, push d. Give n, capacity and contents after each step.
  2. Evaluate the postfix expression 2 3 4 * + 5 −, showing the stack after every token.
  3. 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

  1. Remove adjacent duplicates. Repeatedly remove pairs of equal adjacent letters: "abbaca" → "ca" (cf. LeetCode 1047). O(n).
  2. Decode string. "3[a2[c]]" → "accaccacc" (cf. LeetCode 394).
  3. Undo/redo editor. Implement type(s), undo() and redo() on a text buffer; a new type after 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
  1. 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]
  2. 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]
  3. 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 list is the default stack.
  4. Each index is pushed exactly once (one push per iteration of the for) and every iteration of the while pops one index. An index cannot be popped more often than it was pushed, so total while iterations ≤ n. Total work = O(n) pushes + O(n) pops + O(n) failed tests = O(n).
  5. 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)
  1. StepncapacityContentsNote
    push a11[a]
    push b22[a, b]grow 1→2, copy 1
    push c34[a, b, c]grow 2→4, copy 2
    pop → c24[a, b]2 ≤ 4/4? no
    pop → b12[a]1 ≤ 4/4 → shrink 4→2
    push d22[a, d]room available, no resize
  2. 2 → [2]; 3 → [2, 3]; 4 → [2, 3, 4]; * → [2, 12]; + → [14]; 5 → [14, 5]; − → [9]. Result 9.
  3. DayPricePoppedSpanStack after (price, span)
    0100—1(100,1)
    180—1(100,1) (80,1)
    260—1(100,1) (80,1) (60,1)
    370(60,1)2(100,1) (80,1) (70,2)
    460—1(100,1) (80,1) (70,2) (60,1)
    575(60,1) (70,2)4(100,1) (80,1) (75,4)
    685(75,4) (80,1)6(100,1) (85,6)
    Spans: [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

  1. 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).
  2. 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).
  3. 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).
  4. 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).
  5. 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).
  6. 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).
  7. Python Software Foundation, queue — A synchronized queue class (LifoQueue). LIFO queue with locking for multi-producer/multi-consumer use (Sections F, H, I, K).
  8. 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).
  9. Python Software Foundation, dis — Disassembler for Python bytecode. CPython bytecode described in terms of the interpreter stack STACK, top = STACK[-1] (Sections F, J).
  10. 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).
  11. Oracle, java.util.Stack (Java SE 21 API). Stack extends Vector; Deque recommended for LIFO operations (Section K).
  12. 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).
  13. WebAssembly Community Group, WebAssembly Core Specification — Runtime Structure. Instructions operate on an implicit stack of values, labels and activations (Sections F, J, N).
  14. 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).
  15. 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).
  16. 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).
  17. CP-Algorithms, “Expression parsing”. Two-stack O(n) expression evaluation with precedence, unary operators and right-associativity (Sections B, C, I, J).
  18. 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).
  19. 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).
  20. Wikipedia contributors, “Call stack” (secondary). Stack frames hold return addresses, parameters and locals; stack overflow (Sections B, F, J, L, P).
  21. Wikipedia contributors, “Shunting yard algorithm” (secondary). Invented by Dijkstra, published November 1961; produces postfix; O(n) (Sections B, I, J).
  22. Wikipedia contributors, “All nearest smaller values” (secondary; cites Berkman, Schieber & Vishkin 1993). Linear-time stack algorithm behind monotonic stacks; parallel algorithms (Sections I, N).
  23. Wikipedia contributors, “Stack-sortable permutation” (secondary; cites Knuth 1968). Catalan-number counts, 231-avoidance (Sections G, P).
  24. 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).
  25. 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.