Everything Data Structures
A complete course on data structures: from asymptotic analysis to the storage engines behind Spanner and Kafka.
Five volumes · 31 chapters · 4 appendices · ~220,000 words · 258 exercises with worked solutions · Python, C, C++, Java, and Go
By Ngoc Anh Khoa Doan, with the editorial help of Claude.
Start here
You do not have to read this front to back. Pick the track that matches what you’re doing:
| If you are… | Start with | Then |
|---|---|---|
| New to data structures | Chapter 1: Philosophy and Mathematics | Work through Volume I in order |
| Preparing for interviews | Appendix B: When to Use What | Volume I, then Graphs and Hash Tables |
| Doing competitive programming | Chapter 23: CP Data Structures | Chapter 24: Research-Grade |
| Building systems | Chapter 29: System Design as Composition | Chapter 31: Case Studies |
| Looking something up | Appendix A: Complexity Cheat Sheet | Chapter 25: Selection Guide |
The full syllabus with chapter-by-chapter reading lists is in the repository README.
What makes this different
It doesn’t stop at red-black trees. Most treatments end where the undergraduate syllabus ends. This one continues through competitive-programming machinery (link-cut trees, wavelet trees, Mo’s algorithm) into research-grade structures like FM-indexes and succinct trees, and then out the other side into distributed systems.
Volume V argues something specific. That network topologies and system designs are data structures, composed at scale. A routing table is a trie. Consistent hashing is a hash ring. A message queue is a persistent FIFO with durability guarantees. Once you see systems this way, system design stops being a separate discipline you memorize and starts being a subject you can reason about from first principles.
Every chapter answers the same questions. What is the idea? What invariant holds? What do the operations cost, and why? What does the code look like? Where is this actually used? Who invented it, and what problem forced them to?
Every chapter ends with exercises. Hand traces on concrete numbers, proofs, find-the-bug snippets, short implementations and design questions, marked ★ (check your understanding), ★★ (apply it) and ★★★ (stretch). Each has a worked solution folded away beneath it, and many have a hint, so you can try first and check after.
Tradeoffs are stated plainly. Fibonacci heaps have the best asymptotic bounds on the page and lose to binary heaps in practice, and this book says so, and explains why. Asymptotic superiority is a claim about a limit, and the limit may sit far beyond any input you will ever see.
The five volumes
Volume I: Foundations and Fundamentals Complexity analysis, memory and pointers, arrays, linked lists, stacks, queues, trees, binary search trees, self-balancing trees, heaps, and B-trees. Everything a working programmer must know.
Volume II: Advanced Structures and Algorithms Graphs and their algorithms, hash tables in depth, and string structures: tries, suffix trees, suffix arrays.
Volume III: Specialized and Modern Structures Probabilistic structures, spatial indexes, external-memory and cache-oblivious design, persistence, concurrency, emerging structures, design patterns, and the practical business of choosing and debugging.
Volume IV: Competitive Programming and Research-Grade Structures The contest arsenal and the research frontier: segment trees with lazy propagation, heavy-light decomposition, link-cut trees, suffix automata, wavelet trees, succinct representations, FM-indexes, and fractional cascading.
Volume V: Network and System Design Data Structures Distributed hash tables, consistent hashing, CRDTs, consensus, routing tables, storage engines, rate limiters, inverted indexes, and case studies of Spanner, Dynamo, Kafka, Delta Lake, and Cloudflare’s edge.
Using this book
Every page has a search (press s), a print/PDF view (the printer icon), and an edit link to its source on GitHub. Corrections are welcome: see the contributing guide.
The prose is CC BY 4.0 and the code is MIT. Use it in your class, your study group, or your blog.
Start with the Preface, or jump straight to Chapter 1.
Preface
Everything Data Structures, by Ngoc Anh Khoa Doan, with the editorial help of Claude.
This book represents a monumental effort to document every significant data structure known to computer science, from the most elementary building blocks to the most sophisticated, specialized, and esoteric structures employed in cutting-edge research and industrial applications. The study of data structures is not merely an academic exercise, it is the foundation upon which all efficient software is built.
The history of data structures mirrors the evolution of computing itself. When John von Neumann conceived the stored-program computer in the 1940s, programmers worked directly with raw memory addresses. As programs grew more complex, the need for organization became apparent. The 1960s and 1970s saw the emergence of fundamental structures, arrays, linked lists, trees, alongside the theoretical frameworks to analyze them. The work of Donald Knuth in “The Art of Computer Programming” codified these structures and established the mathematical rigor that remains the standard today.
The subsequent decades brought new challenges: massive databases requiring disk-optimized structures, distributed systems demanding new approaches to consistency, and probabilistic methods that traded absolute correctness for space efficiency. Each chapter of this book tells the story of how data structures evolved to meet these challenges.
This book is organized into five volumes. Volume I establishes the mathematical foundations and covers the fundamental structures every programmer must master. Volume II explores graphs, hash tables, and string structures. Volume III examines modern developments including probabilistic, spatial, persistent, and concurrent structures. Volume IV covers competitive-programming and research-grade structures. Volume V shows how network topologies and system designs are themselves data structures composed at scale.
Whether you are a student encountering data structures for the first time, a practitioner seeking to optimize a production system, or a researcher exploring the frontiers of the field, this book aims to be your definitive reference.
Ngoc Anh Khoa Doan
Volume I: Foundations and Fundamentals
Everything later in this book is built from the material in this volume. A hash table is an array plus a function. A B-tree is a search tree tuned for disk. A Kafka topic is a queue that never forgets. A lock-free skip list is a linked list with ideas from probability and concurrency. If those foundations are solid, the rest of the book is a series of variations on things you already understand.
The volume moves from the language of cost (Chapter 1) and how memory really works (Chapter 2), through the two ways to store a sequence (contiguous arrays and linked nodes), to the hierarchical structures that make ordered data fast to search.
Before you start. You should be comfortable reading short Python programs: functions, loops, lists, dicts and classes. Most chapters also show C, because C makes memory layout visible. You don’t need any prior data structures course. A little algebra (logarithms, sums of series) helps in Chapter 1 and is explained where it’s used.
Part 1: Mathematical Foundations
| Chapter | After it you can |
|---|---|
| 1: The Philosophy and Mathematics of Data Structures | Read and reason with O, Ω and Θ; tell worst-case, average and amortized cost apart; explain why a dynamic array’s append is O(1) amortized |
| 2: Primitive Types and Memory Organization | Explain what a pointer is, why integers overflow, how structs are padded, how malloc manages the heap (free lists, buddy and slab allocators), and why memory layout affects speed |
Part 2: Fundamental Linear Structures
| Chapter | After it you can |
|---|---|
| 3: Arrays: The Foundation of Contiguous Storage | Implement a growable array, address multi-dimensional data, use binary search, two pointers, sliding windows and prefix sums, and explain how Roaring bitmaps compress sets |
| 4: Linked Lists: The Art of Distributed Storage | Manipulate pointers safely with sentinels, reverse and merge lists in place, detect cycles, and know when a list loses to an array |
| 5: Stacks and Queues: Ordered Access Patterns | Build both on arrays or lists, evaluate expressions with a stack, use circular buffers and deques, and solve next-greater and sliding-window problems with monotonic stacks and queues |
Part 3: Hierarchical Structures and Trees
| Chapter | After it you can |
|---|---|
| 6: Tree Fundamentals and Binary Trees | Use tree vocabulary precisely, traverse a tree four ways (recursively and with an explicit stack), and write recursive tree functions |
| 7: Binary Search Trees | Search, insert and delete in a BST, answer successor, range and rank queries, and explain why insertion order can ruin it |
| 8: Self-Balancing Trees | Perform rotations, insert into and delete from AVL and red-black trees, see a red-black tree as a 2-3-4 tree, and choose between AVL, red-black, splay trees and treaps |
| 9: Heaps and Priority Queues | Implement a binary heap, build one in O(n), support decrease-key, and solve top-k and running-median problems |
| 10: Multiway Search Trees and B-Trees | Insert into and delete from a B-tree, explain why databases use B+ trees, and estimate how many disk reads a lookup costs |
Suggested route
Read Chapters 1, 3, 4 and 5 in order, then 6 and 7 together, since a BST is the first place tree traversals pay off. Chapter 2 can be read alongside Chapter 3 or skimmed if you already know C. Chapter 8 is the hardest in the volume; on a first pass, aim to understand rotations and the red-black invariants, and come back for the deletion cases. Chapter 9 depends only on Chapter 6’s array representation of trees. Read Chapter 10 last, because it brings together search trees and the memory hierarchy from Chapter 2.
Each chapter ends with exercises. Do at least the ★ ones before moving on: they are short and check the ideas the next chapter assumes.
Chapter 1: The Philosophy and Mathematics of Data Structures
1.1 What Data Structures Really Are
A data structure is a systematic organization of data that enables efficient access and modification. But this dry definition obscures what data structures truly represent: the art of translating abstract relationships into concrete, manipulable forms. Every program is a model of some reality, and data structures are the vocabulary of that model.
Consider the challenge of representing a family tree. You could use an array, storing each person and a numeric index indicating their parent. This works, but querying becomes cumbersome, what is the average age of all grandchildren of a particular person? The structure constrains the operations you can perform efficiently.
Now consider representing the same family tree as a tree structure, where each node contains a person’s data and pointers to their children. Suddenly, the query becomes trivial: traverse from the given person to their children, then to their grandchildren, computing ages along the way. The data structure has made the problem tractable.
This relationship between structure and operation lies at the heart of data structure design. There is no universally “best” data structure; there are only structures that are better or worse for particular access patterns, modification patterns, and constraints.
1.2 The Abrahamic Truth: No Free Lunch
The No Free Lunch Theorem, originally formulated in optimization, has profound implications for data structure design. Simply stated: no data structure can excel at all operations. If you want fast search, you sacrifice fast insertion (or vice versa). If you want minimal memory, you sacrifice speed. If you want deterministic worst-case performance, you sacrifice average-case performance.
This fundamental trade-off is why we have so many data structures. Each structure represents a different point in the multi-dimensional space of possible trade-offs. The practitioner’s art lies in understanding which trade-offs matter for their specific application.
Let us enumerate the dimensions of this trade-off space:
Time Complexity Dimensions:
- Search time (point queries)
- Insertion time
- Deletion time
- Range query time
- Successor/predecessor time
- Maximum/minimum access time
- Traversal time
Space Complexity Dimensions:
- Raw space usage
- Overhead per element
- Space amplification under modification
- Fragmentation behavior
Operational Dimensions:
- Sequential access patterns
- Random access patterns
- Bulk operations
- Persistence and versioning
Implementation Dimensions:
- Complexity of implementation
- Debugging difficulty
- Cache behavior
- Thread safety
1.3 Asymptotic Analysis: The Language of Efficiency
Computer scientists use asymptotic notation to describe the behavior of algorithms and data structures as input sizes grow arbitrarily large. This approach abstracts away machine-specific constants and focuses on the fundamental growth rate.
Big-O Notation: Upper Bounds
O(f(n)) describes an upper bound on running time. f(n) = O(g(n)) means that f grows no faster than some constant multiple of g for sufficiently large n. Formally:
∃ c > 0, ∃ n₀ > 0, such that ∀ n ≥ n₀: 0 ≤ f(n) ≤ c·g(n)
When we say array indexing is O(1), we mean the access time is bounded by a constant, regardless of how many elements are stored. This is an upper bound, we’re saying access will never be worse than constant time.
Big-Omega Notation: Lower Bounds
Ω(f(n)) describes a lower bound. f(n) = Ω(g(n)) means f grows at least as fast as g for sufficiently large n. Formally:
∃ c > 0, ∃ n₀ > 0, such that ∀ n ≥ n₀: 0 ≤ c·g(n) ≤ f(n)
When we say comparison-based sorting requires Ω(n log n), we’re establishing that no comparison sort can do better in the worst case. This is a fundamental lower bound.
Theta Notation: Tight Bounds
Θ(f(n)) indicates both upper and lower bounds. f(n) = Θ(g(n)) means f grows asymptotically the same rate as g. Formally:
∃ c₁ > 0, ∃ c₂ > 0, ∃ n₀ > 0, such that ∀ n ≥ n₀: c₁·g(n) ≤ f(n) ≤ c₂·g(n)
When we say mergesort is Θ(n log n), we mean this is both an upper bound (it won’t be slower) and a lower bound (you can’t do better).
Little-o and Little-Omega: Asymptotic Inequalities
o(f(n)) means “grows strictly slower than f(n)”: lim(n→∞) g(n)/f(n) = 0
ω(f(n)) means “grows strictly faster than f(n)”: lim(n→∞) g(n)/f(n) = ∞
1.4 Common Complexity Classes
Understanding the practical implications of different complexity classes is essential:
Constant Time: O(1)
- Array indexed access
- Hash table lookup (with good hash function)
- Bit operations
- Stack push/pop
- Queue enqueue/dequeue
The signature of O(1) is “doesn’t depend on n.” Whether you have 10 elements or 10 million, the operation takes the same time.
Logarithmic Time: O(log n)
- Binary search in sorted array
- Balanced tree operations (BST, AVL, Red-Black, B-Tree)
- Skip list operations (expected, not worst case)
Logarithmic growth is remarkably slow. Even at n = 1 billion, log₂(n) ≈ 30. This means an O(log n) operation takes at most about 30 steps for a billion elements.
O(log n) is the floor for comparison-based search, but not for every kind of search. When keys are integers below some bound u, a van Emde Boas tree answers predecessor queries in O(log log u), about 5 steps for 32-bit keys, by exploiting the bits of the key rather than comparing whole keys (Chapter 24).
Linear Time: O(n)
- Sequential scan of array
- Linked list traversal
- Breadth-first or depth-first graph search
- Counting sort (under constraints)
- Hash table operations with poor hash function
Linearithmic Time: O(n log n)
- Comparison-based sorting (merge sort, heap sort, quicksort average case)
- Building a heap by n successive inserts (bottom-up heapify builds one in O(n))
- Balanced tree operations if rebuilding required
Polynomial Time: O(n^k)
- Simple matrix operations
- Naive string matching (O(nm))
- Certain dynamic programming solutions
Exponential Time: O(2^n)
- Generating all subsets
- Naive solutions to NP-complete problems
- Recursive Fibonacci without memoization
Factorial Time: O(n!)
- Generating all permutations
- Traveling salesman brute force
- Certain combinatorial problems
1.5 Amortized Analysis: Averaging the Worst
Sometimes we care less about individual operation cost and more about total cost over a sequence of operations. Amortized analysis computes the average cost per operation over a worst-case sequence.
Consider a dynamic array (like Python’s list or Java’s ArrayList). When it fills, it doubles its capacity and copies all elements. This copy costs O(n), which seems expensive. However, this expensive operation happens only rarely, specifically, when the array size is a power of 2.
Over n insert operations, the total cost is: n + (1 + 2 + 4 + 8 + … + n) ≤ n + 2n = 3n
So the amortized cost per insert is O(3n/n) = O(1). Each individual insert is O(1) on average, even though occasional inserts are O(n).
Three techniques for amortized analysis exist:
Aggregate Analysis: Simply sum the costs of all operations and divide by n. If the total cost of any sequence of n operations is T(n), the amortized cost is T(n)/n.
Accounting Method: Assign different charges to different operations. Some operations are charged more than they cost; the excess is stored as “credit” and used to pay for operations that cost more than they were charged. The total credit never goes negative.
For dynamic arrays, we might charge 3 units for each insert: 1 unit for the immediate insert, 1 unit to copy this element at the next resize, and 1 unit to copy one of the older elements that were already copied at the previous resize.
Potential Method: Define a potential function Φ that maps data structure states to non-negative numbers. The amortized cost of an operation is the real cost plus the change in potential:
amortized_cost = real_cost + ΔΦ
If Φ is always non-negative and Φ(start) = 0, the total amortized cost is an upper bound on total real cost.
For a dynamic array, define Φ = 2n - m, where n is the current size and m is the capacity. Right after a doubling, before the new element is written, the array is half full and Φ = 0. When the array is full, Φ = n (its maximum), exactly enough to pay for copying the n elements at the next resize.
1.6 The RAM Model and Real Costs
Theoretical analysis assumes the Random Access Machine (RAM) model, where:
- All operations (arithmetic, memory access) take constant time
- Memory is unbounded
- No cache effects
Reality is more complex. Modern computers have hierarchical memory:
- L1 cache: ~32KB, ~1ns access
- L2 cache: ~256KB, ~4ns access
- L3 cache: ~8MB, ~15ns access
- Main memory: ~64GB, ~100ns access
- SSD: ~100GB, ~100μs access
- Hard disk: ~TB, ~10ms access
A structure that minimizes main memory accesses may perform better than one with theoretically superior asymptotic complexity. This is why:
- Arrays often outperform linked lists (cache-friendly sequential access)
- B-trees outperform binary trees for database indexes (fewer disk accesses)
- Cache-oblivious structures adapt to all levels automatically
1.7 Lower Bounds: How Low Can You Go?
A lower bound establishes that no algorithm can do better than a certain complexity. Proving lower bounds is often more difficult than proving upper bounds.
Comparison-Based Sorting: Ω(n log n) The proof uses a decision tree argument. Any comparison sort can be represented as a binary decision tree, where each internal node represents a comparison and each leaf represents a final ordering. A binary tree with L leaves must have height at least log₂ L. Since there are n! possible orderings, the tree needs at least n! leaves, requiring height at least log₂(n!) = Ω(n log n).
Static Dictionary: Ω(log n) For static sets (no insertions or deletions), any comparison-based structure answering membership queries needs Ω(log n) comparisons in the worst case. This is why binary search and balanced binary trees are optimal among comparison-based structures for static ordered sets. Hashing escapes the bound because it does not compare keys: FKS perfect hashing answers static membership in O(1) worst-case time with O(n) space.
Dynamic Dictionary: Ω(1) Surprisingly, with amortization or randomization, we can achieve O(1) expected time for dynamic sets. Hash tables achieve this, though at the cost of worst-case degradation.
1.8 References for Further Study
The mathematical foundations of data structures draw from several disciplines:
- Combinatorics: Counting arguments in decision tree lower bounds
- Information Theory: Entropy bounds on compression and encoding
- Algebra: Group theory in symmetric structures, polynomial methods
- Probability: Randomization in skip lists, hashing, and probabilistic data structures
- Algebraic Topology: Recent connections to persistent homology and spatial data structures
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
1.1 ★ Constants for a Θ bound. Show that f(n) = 3n² + 10n + 5 is Θ(n²) by giving explicit constants c₁, c₂ and n₀ that satisfy the formal definition in Section 1.3. Then explain why the definition needs n₀ at all.
Solution
Take c₁ = 3 and c₂ = 4.
- Lower bound: 3n² ≤ 3n² + 10n + 5 holds for every n ≥ 1, since 10n + 5 > 0.
- Upper bound: 3n² + 10n + 5 ≤ 4n² is equivalent to 10n + 5 ≤ n². At n = 10 this is 105 ≤ 100, which fails. At n = 11 it is 115 ≤ 121, which holds, and for larger n the left side grows by 10 per step while the right side grows by 2n + 1 ≥ 23, so it keeps holding.
So c₁ = 3, c₂ = 4, n₀ = 11 work. Other choices are fine too: c₂ = 18 works from n₀ = 1, because 3n² + 10n + 5 ≤ 3n² + 10n² + 5n² for n ≥ 1.
n₀ exists so that small inputs, where lower-order terms dominate, do not decide the bound. With c₂ = 4 the inequality is false for n ≤ 10 and true forever after; asymptotic notation only cares about “forever after”.
1.2 ★ Count the copies. A dynamic array starts with capacity 1 and doubles its capacity whenever an insert finds it full. Starting from empty, you insert 17 elements. Which inserts trigger a resize, how many element copies happen in total, and what is the total cost if each write of a new element costs 1 and each copy costs 1? Compare the total with the 3n bound from Section 1.5.
Solution
A resize happens when an insert finds size = capacity:
| Insert # | Size before | Capacity before | Copies | Capacity after |
|---|---|---|---|---|
| 2 | 1 | 1 | 1 | 2 |
| 3 | 2 | 2 | 2 | 4 |
| 5 | 4 | 4 | 4 | 8 |
| 9 | 8 | 8 | 8 | 16 |
| 17 | 16 | 16 | 16 | 32 |
Total copies: 1 + 2 + 4 + 8 + 16 = 31. Total cost: 17 writes + 31 copies = 48. The bound is 3 × 17 = 51, so 48 ≤ 51 as promised.
The copies form a geometric series whose largest term (16) is less than n = 17, so the copies sum to less than 2n. Insert 17 is the worst case for this n: it pays for a 16-element copy and then leaves the new array almost empty.
1.3 ★★ Rank the growth rates. Order these functions from slowest-growing to fastest-growing as n → ∞. Mark any two that are Θ of each other.
n log₂ n, n^1.5, 2^(log₂ n), log₂(n!), n² / log₂ n, √n, (log₂ n)³, 1.01ⁿ
Hint
Simplify first: one of these is just n in disguise, and Section 1.7 tells you the order of log₂(n!). For a polylog against a power, substitute n = 2^k.
Solution
(log₂ n)³ < √n < 2^(log₂ n) < n log₂ n ≡ log₂(n!) < n^1.5 < n² / log₂ n < 1.01ⁿ
Reasons, pair by pair:
- (log₂ n)³ vs √n. With n = 2^k the ratio is k³ / 2^(k/2), which goes to 0. Any power of a logarithm is o(n^ε) for every ε > 0. The crossover is late, though: √n only passes (log₂ n)³ at about n ≈ 6 × 10⁸, so for small inputs the “slower” function is larger.
- 2^(log₂ n) is exactly n.
- n vs n log₂ n. The ratio is log₂ n, which is unbounded.
- n log₂ n vs log₂(n!). These are Θ of each other: log₂(n!) ≤ n log₂ n trivially, and log₂(n!) ≥ (n/2) log₂(n/2) (see Exercise 1.5).
- n log₂ n vs n^1.5. Divide both by n: log₂ n is o(√n).
- n^1.5 vs n² / log₂ n. The ratio (n² / log₂ n) / n^1.5 = √n / log₂ n is unbounded.
- n² / log₂ n vs 1.01ⁿ. Every exponential with base > 1 eventually beats every polynomial. Here 1.01ⁿ overtakes n² / log₂ n at about n ≈ 1,190.
1.4 ★★ The potential method by hand. Use the potential Φ = 2n − m from Section 1.5 (n = size, m = capacity) for a doubling dynamic array. Charge real cost 1 for writing the new element plus 1 per element copied. Compute the amortized cost (real cost + ΔΦ) of (a) an insert that does not resize and (b) an insert that finds the array full with n = m elements.
Hint
In case (b), compute Φ before the insert with n = m, and Φ after with size m + 1 and capacity 2m.
Solution
(a) No resize. Real cost 1. n grows by 1 and m is unchanged, so ΔΦ = 2. Amortized cost = 1 + 2 = 3.
(b) Resize. Real cost is m copies plus 1 write, so m + 1.
- Before: Φ = 2m − m = m.
- After: size m + 1, capacity 2m, so Φ = 2(m + 1) − 2m = 2.
- ΔΦ = 2 − m.
Amortized cost = (m + 1) + (2 − m) = 3.
Both cases cost exactly 3, so n inserts have amortized cost 3n. The potential built up by cheap inserts (2 per insert) is what pays for the copy: by the time the array is full, Φ has climbed to m, and the resize spends it. Because Φ ≥ 0 after the first insert, total real cost is at most total amortized cost (up to the constant Φ at the start), which gives the same 3n bound as aggregate analysis.
1.5 ★★ How many comparisons does sorting 10 items need? Section 1.7 claims log₂(n!) = Ω(n log n) without proof.
(a) Prove log₂(n!) ≥ (n/2) log₂(n/2) for n ≥ 2, and conclude that log₂(n!) = Θ(n log n).
(b) Use the decision-tree argument to give a lower bound on the number of comparisons any comparison sort needs in the worst case on 10 elements.
Hint
For (a), throw away the smaller half of the factors in n! = 1 × 2 × … × n, and make each remaining factor smaller too.
Solution
(a) n! = 1 × 2 × … × n. The largest ⌈n/2⌉ factors are each at least n/2, and the rest are at least 1, so
n! ≥ (n/2)^(n/2)
Taking log₂ of both sides gives log₂(n!) ≥ (n/2) log₂(n/2) = (n/2)(log₂ n − 1), which is at least (n/4) log₂ n once n ≥ 4. So log₂(n!) = Ω(n log n). For the upper bound, each of the n factors is at most n, so n! ≤ nⁿ and log₂(n!) ≤ n log₂ n. Together: log₂(n!) = Θ(n log n).
(b) 10! = 3,628,800 orderings, so the decision tree needs at least that many leaves. A binary tree of height h has at most 2^h leaves, so 2^h ≥ 3,628,800, giving h ≥ log₂(3,628,800) ≈ 21.79. Height is an integer, so h ≥ 22: some input forces at least 22 comparisons. (This bound happens to be achievable; 22 comparisons suffice for 10 elements. Merge sort uses up to 25.)
1.6 ★★★ Shrinking without thrashing. You add a pop operation to the doubling array, and to save memory you halve the capacity whenever a pop leaves the array at most half full (n ≤ m/2).
(a) Find a sequence of operations that costs Θ(n) per operation.
(b) Change the rule to: halve the capacity when a pop leaves the array at most a quarter full (n ≤ m/4). Argue that every operation is now amortized O(1).
Hint
For (a), start from a full array and alternate push and pop. For (b), ask how full the array is immediately after any resize, and how many operations must happen before the next one.
Solution
(a) Fill the array so that n = m = 2^k. Then repeat: push, pop, push, pop, …
- push: the array is full, so it doubles to capacity 2m and copies m elements. Now n = m + 1.
- pop: now n = m ≤ 2m/2, so it halves to capacity m and copies m elements. Now n = m = capacity again.
- push: full again, double, copy m elements.
Every operation after the fill copies m ≈ n elements, so a sequence of length 2n costs Θ(n²), Θ(n) per operation. The two thresholds coincide, so the array never gets to accumulate slack between resizes. In a simulation with m = 1024, 4,000 alternating operations after the fill copy about 4.1 million elements.
(b) Immediately after any resize, the array is (essentially) half full:
- After a grow from capacity m to M = 2m, the size is m + 1 ≈ M/2.
- After a shrink from capacity 2M to M (triggered at n = 2M/4 = M/2), the size is M/2.
From that state, the next grow needs the size to rise from about M/2 to M: at least about M/2 pushes. The next shrink needs the size to fall from M/2 to M/4: at least M/4 pops. Either way, at least about M/4 operations happen between consecutive resizes, and a resize copies at most M elements. Charging the copy to those operations costs at most about 4 copies each, so every operation is amortized O(1). (Rerunning the simulation from (a) with the quarter rule, the 4,000 alternating operations trigger exactly one resize, a 1,024-element copy on the first push, instead of 4.1 million copies.)
The general lesson: the grow threshold and the shrink threshold must be separated by a constant factor, so that a resize always leaves room for Θ(m) cheap operations before the next one.
Where this connects
- Chapter 22: Practical Considerations. How these bounds translate into actual decisions
- Chapter 16: External Memory and Cache-Oblivious Structures. Why the RAM model this chapter assumes is not how real hardware behaves
Chapter 2: Primitive Types and Memory Organization
2.1 The Building Blocks: Primitive Data Types
Every data structure ultimately decomposes into primitive types, fundamental units that the hardware directly supports. Understanding these types, their properties, and their cost is essential for effective data structure design.
Boolean Type
The boolean type represents truth values. While conceptually just two states (true and false), implementation varies:
- C/C++: Typically stored as one byte, with 0 representing false and 1 representing true
- Java: Strictly one bit conceptually, but one byte in arrays
- Python: Full objects with True/False keywords
- Hardware: Boolean operations are fundamental CPU operations
Boolean operations (AND, OR, NOT, XOR) are typically constant-time hardware operations. However, boolean arrays (bitsets) can be significantly more space-efficient than boolean objects.
Integer Types
Integer types represent whole numbers with various ranges:
| Type | Typical Size | Range (signed) | Range (unsigned) |
|---|---|---|---|
| byte | 8 bits | -128 to 127 | 0 to 255 |
| short | 16 bits | -32,768 to 32,767 | 0 to 65,535 |
| int | 32 bits | -2.1B to 2.1B | 0 to 4.3B |
| long | 64 bits | -9.2Q to 9.2Q | 0 to 18.4Q |
The “long” type illustrates how naming varies across languages:
- Java: long is always 64 bits
- C/C++: long may be 32 or 64 bits depending on platform
- Python: integers are arbitrary precision (bignums)
Integer overflow is a subtle source of bugs. In two’s complement representation (virtually universal), adding 1 to the maximum value wraps to the minimum value. This has caused real-world bugs:
- Ariane 5 rocket explosion (1996): 64-bit to 16-bit conversion overflow
- Boeing 787 (2015): a 32-bit counter in the generator control units overflowed after 248 days of continuous power, which could shut down all AC power
- YouTube (2014): the view counter for “Gangnam Style” exceeded 2,147,483,647, the largest signed 32-bit integer
Floating-Point Types
Floating-point numbers represent real numbers with limited precision:
| Type | Typical Size | Precision | Range |
|---|---|---|---|
| float | 32 bits | ~7 decimal digits | ±10^38 |
| double | 64 bits | ~15 decimal digits | ±10^308 |
| extended | 80 bits | ~19 decimal digits | Platform-dependent |
IEEE 754 standardizes floating-point representation:
- 1 bit: sign
- 8 bits: exponent (biased)
- 23 bits: mantissa (fraction)
This gives the familiar scientific notation: (-1)^sign × 1.mantissa × 2^(exponent − 127) for normal numbers. A 64-bit double has the same layout with an 11-bit exponent (bias 1023) and a 52-bit fraction.
Key considerations for data structures:
- Floating-point equality is problematic (0.1 + 0.2 ≠ 0.3)
- NaN (Not a Number) propagates through operations
- Infinity arithmetic has special rules
- Denormalized numbers provide gradual underflow
Why 0.1 + 0.2 ≠ 0.3. A double holds a 53-bit binary significand, and 1/10 has no finite binary expansion (0.0001100110011… in binary, repeating forever), so the literal 0.1 is rounded to the nearest double. float.hex and decimal.Decimal show exactly what is stored:
from decimal import Decimal
for x in (0.1, 0.2, 0.3, 0.1 + 0.2):
print(x.hex(), Decimal(x))
0x1.999999999999ap-4 0.1000000000000000055511151231257827021181583404541015625
0x1.999999999999ap-3 0.200000000000000011102230246251565404236316680908203125
0x1.3333333333333p-2 0.299999999999999988897769753748434595763683319091796875
0x1.3333333333334p-2 0.3000000000000000444089209850062616169452667236328125
The repeating hex digit 9 ends in a rounded-up a, so 0.1 and 0.2 are both stored slightly too large, while 0.3 is stored slightly too small. The exact sum of the two stored values is 0.3000000000000000166533453693773481063544750213623046875. Doubles between 0.25 and 0.5 are 2^−54 ≈ 5.55 × 10^−17 apart, and this sum lies exactly halfway between the double for 0.3 (significand ending in hex 3) and the next one up (ending in hex 4). IEEE 754’s default rounding breaks ties toward the even significand, the one ending in 4, so 0.1 + 0.2 is one unit in the last place above 0.3. Every step was correctly rounded; the inputs were never the decimal numbers they were written as. Compare with a tolerance (math.isclose), or compute in integers (cents, not dollars) or decimal when exact decimal results matter. Exercise 2.5 shows what the difference does to a hash table.
Character Types
Characters represent text elements:
- ASCII: 7 bits (128 characters), includes control characters and basic Latin
- Extended ASCII: 8 bits (256 characters), various ISO-8859 pages
- Unicode: Variable-width, includes virtually all writing systems
- UTF-8: Variable 1-4 bytes, ASCII-compatible, dominant on the web
- UTF-16: 2 or 4 bytes, used in Java, Windows, JavaScript strings
The choice of character encoding affects string data structure design significantly.
2.2 Memory Organization and Addressing
Understanding how memory is organized helps in designing efficient data structures.
Byte-Addressable Memory
Modern computers are byte-addressable: each byte has a unique address. Larger types (ints, floats) occupy multiple consecutive bytes.
The endianness question: which byte is stored at the lowest address?
- Little-endian (Intel, ARM): Least significant byte first
- Value 0x01234567 stored as 67 45 23 01 at addresses 0,1,2,3
- Big-endian (Network order, some RISC): Most significant byte first
- Value 0x01234567 stored as 01 23 45 67 at addresses 0,1,2,3
Mixed-endian architectures exist but are rare. The choice affects:
- Network protocol compatibility
- Binary file formats
- Debugging (hex dumps appear “reversed” on little-endian)
- Type punning through memory
Alignment and Padding
Modern CPUs are optimized to access memory at aligned addresses. A 4-byte int should be at an address divisible by 4; an 8-byte double should be at an address divisible by 8.
When structures contain multiple types, compilers insert padding to maintain alignment:
struct Example {
char a; // 1 byte, offset 0
// 3 bytes padding
int b; // 4 bytes, offset 4
char c; // 1 byte, offset 8
// 3 bytes padding (struct alignment is 4, from int)
};
// sizeof(Example) = 12 (on common 32- and 64-bit ABIs)
The #pragma pack directive and attribute((packed)) can eliminate padding, but at a cost: unaligned accesses may be slower or even cause hardware exceptions on some architectures.
Stack vs. Heap Memory
Two primary memory regions exist for dynamic data:
Stack:
- Automatic memory management
- Fast allocation (just move stack pointer)
- Automatic deallocation (scope-based)
- Limited size (typically 1-8MB)
- Perfect for small, short-lived objects
- Local variables, function parameters, return addresses
Heap:
- Manual management (malloc/free, new/delete)
- Slower allocation (search for a free block, Section 2.5)
- Manual or garbage-collected deallocation
- Large size (limited by physical + virtual memory)
- Good for large or long-lived objects
- Dynamic data structures
The stack’s speed comes from its simplicity: allocation is decrementing a pointer, deallocation is incrementing. However, the stack cannot grow indefinitely, and objects must have known lifetimes.
2.3 Pointers and References
Pointers are variables that store memory addresses. They are the fundamental mechanism for building dynamic, linked data structures.
Pointer Basics
int x = 42;
int *p = &x; // p stores address of x
int y = *p; // y = 42 (dereference p)
*p = 100; // x = 100 (modify through pointer)
The pointer-to-pointer pattern allows modification of pointers themselves:
void insert(Node **head, int value) {
Node *new = malloc(sizeof(Node));
new->data = value;
new->next = *head;
*head = new;
}
Pointer Arithmetic
In C and C++, pointers can be incremented and decremented:
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // Points to arr[0]
p++; // Points to arr[1]
int val = *(p + 2); // Value at arr[3] = 40
This arithmetic is scaled by the size of the pointed-to type. p++ moves by sizeof(*p) bytes.
Null Pointers
The null pointer represents “points to nothing.” Its representation is implementation-defined but is typically address 0. Dereferencing null causes undefined behavior (usually a crash).
Modern C++ prefers nullptr over NULL (which is just 0, potentially ambiguous with integer 0). Java and Python use null or None for reference types.
Reference Types
References (C++, and analogous concepts in other languages) are aliases to existing objects:
int x = 42;
int &r = x; // r is another name for x
r = 100; // x = 100
Unlike pointers:
- References must be initialized
- References cannot be reseated
- References cannot be null
- Access syntax is cleaner (no dereference operator)
References provide the safety of not being null while maintaining the efficiency of pointer-based indirection.
2.4 Records and Structures
Records (called structs in C, classes in object-oriented languages) group related fields:
struct Student {
char name[50];
int id;
float gpa;
struct Student *advisor; // Pointer for linked structures
};
Memory Layout
Structures are laid out sequentially in memory, with padding as needed for alignment. The programmer can control layout with pragmas or attributes:
// Force tight packing (no padding)
struct PackedStudent {
char name[50];
int id;
float gpa;
} __attribute__((packed));
Bit Fields
C and C++ allow specifying field widths in bits:
struct Flags {
unsigned int is_signed : 1;
unsigned int is_array : 1;
unsigned int size : 6; // 0-63
};
Bit fields pack multiple boolean or small-integer fields into single bytes. However, they have drawbacks:
- No addressable pointer to a bit field
- Layout is implementation-defined
- May be slower to access than full bytes
2.5 How malloc Works: Allocators as Data Structures
Section 2.2 described heap allocation as “search for a free block”. That search is a data-structure problem in its own right. The allocator keeps a set of free address ranges and must answer two operations quickly: malloc(n), “give me a range of at least n bytes”, and free(p), “the range starting at p is free again”. Every linked structure in this book calls malloc once per node, so the allocator’s costs show up inside all of them.
The Problem
Three facts make this harder than it looks.
- Sizes vary and frees arrive in any order. A C or C++ allocator cannot move a live block, because the program holds raw pointers to it and the allocator cannot find them all to fix them up. (A compacting garbage collector can, which is why it doesn’t have this problem.) So the free space breaks into holes between live blocks.
free(p)gets only a pointer. The allocator must recover the block’s size and find its neighbours from the address alone. Programs callfreeabout as often asmalloc, so this has to be O(1), not a search.- Memory is lost two ways. Internal fragmentation is space inside an allocated block that the program didn’t ask for: headers, alignment padding, rounding up to a size class. External fragmentation is free memory split into holes too small to use. Fill a 1 MiB heap with 1,024 blocks of 1 KiB and free every other one: 512 KiB is free, yet a 2 KiB request fails because no two free blocks are adjacent.
No placement policy avoids external fragmentation on every input. J. M. Robson showed in 1971 that for any allocator that never moves blocks, some sequence of requests forces the heap to exceed the live data by a factor that grows with the logarithm of the ratio between the largest and smallest block sizes. Allocators are therefore judged on real programs, not worst cases.
Implicit Free Lists and Boundary Tags
The simplest design puts the bookkeeping in the heap itself. Each block starts with a one-word header holding the block’s size. Sizes are multiples of the alignment (8 or 16 bytes on real systems), so the low bits of the size are always zero, and one of them stores an “allocated” flag. Starting from the first block and adding sizes walks every block in address order: the list is implicit, because the links are the sizes.
malloc(n)walks the blocks until it finds a free one that is big enough. If the block is much bigger, it splits it: the front becomes the allocated block and the rest a new free block. It returns the address just past the header.free(p)reads the header one word beforepto get the size. The next block’s header is at the header plus the size, so checking whether the next block is free and merging with it (coalescing) is O(1).
The previous block is the hard part. Nothing in our header says where the previous block starts. Knuth’s boundary tag fixes this: copy the tag into a footer, the last word of every block. The word just before our header is then the previous block’s footer, which gives its size and state in O(1). With immediate coalescing on every free, the heap keeps one invariant: no two free blocks are adjacent.
The simulation below models the heap as a Python list of words. Sizes are in words and always even, so bit 0 of a tag is free to hold the allocated flag.
class FreeListHeap:
"""Implicit free list with boundary tags, first fit and immediate coalescing.
mem is the heap, one list entry per word. Every block is laid out as
[header, payload..., footer], and header and footer both hold the tag
size | used, where size counts the whole block in words and is always even.
"""
MIN_BLOCK = 4 # header + 2 payload words + footer
def __init__(self, words):
assert words % 2 == 0 and words >= self.MIN_BLOCK
self.mem = [0] * words
self._tag(0, words, 0) # one free block covers the heap
def _tag(self, addr, size, used):
self.mem[addr] = self.mem[addr + size - 1] = size | used
def _size(self, i): # i is a header or footer word
return self.mem[i] & ~1
def _used(self, i):
return self.mem[i] & 1
def blocks(self):
addr = 0
while addr < len(self.mem):
yield addr, self._size(addr), self._used(addr)
addr += self._size(addr)
def malloc(self, n):
need = max(self.MIN_BLOCK, (n + 3) & ~1) # n + header + footer, rounded up to even
for addr, size, used in self.blocks(): # first fit: lowest address that fits
if not used and size >= need:
if size - need >= self.MIN_BLOCK: # split; the tail stays free
self._tag(addr + need, size - need, 0)
size = need
self._tag(addr, size, 1)
return addr + 1 # the pointer is the first payload word
return None # no free block is big enough
def free(self, p):
addr = p - 1
size = self._size(addr)
nxt = addr + size
if nxt < len(self.mem) and not self._used(nxt): # next block's header
size += self._size(nxt)
if addr > 0 and not self._used(addr - 1): # previous block's footer
addr -= self._size(addr - 1)
size += self._size(addr)
self._tag(addr, size, 0)
A trace on a 24-word heap, writing blocks as start:size with U for used and F for free:
| Operation | Returns | Blocks afterwards | What happened |
|---|---|---|---|
| start | 0:24 F | one free block | |
p = malloc(3) | 1 | 0:6 U, 6:18 F | 3 + 2 tags = 5, rounded up to 6; split |
q = malloc(5) | 7 | 0:6 U, 6:8 U, 14:10 F | 5 + 2 = 7, rounded up to 8 |
r = malloc(2) | 15 | 0:6 U, 6:8 U, 14:4 U, 18:6 F | exactly the minimum block |
free(p) | 0:6 F, 6:8 U, 14:4 U, 18:6 F | both neighbours used (there is no left one) | |
free(r) | 0:6 F, 6:8 U, 14:10 F | header at 18 says free: merge right | |
free(q) | 0:24 F | header at 14 and footer at 5 both say free: merge both ways |
After the three malloc calls the list mem begins [7, 0, 0, 0, 0, 7, 9, ...]: tag 7 is size 6 with the used bit set, and the same tag sits in word 0 (header) and word 5 (footer). Each block carries one word of internal fragmentation from rounding plus two words of tags.
Cost. free is O(1) worst case. malloc is O(B) worst case, where B is the number of blocks, allocated and free, because the walk steps over every allocated block too. The footer costs a word per block. Real allocators such as dlmalloc save it on allocated blocks: a free block keeps its footer, and each header carries a “previous block in use” bit, so the footer is only read when that bit says the previous block is free.
Explicit Free Lists and Placement Policies
Walking allocated blocks is wasted work. An explicit free list threads a doubly linked list (Chapter 4) through the free blocks only, storing the prev and next pointers in the free block’s payload, which nobody else is using. malloc now costs O(F) for F free blocks. free stays O(1): coalescing unlinks the free neighbours, which a doubly linked list does in O(1) given the node, and pushes the merged block. The price is a larger minimum block, header plus two pointers plus footer: 32 bytes on a 64-bit machine, so malloc(1) costs 32 bytes. Pushing freed blocks at the head (LIFO order) is O(1); keeping the list sorted by address costs O(F) per free but fragments less.
Which free block to choose is the placement policy:
- First fit takes the first block in the list that is big enough. With an address-ordered list, small leftover splinters collect at the low addresses and every search has to step over them.
- Next fit resumes the search where the previous one stopped. Searches are shorter, but allocations get scattered across the whole heap.
- Best fit takes the smallest block that is big enough, leaving the smallest leftover. On a plain list it scans all F blocks; with free blocks kept in a balanced tree or a trie keyed by size it costs O(log F).
Intuition says best fit should create many useless tiny leftovers. Measurements say otherwise: Johnstone and Wilson (“The Memory Fragmentation Problem: Solved?”, 1998) replayed the allocation traces of real programs and found that best fit and address-ordered first fit both waste very little memory, while next fit does noticeably worse. Neither policy dominates on every input (Exercise 2.8 builds a case for each), and Knuth’s fifty-percent rule says the search cost doesn’t go away: in steady state under first fit there are about half as many free blocks as allocated ones.
Segregated Free Lists and Size Classes
Every production allocator replaces the single list with an array of lists, one per size class. malloc(n) rounds n up to its class and pops the head of that list in O(1), falling back to a larger class or fresh memory only when the list is empty. Most programs allocate a small number of distinct sizes over and over, so the fast path hits almost every time.
The extreme form, simple segregated storage, gives each class its own pages carved into equal slots and never splits or coalesces. Objects then need no header at all: the allocator finds the size class from the page the address falls in. What it gives up is flexibility: memory parked in the free list of one class cannot serve a request for another.
- dlmalloc (Doug Lea, first released in 1987) is “in most ways a best-fit allocator”, in its own documentation’s words. Chunks under 256 bytes live in small bins, exact-size doubly linked lists 8 bytes apart, and larger free chunks live in bins covering ranges of sizes, kept as bitwise tries so the best fit is found quickly. Chunks carry Knuth’s boundary tags. glibc’s
malloc(ptmalloc) is derived from it and added a per-thread cache, tcache, in glibc 2.26 (2017). - jemalloc (Jason Evans, written for FreeBSD’s libc) spaces its small size classes at four per doubling of size after the smallest ones: 16, 32, 48, …, 128, then 160, 192, 224, 256, then 320, 384, 448, 512, and so on. Its manual states that this limits internal fragmentation to about 20% for all but the smallest classes: a 129-byte request gets a 160-byte slot and wastes 31 bytes, 19%. It runs several independent arenas (by default four per CPU) to cut lock contention, and gives each thread a cache of free objects so most requests need no synchronization at all.
- tcmalloc (Google, “thread-caching malloc”) maps small requests to one of 60 to 80 size classes. Its front end is a cache per thread (the original design) or, in newer versions, per CPU. Behind it, each size class has a transfer cache and a central free list that carves objects out of spans of pages; requests above the largest class go straight to the page heap.
The thread or CPU cache matters as much as the size classes. A single free list behind one lock serializes every allocation in a multithreaded program. A thread-local list needs no lock and no atomic instruction; the cost is memory sitting idle in one thread’s cache while another thread asks the operating system for more.
The Buddy System
The buddy system trades internal fragmentation for very cheap coalescing. The managed space has 2^m units. Every block has a size 2^k (its order is k) and starts at a multiple of 2^k. There is one free list per order.
- Allocate n units: round up to the smallest order k with 2^k ≥ n. Take a free block of the smallest order j ≥ k that has one. While j > k, split it into two halves of order j − 1, keep the low half and put the high half on the free list. The two halves of a split are each other’s buddies.
- Free a block of order k at address a: its buddy is at a XOR 2^k. Because a is a multiple of 2^k, bit k is the only bit that differs between the low and high halves of their parent, so flipping it gives the other half. If the buddy is free and still of order k, merge the two into the parent (which starts at
awith bit k cleared) and repeat one order up.
No footers and no searching for neighbours: the address alone identifies the only block it can merge with.
class BuddyAllocator:
"""Binary buddy system over addresses 0 .. 2**max_order - 1 (units, e.g. pages)."""
def __init__(self, max_order):
self.max_order = max_order
self.free_lists = [set() for _ in range(max_order + 1)] # order k -> free addresses
self.free_lists[max_order].add(0)
self.order_of = {} # allocated address -> order
def alloc(self, n):
k = max(0, (n - 1).bit_length()) # smallest k with 2**k >= n
j = k
while j <= self.max_order and not self.free_lists[j]:
j += 1 # smallest non-empty order that is big enough
if j > self.max_order:
return None
addr = self.free_lists[j].pop()
while j > k: # split, keep the low half, free the high half
j -= 1
self.free_lists[j].add(addr + (1 << j))
self.order_of[addr] = k
return addr
def free(self, addr):
k = self.order_of.pop(addr)
while k < self.max_order:
buddy = addr ^ (1 << k) # flip bit k of the address
if buddy not in self.free_lists[k]:
break # buddy is allocated or split: stop merging
self.free_lists[k].remove(buddy)
addr &= ~(1 << k) # the merged block starts at the lower buddy
k += 1
self.free_lists[k].add(addr)
The free lists are sets here so that “is my buddy free?” and “remove my buddy” are O(1). The Linux kernel gets the same effect with doubly linked lists plus a flag and the order stored in each page’s descriptor.
Trace on 64 units (BuddyAllocator(6)):
A = alloc(5)needs order 3 (8 units). Only order 6 is free, so 64 splits into 32 + 32, the low 32 into 16 + 16, the low 16 into 8 + 8. A = 0. Free: 8 at order 3, 16 at order 4, 32 at order 5.B = alloc(12)needs order 4 and takes the free 16. B = 16.C = alloc(3)needs order 2. Order 2 is empty, so the order-3 block at 8 splits into 4 + 4. C = 8, and 12 is free at order 2.free(A): the buddy of 0 at order 3 is 0 XOR 8 = 8. Block 8 is split (C lives in it), so there is no merge, and 0 goes on the order-3 list.free(C): buddy 8 XOR 4 = 12 is free, so merge into 8 at order 3. Buddy 8 XOR 8 = 0 is free at order 3, so merge into 0 at order 4. Buddy 0 XOR 16 = 16 is B, allocated, so stop. Free: 0 at order 4 and 32 at order 5.
Cost. Allocation and free are both O(m) worst case, one step per order, where m is log2 of the space size in units. The price is internal fragmentation: the three requests above total 20 units but occupy 28, 29% waste. Rounding up to a power of two wastes just under half the block in the worst case (a request of 2^k + 1 gets 2^(k+1)) and a quarter on average if request sizes are spread uniformly between consecutive powers of two. There is also external fragmentation the buddy rule cannot fix: two adjacent free blocks that are not buddies, such as free blocks at 12 and 16 in a 64-unit space, can never merge.
Kenneth Knowlton described the binary buddy system in “A Fast Storage Allocator” (CACM, 1965). The Linux kernel’s page allocator is a buddy allocator over physical page frames: it keeps free lists per order in each memory zone (/proc/buddyinfo prints how many free blocks of each order there are), finds a buddy by XORing the page frame number with 1 << order, and by default goes up to order 10, blocks of 1,024 pages, which is 4 MiB with 4 KiB pages.
Slab Allocation
Jeff Bonwick’s slab allocator (“The Slab Allocator: An Object-Caching Kernel Memory Allocator”, USENIX 1994, written for the SunOS 5.4 kernel) starts from an observation about kernels: they allocate a few kinds of fixed-size objects (inodes, process descriptors, network buffers) over and over, and initializing an object often costs more than allocating it.
- There is a cache per object type. A cache owns slabs: one or more contiguous pages, obtained from the page allocator, cut into equal-size objects, with a free list of the objects in each slab.
- Allocation pops an object from a partially full slab, and free pushes it back. Both are O(1). Objects have no headers, and there is no external fragmentation inside a slab: the only waste is the leftover tail of the slab that is too small for another object.
- Freed objects keep their constructed state (initialized locks, list heads), so the constructor runs once when the slab is created, not on every allocation. When memory runs short, completely free slabs go back to the page allocator.
- Slab colouring starts the objects in different slabs at slightly different offsets, so the same field of different objects doesn’t always land in the same CPU cache sets.
This is segregated storage with one class per type, layered on top of the buddy allocator. Linux had three implementations: SLAB (following Bonwick’s design), SLOB (for very small systems) and SLUB (Christoph Lameter, merged in 2007), which is simpler and keeps its per-slab metadata in the page descriptor. SLOB was removed in Linux 6.4 and SLAB in 6.8 (2024), so SLUB is now the only one. kmalloc serves general requests from caches named by size (kmalloc-32, kmalloc-64, kmalloc-96, …), which you can see in /proc/slabinfo. Memcached’s slab classes (Chapter 29) apply the same idea in user space.
Arenas and Bump Allocation
When many objects die at the same time, the allocator doesn’t need to track them individually at all. An arena (or region) is a large chunk with a pointer top to its first unused byte. Allocation rounds top up to the required alignment (Section 2.2), returns it, and advances it. There is no per-object free. Instead, reset frees everything at once by setting top back to the start.
class Arena:
"""Bump allocator over one chunk of `size` bytes; offsets stand in for addresses."""
def __init__(self, size):
self.size, self.top = size, 0
def alloc(self, n, align=8): # align must be a power of two
start = (self.top + align - 1) & -align # round up to a multiple of align
if start + n > self.size:
return None # a real arena would chain a new chunk
self.top = start + n
return start
def reset(self):
self.top = 0 # frees every object at once
Both operations are O(1) worst case and take a handful of instructions; a real arena that chains chunks frees them all on reset. Objects allocated together sit next to each other, which helps the cache. The stack of Section 2.2 is a bump allocator whose frees must come in LIFO order.
Arenas fit any workload with phases. Compilers put the syntax tree and intermediate code for a compilation unit in arenas (LLVM’s BumpPtrAllocator, GCC’s obstacks). Servers give each request a pool that is discarded when the response is sent (Apache’s APR pools, PostgreSQL’s memory contexts, which are reset at the end of a query). Game engines allocate per-frame scratch data from an arena that is reset every frame. The cost is that memory is not reused until reset, and one long-lived object in an arena keeps the whole arena alive; a pointer kept past a reset points into memory that the next phase will overwrite.
Testing the Simulations
An allocator bug usually shows up far from its cause, as one object silently overwriting another. The simulations above can be checked directly: after every operation of a long random sequence, assert that the blocks tile the space exactly, that no two live allocations overlap, that the allocator agrees with the test about which blocks are live, and that no two free blocks could still be merged. For the free list, a brute-force first fit also predicts every malloc result.
import random
def assert_disjoint(intervals):
intervals = sorted(intervals)
for (s1, e1), (s2, e2) in zip(intervals, intervals[1:]):
assert e1 <= s2, "two live allocations overlap"
def check_free_list(h, live):
"""live maps each pointer the test holds to the number of words it asked for."""
end, prev_free, found = 0, False, {}
for addr, size, used in h.blocks():
assert h.mem[addr] == h.mem[addr + size - 1], "header and footer disagree"
if used:
found[addr + 1] = size - 2 # payload capacity
else:
assert not prev_free, "two adjacent free blocks"
prev_free = not used
end = addr + size
assert end == len(h.mem), "blocks do not tile the heap"
assert found.keys() == live.keys()
assert all(found[p] >= n for p, n in live.items())
assert_disjoint((p, p + n) for p, n in live.items())
def first_fit_reference(h, n):
need = max(h.MIN_BLOCK, (n + 3) & ~1)
return next((a + 1 for a, s, u in h.blocks() if not u and s >= need), None)
def check_buddy(b, live):
blocks = sorted([(a, k) for k, s in enumerate(b.free_lists) for a in s]
+ list(b.order_of.items()))
pos = 0
for addr, k in blocks:
assert addr == pos and addr % (1 << k) == 0, "blocks do not tile the space"
pos += 1 << k
assert pos == 1 << b.max_order
for k, s in enumerate(b.free_lists[:-1]):
assert all(a ^ (1 << k) not in s for a in s), "free buddies not merged"
assert b.order_of.keys() == live.keys()
assert all(1 << b.order_of[a] >= n for a, n in live.items())
assert_disjoint((a, a + n) for a, n in live.items())
random.seed(1)
for trial in range(200):
h, b = FreeListHeap(256), BuddyAllocator(8)
live_h, live_b = {}, {}
for step in range(300):
if live_h and random.random() < 0.45:
p = random.choice(list(live_h))
h.free(p)
del live_h[p]
else:
n = random.randint(1, 40)
expect = first_fit_reference(h, n)
p = h.malloc(n)
assert p == expect
if p is not None:
live_h[p] = n
if live_b and random.random() < 0.45:
a = random.choice(list(live_b))
b.free(a)
del live_b[a]
else:
n = random.randint(1, 70)
a = b.alloc(n)
if a is not None:
live_b[a] = n
check_free_list(h, live_h)
check_buddy(b, live_b)
for p in list(live_h):
h.free(p)
for a in list(live_b):
b.free(a)
assert list(h.blocks()) == [(0, 256, 0)] # everything coalesced back
assert b.free_lists[8] == {0}
print("all invariants held")
2.6 Type Systems and Generic Programming
Modern languages provide mechanisms for writing data structures that work with arbitrary types.
Templates (C++)
template<typename T>
class Stack {
std::vector<T> data;
public:
void push(const T& item) { data.push_back(item); }
T pop() { T item = data.back(); data.pop_back(); return item; }
};
Templates are resolved at compile-time, producing zero runtime overhead for type checking.
Generics (Java, C#)
public class Stack<T> {
private ArrayList<T> data = new ArrayList<>();
public void push(T item) { data.add(item); }
public T pop() { return data.remove(data.size() - 1); }
}
Java generics use type erasure, they exist only at compile time, with runtime types being just Object.
Python Duck Typing
Python uses dynamic typing with duck typing (“if it walks like a duck…”):
class Stack:
def __init__(self):
self.data = []
def push(self, item):
self.data.append(item)
def pop(self):
return self.data.pop()
Any object with append() and pop() works with this Stack. This flexibility comes at the cost of runtime type checking.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
2.1 ★ Two’s complement by hand. Work in 8 bits.
(a) Write the bit patterns of −1, −5 and −128.
(b) A signed 8-bit variable holds 127 and you add 1. What value does it hold now, assuming the hardware simply wraps?
(c) An unsigned 8-bit variable holds 200 and you add 100. What does it hold?
(d) What is −(−128) in signed 8-bit arithmetic?
Solution
In two’s complement, −x is formed by inverting the bits of x and adding 1. Equivalently, an 8-bit pattern with value v as an unsigned number means v − 256 as a signed number whenever the top bit is set.
(a)
- −1: invert 00000001 → 11111110, add 1 → 11111111 (255 unsigned).
- −5: invert 00000101 → 11111010, add 1 → 11111011 (251 unsigned).
- −128: 10000000 (128 unsigned). It is its own pattern; there is no +128 in 8 bits.
(b) 127 is 01111111. Adding 1 gives 10000000, which reads as −128. This is the wraparound from Section 2.1. (In C, signed overflow is formally undefined behavior, so the compiler is allowed to assume it never happens. Wrapping is what the hardware does, not a promise the language makes.)
(c) 200 + 100 = 300 = 256 + 44. Unsigned arithmetic is defined to wrap modulo 256, so the result is 44.
(d) Invert 10000000 → 01111111, add 1 → 10000000, which is −128 again. The range −128..127 is asymmetric, so negating the minimum value overflows. This is why abs(INT_MIN) is a classic bug.
2.2 ★ Which byte comes first? The 32-bit value 0xDEADBEEF is stored at address 0x100.
(a) List the bytes at addresses 0x100, 0x101, 0x102, 0x103 on a little-endian machine and on a big-endian machine.
(b) A program reads the single byte at 0x100 to “check the low byte” of the value. On which machine does it get 0xEF?
Solution
(a)
| Address | Little-endian | Big-endian |
|---|---|---|
| 0x100 | EF | DE |
| 0x101 | BE | AD |
| 0x102 | AD | BE |
| 0x103 | DE | EF |
Little-endian puts the least significant byte (0xEF) at the lowest address; big-endian puts the most significant byte (0xDE) there.
(b) Only on the little-endian machine. On big-endian the same read returns 0xDE, the high byte. Code that reads part of a value through a narrower pointer (type punning, Section 2.2) silently changes meaning between the two. You can confirm the layouts in Python with struct.pack('<I', 0xDEADBEEF) (bytes ef be ad de) and struct.pack('>I', 0xDEADBEEF) (bytes de ad be ef).
2.3 ★★ Layout and reordering. Assume a typical 64-bit platform: char is 1 byte, int is 4 bytes aligned to 4, double is 8 bytes aligned to 8.
struct Record {
char a;
double b;
char c;
int d;
};
(a) Give the offset of each field and sizeof(struct Record).
(b) Reorder the fields to make the struct as small as possible. What is the new size?
(c) If you store 10 million records in an array, how much memory does the reordering save?
Hint
Each field goes at the next offset that is a multiple of its alignment, and the total size is rounded up to a multiple of the largest alignment in the struct, so that every element of an array of these structs is aligned too.
Solution
(a)
| Field | Size | Offset | Padding before it |
|---|---|---|---|
| a | 1 | 0 | 0 |
| b | 8 | 8 | 7 |
| c | 1 | 16 | 0 |
| d | 4 | 20 | 3 |
The fields end at byte 24, which is already a multiple of 8, so sizeof(struct Record) = 24. Only 14 of those bytes are data.
(b) Sort by decreasing alignment: double b; int d; char a; char c;. Offsets are 0, 8, 12, 13, the fields end at 14, and the size rounds up to the next multiple of 8: 16.
(c) 10,000,000 × (24 − 16) = 80,000,000 bytes, about 80 MB, saved by moving lines of source code around. The data didn’t change at all. (Checked with gcc on x86-64: 24 and 16. The same rule explains the struct Example in Section 2.2: char, int, char has size 12, because its largest alignment is 4.)
2.4 ★★ Pointer arithmetic trace. Assume int is 4 bytes and arr starts at address 0x2000.
int arr[6] = {10, 20, 30, 40, 50, 60};
int *p = arr + 1;
int *q = p + 3;
printf("%d %d %ld\n", *p, *(q - 1), (long)(q - p));
p += 2;
*p = *q + 1;
(a) What does the printf print?
(b) What address does q hold?
(c) What is the contents of arr at the end?
Solution
Pointer arithmetic counts in elements, not bytes (Section 2.3): p + k moves k × sizeof(int) = 4k bytes.
p = arr + 1points atarr[1](20).q = p + 3points atarr[4](50).
(a) *p is 20. *(q - 1) is arr[3], which is 40. q - p is measured in elements: 4 − 1 = 3. Output: 20 40 3.
(b) q is arr + 4, so 0x2000 + 4 × 4 = 0x2010.
(c) p += 2 moves p to arr[3]. Then *p = *q + 1 stores arr[4] + 1 = 51 into arr[3]. Final contents: {10, 20, 30, 51, 50, 60}.
2.5 ★★ Floats as keys. Run this in CPython:
d = {}
d[0.1 + 0.2] = "a"
print(0.3 in d)
nan = float("nan")
s = {nan}
print(nan in s, float("nan") in s)
print(sorted([3.0, float("nan"), 1.0, 2.0]))
It prints:
False
True False
[3.0, nan, 1.0, 2.0]
Explain each line, and state what rule a data structure that stores floating-point keys should follow.
Hint
A hash table finds a key by hashing it and then testing equality; a sort assumes that < defines a consistent order. Check what each of those assumptions does with 0.1 + 0.2 and with NaN.
Solution
Line 1: False. 0.1 + 0.2 evaluates to 0.30000000000000004, a different double from 0.3. The dict compares keys exactly, so the lookup misses. This is the “0.1 + 0.2 ≠ 0.3” problem from Section 2.1 turning into a missing record.
Line 2: True False. NaN is not equal to anything, including itself (nan == nan is False). Python’s containers check identity before equality (x is e or x == e), so the same NaN object is found. A different NaN object hashes and compares as a stranger, so it is never found. A set can even hold many “NaN” entries that all print the same.
Line 3: unsorted output. Every comparison against NaN (<, >, ==) is False, so < is no longer a consistent total order and the sort’s assumptions break. Here the sort ends up returning its input unchanged. The exact result depends on the algorithm and the input order, which is the real problem: the output is not sorted and nothing raises an error.
Rule: don’t use raw floats as exact keys for hashing or ordering unless every key comes from the same exact computation. Round or quantize to a fixed precision (or store integers, such as cents instead of dollars), and reject or canonicalize NaN before it enters a hash table, a sorted array or a search tree.
2.6 ★★★ Pack 100 million flags. You need to store 100 million records of the struct Flags from Section 2.4 (is_signed 1 bit, is_array 1 bit, size 6 bits).
(a) Compare the memory used by three layouts: a struct of three int fields, the bit-field struct (assume its container is one 4-byte unsigned int), and one byte per record in a byte array.
(b) Implement the byte layout in Python: pack(is_signed, is_array, size) returns an int in 0..255 with is_signed in bit 0, is_array in bit 1 and size in bits 2 to 7; unpack(b) returns the three fields; set_size(b, size) returns b with only the size field changed.
(c) Why can’t C give you a pointer to a bit field, and what must the compiler emit for f.size = 9?
Hint
For (b), a field of width w starting at bit k is (b >> k) & ((1 << w) - 1). To overwrite it, clear those bits with an inverted mask first.
Solution
(a)
| Layout | Bytes per record | 100 million records |
|---|---|---|
Three int fields | 12 | 1.2 GB |
| Bit-field struct | 4 | 400 MB |
| One byte each | 1 | 100 MB |
The three fields need only 8 bits, so the byte layout is optimal, and 12× smaller than the naive struct. The bit-field struct wastes 3 of its 4 bytes because its storage unit is the unsigned int the fields were declared with.
(b)
SIZE_SHIFT = 2
SIZE_MASK = 0x3F # 6 bits
def pack(is_signed, is_array, size):
assert is_signed in (0, 1) and is_array in (0, 1) and 0 <= size <= SIZE_MASK
return is_signed | (is_array << 1) | (size << SIZE_SHIFT)
def unpack(b):
return b & 1, (b >> 1) & 1, (b >> SIZE_SHIFT) & SIZE_MASK
def set_size(b, size):
assert 0 <= size <= SIZE_MASK
cleared = b & ~(SIZE_MASK << SIZE_SHIFT) & 0xFF # zero bits 2..7, keep bits 0..1
return cleared | (size << SIZE_SHIFT)
records = bytearray(100) # 100 million in the real thing: 100 MB
records[3] = pack(1, 0, 9)
assert records[3] == 0b00100101 # size 9 = 001001, then is_array 0, is_signed 1
assert unpack(records[3]) == (1, 0, 9)
records[3] = set_size(records[3], 42)
assert unpack(records[3]) == (1, 0, 42)
(c) Memory is byte-addressable (Section 2.2): an address names a byte, not a bit, so there is no address for “bits 2 to 7 of this byte”. For the same reason the hardware cannot write 6 bits in place. f.size = 9 becomes a read-modify-write: load the containing word, AND it with a mask that clears the field, OR in 9 << shift, store the word back. That is exactly set_size above. It costs a few extra instructions per access, and in concurrent code the read-modify-write also rewrites the neighbouring fields, so two threads updating different bit fields of the same word can lose each other’s writes.
2.7 ★★ Buddy allocation by hand. A buddy allocator manages 64 units, all free. It receives P = alloc(7), Q = alloc(20), R = alloc(2), S = alloc(9), in that order, and splits as in Section 2.5 (keep the low half, free the high half).
(a) Give the address and block size of P, Q, R and S, and list the free blocks afterwards.
(b) How many units are lost to internal fragmentation?
(c) Now free(R). Compute each buddy address the allocator checks, say which merges happen, and give the free blocks afterwards.
Solution
(a) P needs order 3 (8 units). The only free block is 0..63, which splits into 32 + 32, then 16 + 16, then 8 + 8: P = 0 (size 8), leaving free blocks 8 (order 3), 16 (order 4) and 32 (order 5). Q needs order 5 and takes Q = 32 (size 32). R needs order 1 (2 units); orders 1 and 2 are empty, so the order-3 block at 8 splits into 4 + 4 and the low 4 into 2 + 2: R = 8 (size 2), leaving 10 free at order 1 and 12 free at order 2. S needs order 4 and takes S = 16 (size 16). Free afterwards: 10 (2 units) and 12 (4 units).
(b) The requests total 7 + 20 + 2 + 9 = 38 units and the blocks total 8 + 32 + 2 + 16 = 58, so 20 units (34% of the allocated space) are internal fragmentation.
(c) R is at 8 with order 1. Buddy 8 XOR 2 = 10 is free at order 1: merge into 8 at order 2. Buddy 8 XOR 4 = 12 is free at order 2: merge into 8 at order 3. Buddy 8 XOR 8 = 0 is P, which is allocated: stop. Free afterwards: one block of 8 units at 8. Running the BuddyAllocator of Section 2.5 on the same calls gives the same addresses.
2.8 ★★ No policy wins everywhere. A heap has two free blocks: 20 words at address 0 and 15 words at address 100. Ignore headers and minimum sizes, so a request of n words takes exactly n words from the front of the chosen block.
(a) The requests are 15, then 20. Show that first fit fails and best fit succeeds.
(b) The requests are 10, 10, then 15. Show that best fit fails and first fit succeeds.
(c) What does this mean for choosing a policy?
Solution
(a) First fit gives the 15 to the first block that fits, the 20-word block at 0, leaving free blocks of 5 and 15. The request for 20 then fails. Best fit gives the 15 to the 15-word block, an exact fit, so the 20-word block is still whole and the second request succeeds.
(b) First fit: 10 from the 20-word block (free: 10 and 15), 10 more from it (free: 0 and 15), then 15 from the 15-word block. All succeed. Best fit: the first 10 goes to the smaller block that fits, the 15 (free: 20 and 5), the second 10 goes to the 20 (free: 10 and 5), and the 15 fails although 15 words are free in total.
(c) Each policy has inputs on which it fails while the other succeeds, so neither dominates, consistent with Robson’s lower bound that some sequence defeats every non-moving allocator. Policies are compared on traces of real programs, where best fit and address-ordered first fit both do well.
2.9 ★★ Arena alignment and reset. Use the Arena class from Section 2.5 with a 64-byte chunk.
(a) Allocate, in order, (size, alignment) = (1, 1), (8, 8), (2, 2), (4, 4), (16, 16), (1, 1). Give each offset, the final top, and the bytes lost to padding.
(b) Find an order for the same six requests that wastes no padding.
(c) A request handler keeps the offset of the 16-byte object in a global variable, the arena is reset, and the next request allocates (16, 16) and writes to it. What does the stale offset now refer to?
Hint
(top + align - 1) & -align rounds top up to the next multiple of align. This is the same rule as struct padding in Exercise 2.3.
Solution
(a)
| Request | top before | Offset | Padding |
|---|---|---|---|
| (1, 1) | 0 | 0 | 0 |
| (8, 8) | 1 | 8 | 7 |
| (2, 2) | 16 | 16 | 0 |
| (4, 4) | 18 | 20 | 2 |
| (16, 16) | 24 | 32 | 8 |
| (1, 1) | 48 | 48 | 0 |
Final top is 49. The objects total 32 bytes and 17 bytes are padding.
(b) Decreasing alignment: (16, 16), (8, 8), (4, 4), (2, 2), (1, 1), (1, 1) land at offsets 0, 16, 24, 28, 30, 31 and top ends at 32, no padding. Each object ends on a multiple of the next object’s alignment, the same reason sorting struct fields by decreasing alignment works.
(c) After reset, top is 0 and the next request lays out its objects from offset 0 again, so its (16, 16) object lands at offset 0. Offset 32 now belongs to whatever object of the new request covers byte 32, or to unallocated space if the request uses less. Reads through the stale offset see another request’s data and writes corrupt it, and nothing detects it. This is the arena form of use-after-free, and the reason an arena-allocated object must not outlive the phase its arena belongs to.
Where this connects
- Chapter 3: Arrays—The Foundation of Contiguous Storage. The first structure built directly on this memory model
- Chapter 16: External Memory and Cache-Oblivious Structures. What the memory hierarchy does to these assumptions
- Chapter 29: System Design as Data Structure Composition. Memcached’s slab classes, the size-class idea of Section 2.5 applied to a cache
Chapter 3: Arrays—The Foundation of Contiguous Storage
3.1 The Array Concept
An array is a contiguous block of memory containing elements of identical type. This simplicity is its power: given the address of the first element and an index, we can compute the address of any element in constant time.
The address formula: address(arr[i]) = base_address + i × element_size
This direct addressing is why arrays provide O(1) indexed access. No traversal, no searching, the location is known.
3.2 One-Dimensional Arrays
The simplest array form stores elements in a single row:
Memory Layout for int array[5] = {10, 20, 30, 40, 50}:
Address: 0x1000 0x1004 0x1008 0x100C 0x1010
┌───────┬───────┬───────┬───────┬───────┐
Index: │ 0 │ 1 │ 2 │ 3 │ 4 │
├───────┼───────┼───────┼───────┼───────┤
Value: │ 10 │ 20 │ 30 │ 40 │ 50 │
└───────┴───────┴───────┴───────┴───────┘
↑
base_address = 0x1000
The power of this layout is cache prefetching. When you access arr[0], the CPU typically loads not just that element but a cache line (often 64 bytes). This means arr[1], arr[2], arr[3]… are likely already in cache. Sequential array access is extremely fast.
3.3 Multi-Dimensional Arrays
Multi-dimensional arrays store data in grid or higher-dimensional tensor form.
Row-Major Order (C, C++, Python)
Elements stored row-by-row:
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Address formula: address(matrix[i][j]) = base + (i × 4 + j) × element_size
Column-Major Order (Fortran, MATLAB, R)
Elements stored column-by-column:
Address formula: address(matrix[i][j]) = base + (j × 3 + i) × element_size
Arrays of Arrays (Jagged Arrays)
Instead of contiguous memory, each row/column is a separate array:
vector<vector<int>> matrix(3);
for (int i = 0; i < 3; i++)
matrix[i] = vector<int>(4); // Each row independently allocated
This allows irregular shapes but loses cache locality and complicates memory management.
3.4 Dynamic Arrays
Fixed-size arrays require size at compile time. Dynamic arrays resize as needed.
The Resize Strategy
When capacity is exhausted:
- Allocate new, larger array (typically 2× current size)
- Copy all elements to new array
- Deallocate old array
Initial array (capacity 4):
┌────┬────┬────┬────┐
│ 1 │ 2 │ 3 │ 4 │
└────┴────┴────┴────┘
After inserting 5 (capacity exceeded):
┌────┬────┬────┬────┬────┬────┬────┬────┐
│ 1 │ 2 │ 3 │ 4 │ 5 │ │ │ │
└────┴────┴────┴────┴────┴────┴────┴────┘
(old array, now freed)
Amortized Analysis of Dynamic Arrays
With capacity doubling, starting from capacity 1:
- Insert 2: Copy 1 element
- Insert 3: Copy 2 elements
- Insert 5: Copy 4 elements
- Insert 9: Copy 8 elements
- …
- Insert 2^k + 1: Copy 2^k elements
Total copies for n insertions: 1 + 2 + 4 + … + 2^k where 2^k < n (the largest copy is smaller than n) < 2 × 2^k (geometric series) < 2n (since 2^k < n)
Amortized per insertion: O(2n/n) = O(1)
Implementation in Various Languages
C++ vector:
vector<int> v;
for (int i = 0; i < 1000; i++) {
v.push_back(i); // Amortized O(1)
}
Python list:
lst = []
for i in range(1000):
lst.append(i) # Amortized O(1)
Java ArrayList:
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
list.add(i); // Amortized O(1)
}
Go slices:
slice := make([]int, 0)
for i := 0; i < 1000; i++ {
slice = append(slice, i) // Amortized O(1)
}
3.5 Bit Arrays and Bitsets
When each element needs only one bit, bit arrays provide massive space savings.
Operations on Bit Arrays
// Set bit i to 1
bits[i / 8] |= (1 << (i % 8));
// Clear bit i to 0
bits[i / 8] &= ~(1 << (i % 8));
// Test bit i
if (bits[i / 8] & (1 << (i % 8))) { ... }
Popular Bitset Implementations
| Language | Class/Type |
|---|---|
| C++ | std::bitset<N>, dynamic_bitset |
| Java | BitSet |
| Python | int (arbitrary precision bit operations) |
| C# | BitArray, BitVector32 |
| Scala | BitSet (uses Longs internally) |
Applications of Bit Arrays
Bloom Filters: Multiple hash functions map elements to bits Sets: Efficient set operations (union, intersection, difference) Sieve of Eratosthenes: Finding primes Computer Graphics: Pixel masks, sprites Networking: IP packet filters, routing tables Database: Bitmap indexes
Compressed Bitmaps
A bitmap pays one bit for every value that could be in the set, whether or not it is. For n values from a universe of size U, that is U bits, against 32n bits for a sorted array of 32-bit integers, so the plain bitmap is smaller only when n > U/32: more than about 3% of the universe present. Bitmap indexes hit this constantly. A column of 10 million rows with 10,000 distinct values needs one 10-million-bit (1.25 MB) bitmap per value, 12.5 GB in all, to record what sorted arrays of row IDs store in 40 MB (10 million IDs, 4 bytes each). Yet bitmaps are worth keeping, because intersecting or uniting two of them is a loop of word-wide ANDs and ORs, 64 elements per instruction, and counting the result is a popcount per word. Compressed bitmaps try to keep that speed while paying space only where values actually are.
Run-length encoding. A sparse bitmap is mostly long runs of zero words (and clustered data also produces runs of one words). Word-aligned schemes replace each run with a single counter word and keep every other word as a literal copy, so logical operations still work a machine word at a time. WAH (Word-Aligned Hybrid) cuts the bitmap into 31-bit groups and stores each 32-bit word as either a literal, a flag bit plus 31 bitmap bits, or a fill, a flag bit, the fill value (0 or 1), and how many consecutive all-0 or all-1 groups it stands for. EWAH (Enhanced WAH) works on 64-bit words and uses a marker word meaning “k clean words of 0s (or of 1s), then m literal words”. To AND two such bitmaps, walk both in step and skip a whole run at once, so the cost is proportional to the compressed sizes rather than to U. The weakness is random access: there is no way to find bit i without decoding from the start, so a single membership test is O(compressed size). Git stores its reachability bitmaps (which objects each commit can reach, in pack order) in EWAH.
Roaring bitmaps keep fast random access by partitioning instead of run-length encoding. For a 32-bit value x, the high 16 bits (x >> 16) pick a chunk of 65,536 consecutive values, and the low 16 bits (x & 0xFFFF) are stored in that chunk’s container. The top level is a sorted array of the chunk numbers present, each paired with its container; empty chunks cost nothing. Each container chooses its own representation:
| Container | Contents | Size | Used when |
|---|---|---|---|
| Array | sorted 16-bit low halves | 2 bytes per value | at most 4096 values |
| Bitmap | 65,536 bits | 8 KB, fixed | more than 4096 values |
| Run | sorted (start, length − 1) pairs | 4 bytes per run | the values form few runs and this is smallest |
The threshold of 4096 is where the two basic containers cost the same: 4096 values × 2 bytes = 8192 bytes = 8 KB, which is exactly a 65,536-bit bitmap. Below it the array is smaller, above it the bitmap is, so the rule simply picks the smaller one, and a container is converted when an insertion or deletion crosses the line. As a result no container uses more than 16 bits per value: an array container uses exactly 16, and a bitmap container spreads 65,536 bits over more than 4096 values. Run containers were added later for data with long runs, such as sorted columns; libraries switch a container to runs when that is smallest, typically when asked to optimize (runOptimize() in the Java library).
Operations follow the two levels:
- Membership: binary search the top level for the high half (at most 65,536 keys, so about 16 probes), then binary search an array container, test one bit in a bitmap container, or binary search the run starts. Both levels are bounded, so this is effectively O(1), and unlike EWAH no decoding from the start is needed.
- Insertion into an array container shifts up to 4095 entries, and the 4097th value converts it to a bitmap. That bounded shift is the price of the sorted array.
- Intersection: merge the two sorted top-level arrays; only chunks present in both can contribute. Then intersect container pairs. Two bitmaps: 1024 64-bit ANDs, with popcount giving the result’s size, and the result becomes an array if it holds 4096 values or fewer. Array and bitmap: test each array value against the bitmap, O(size of the array), and the result is an array. Two arrays: merge them, or use galloping (exponential) search when one is much smaller. Real libraries have routines for run containers too, and use SIMD instructions for the bitmap and array cases.
The cost of an intersection therefore depends on the sizes of the containers involved, never on U, and the dense parts are processed a word at a time. Here is a model in Python, with a Python int standing in for the 65,536-bit bitmap:
from bisect import bisect_left
ARRAY_MAX = 4096 # 4096 values x 2 bytes = 8 KB = one 65,536-bit bitmap
def runs_of(lows):
"""Sorted distinct 16-bit values -> list of (start, length - 1) runs."""
runs = []
for v in lows:
if runs and runs[-1][0] + runs[-1][1] + 1 == v:
runs[-1] = (runs[-1][0], runs[-1][1] + 1)
else:
runs.append((v, 0))
return runs
def make_container(lows):
"""Pick the smallest representation for one chunk's sorted low halves."""
runs = runs_of(lows)
sizes = {"array": 2 * len(lows), "bitmap": 8192, "run": 4 * len(runs)}
if len(lows) > ARRAY_MAX:
del sizes["array"] # an array container never passes 8 KB
kind = min(sizes, key=sizes.get) # ties go to the first: array, then bitmap
if kind == "array":
return kind, list(lows)
if kind == "run":
return kind, runs
bits = 0
for v in lows:
bits |= 1 << v
return kind, bits
def values(container):
kind, data = container
if kind == "array":
return data
if kind == "run":
return [v for s, l in data for v in range(s, s + l + 1)]
return [v for v in range(65536) if data >> v & 1]
def contains(container, low):
kind, data = container
if kind == "array":
i = bisect_left(data, low)
return i < len(data) and data[i] == low
if kind == "bitmap":
return data >> low & 1 == 1
i = bisect_left(data, (low + 1, 0)) - 1 # last run starting at or before low
return i >= 0 and low <= data[i][0] + data[i][1]
class Roaring:
def __init__(self, xs=()):
chunks = {}
for x in sorted(set(xs)):
chunks.setdefault(x >> 16, []).append(x & 0xFFFF)
self.chunks = {hi: make_container(lows) for hi, lows in chunks.items()}
def __contains__(self, x):
c = self.chunks.get(x >> 16)
return c is not None and contains(c, x & 0xFFFF)
def __iter__(self):
for hi in sorted(self.chunks):
for low in values(self.chunks[hi]):
yield hi << 16 | low
def __and__(self, other):
out = Roaring()
for hi in self.chunks.keys() & other.chunks.keys():
(ka, a), (kb, b) = self.chunks[hi], other.chunks[hi]
if ka == kb == "bitmap":
lows = values(("bitmap", a & b)) # 1024 word ANDs in C
elif ka == "array":
lows = [v for v in a if contains((kb, b), v)]
elif kb == "array":
lows = [v for v in b if contains((ka, a), v)]
else: # runs: decode one side
lows = [v for v in values((ka, a)) if contains((kb, b), v)]
if lows:
out.chunks[hi] = make_container(lows)
return out
A set with three very different chunks:
s = Roaring([1, 2, 3, 1000, 50000] # chunk 0: 5 scattered values
+ list(range(65536 + 100, 65536 + 8100)) # chunk 1: 8000 in a row
+ list(range(2 * 65536, 3 * 65536, 3))) # chunk 2: every third value
assert {hi: c[0] for hi, c in s.chunks.items()} == {0: "array", 1: "run", 2: "bitmap"}
evens = Roaring(range(0, 3 * 65536, 2)) # three half-full bitmaps
both = s & evens
assert {hi: c[0] for hi, c in both.chunks.items()} == {0: "array", 1: "array", 2: "bitmap"}
assert set(both) == set(s) & set(range(0, 3 * 65536, 2))
assert 65636 in both and 65637 not in both
s holds 29,851 values. Chunk 0 becomes an array container of 10 bytes, chunk 1 a single run of 4 bytes (an array would be 16,000 bytes, a bitmap 8 KB), and chunk 2, with 21,846 values, a bitmap of 8 KB: about 8.2 KB in total. A sorted array of 32-bit integers would take 119,404 bytes, and a plain bitmap over all 32-bit values 512 MB. In the intersection with evens (all bitmaps), chunk 0 is array ∧ bitmap and keeps 3 values; chunk 1 is run ∧ bitmap and keeps 4000 values, few enough to fall back to an array container; chunk 2 is bitmap ∧ bitmap and keeps the 10,923 multiples of 6, so it stays a bitmap.
In its authors’ benchmarks Roaring is usually faster than WAH and EWAH, and often smaller, and it has become the default compressed bitmap. Apache Lucene’s RoaringDocIdSet (and so Elasticsearch and OpenSearch), the bitmap indexes of Apache Druid and Apache Pinot, ClickHouse’s bitmap functions, and Spark’s tracking of empty shuffle blocks all use it. Delta Lake and Apache Iceberg store deletion vectors, the positions of deleted rows in a data file, as 64-bit Roaring bitmaps, which apply the same high/low split one level up: the high 32 bits select an ordinary 32-bit Roaring bitmap.
3.6 Array Variants for Specific Purposes
Circular Buffers
A circular buffer wraps around at the end, ideal for queues:
rear front
│ │
▼ ▼
┌────┬────┬────┬────┬────┬────┬────┬────┐
│ 30 │ 40 │ 50 │ -- │ -- │ -- │ 10 │ 20 │
└────┴────┴────┴────┴────┴────┴────┴────┘
Queue order: 10, 20, 30, 40, 50. front is the oldest element;
rear is the next free slot, and the writes have wrapped past the end.
Elegant implementation using modulo arithmetic:
enqueue: rear = (rear + 1) % capacitydequeue: front = (front + 1) % capacity
Difference Arrays
Store the difference between consecutive elements:
Original: [10, 20, 25, 30, 35]
Difference: [10, 10, 5, 5, 5]
Range update [1,3) += 3:
Original becomes: [10, 23, 28, 30, 35]
Difference becomes: [10, 13, 5, 2, 5] (diff[1] += 3, diff[3] -= 3)
Range updates become O(1); original array reconstruction is O(n).
Sparse Arrays
For arrays with mostly default values:
struct SparseEntry {
int index;
value_type value;
};
vector<SparseEntry> sparse;
Only non-default values stored, with index for position.
3.7 Searching Sorted Arrays and Array Techniques
O(1) indexing makes a handful of techniques possible that come up constantly in practice. Binary search needs random access outright: it jumps to the middle of a range. Two pointers, sliding windows and prefix sums need only sequential passes: they keep a few indices into the array, move each one in a single direction, and replace an O(n²) or O(nk) loop with an O(n) one.
Binary Search Done Right
Binary search finds a value in a sorted array of n elements in O(log n) worst-case time by halving the range of candidate positions at every step. The idea fits in one sentence; the off-by-one details are where implementations go wrong.
The cleanest formulation does not ask “where is x?” but “where does x belong?”: the first index whose element is ≥ x. That question always has an answer in 0..n (n means “after everything”), so there is no special “not found” case, and one answer serves for membership, insertion point and counting. C++ calls it lower_bound.
The search keeps a half-open interval [lo, hi) of positions not yet classified, with this invariant:
- every element of
a[:lo]is < x, and - every element of
a[hi:]is ≥ x.
At the start lo = 0 and hi = n, both slices are empty, and the invariant holds trivially. Each step looks at one element inside [lo, hi) and moves a boundary to classify it, which keeps the invariant and strictly shrinks the interval. When lo = hi nothing is unclassified, and lo is the first index with an element ≥ x.
def lower_bound(a, x):
"""First index i with a[i] >= x, or len(a) if there is none."""
lo, hi = 0, len(a) # invariant: a[:lo] < x <= a[hi:]
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < x:
lo = mid + 1 # a[mid] and everything left of it are < x
else:
hi = mid # a[mid] and everything right of it are >= x
return lo
def upper_bound(a, x):
"""First index i with a[i] > x, or len(a) if there is none."""
lo, hi = 0, len(a) # invariant: a[:lo] <= x < a[hi:]
while lo < hi:
mid = (lo + hi) // 2
if a[mid] <= x:
lo = mid + 1
else:
hi = mid
return lo
Every detail follows from the invariant:
hi = mid, notmid - 1: a[mid] ≥ x, so it belongs to the “≥ x” region that starts at hi. Settinghi = mid - 1would claim a[mid − 1] ≥ x, which nobody checked.lo < hi, notlo <= hi: when lo = hi the interval is empty. With<=the loop would reada[mid]with lo = hi = n, one past the end.(lo + hi) // 2rounds down, so lo ≤ mid < hi.a[mid]is always in bounds, and both branches shrink the interval.
Trace on a = [3, 8, 8, 8, 15, 21, 30] with x = 8:
| lo | hi | mid | a[mid] | a[mid] < 8? | Action |
|---|---|---|---|---|---|
| 0 | 7 | 3 | 8 | no | hi = 3 |
| 0 | 3 | 1 | 8 | no | hi = 1 |
| 0 | 1 | 0 | 3 | yes | lo = 1 |
| 1 | 1 | return 1 |
upper_bound(a, 8) probes indices 3, 5, 4 and returns 4. So 8 occurs 4 − 1 = 3 times, at indices 1 to 3. For x = 10 both functions return 4: 10 is absent (a[4] is 15), and index 4 is where it would be inserted. Membership is i < len(a) and a[i] == x with i = lower_bound(a, x).
Cost. If the interval has s elements, both branches leave at most ⌊s/2⌋, so the loop runs at most ⌈log₂(n + 1)⌉ times: 20 iterations for a million elements, 30 for a billion. That is the worst case, and the search uses O(1) extra space.
The overflow in (lo + hi) // 2. Python integers do not overflow, so the line is correct in Python. In C, C++, Java or Go with 32-bit int indices, lo + hi exceeds 2³¹ − 1 once the array has more than about 2³⁰ (1.07 billion) elements and the search moves into the upper half. The sum wraps to a negative number and mid becomes a negative index: Java throws ArrayIndexOutOfBoundsException, and C has undefined behavior. The fix is mid = lo + (hi - lo) / 2, which never exceeds hi, or in Java (lo + hi) >>> 1, which reads the wrapped sum as unsigned. In 2006 Joshua Bloch reported that java.util.Arrays.binarySearch, which he had written, had carried this bug for about nine years, and that the same line appears in Jon Bentley’s Programming Pearls. It only showed up once arrays of a billion elements became practical.
Use the library. Python’s bisect module provides both functions: bisect_left(a, x) is lower_bound, bisect_right(a, x) (also exported as bisect) is upper_bound, and since Python 3.10 both accept key=. bisect.insort(a, x) finds the position in O(log n) but then shifts elements to insert, so it is O(n) overall. C++ has std::lower_bound, std::upper_bound and std::equal_range. Java’s Arrays.binarySearch returns some matching index, not necessarily the first, or −(insertion point) − 1 if x is absent.
Binary Search on the Answer
Look at what lower_bound actually tests: the predicate “a[i] ≥ x” is false for a prefix of the indices and true for the rest. Any predicate with that shape (monotone: once true, true for every larger input) can be searched the same way, with no array at all.
def first_true(lo, hi, pred):
"""Smallest v in [lo, hi) with pred(v) true, or hi if there is none.
pred must be monotone: once true, true for every larger v."""
while lo < hi:
mid = (lo + hi) // 2
if pred(mid):
hi = mid
else:
lo = mid + 1
return lo
lower_bound(a, x) is first_true(0, len(a), lambda i: a[i] >= x). The pattern pays off when an optimisation question (“what is the smallest c such that …?”) is hard to answer directly but easy to check for a given c.
Example: packages with weights [3, 2, 2, 4, 1, 4] must ship in order, each day’s load a contiguous run, within d = 3 days. What is the smallest daily capacity that works? Checking one capacity is a greedy pass (load each day until the next package does not fit; filling a day as far as possible never hurts later days). Feasibility is monotone, because a larger capacity never needs more days. The answer lies between max(weights), below which some package fits on no day, and sum(weights), which ships everything in one day.
def days_needed(weights, cap):
"""Days to ship weights, in order, if each day carries at most cap."""
days, load = 1, 0
for w in weights:
if load + w > cap:
days, load = days + 1, 0
load += w
return days
def min_capacity(weights, d):
return first_true(max(weights), sum(weights) + 1,
lambda cap: days_needed(weights, cap) <= d)
assert min_capacity([3, 2, 2, 4, 1, 4], 3) == 6
| lo | hi | mid | days_needed | ≤ 3? | Action |
|---|---|---|---|---|---|
| 4 | 17 | 10 | 2 | yes | hi = 10 |
| 4 | 10 | 7 | 3 | yes | hi = 7 |
| 4 | 7 | 5 | 4 | no | lo = 6 |
| 6 | 7 | 6 | 3 | yes | hi = 6 |
The answer is 6 (days [3, 2], [2, 4], [1, 4]). With n packages of total weight S, the search costs O(n log S) in the worst case, against O(nS) for trying every capacity. git bisect is the same algorithm over commit history, with the predicate “this commit has the bug”, which is monotone as long as the bug was introduced once and never fixed.
Two Pointers
Given a sorted array, find two elements that sum to a target. Trying all pairs is O(n²). Instead, start one index at each end and move them toward each other:
def pair_with_sum(a, target):
"""Indices i < j with a[i] + a[j] == target in sorted a, or None."""
i, j = 0, len(a) - 1
while i < j:
s = a[i] + a[j]
if s == target:
return i, j
if s < target:
i += 1 # a[i] + (largest remaining) is too small: drop a[i]
else:
j -= 1 # (smallest remaining) + a[j] is too big: drop a[j]
return None
The invariant is that any solution uses two indices in [i, j]. If a[i] + a[j] < target, then a[i] plus any remaining element is at most a[i] + a[j], still too small, so a[i] is in no solution and can be dropped. The other case is symmetric. Each iteration drops one index, so there are at most n − 1 iterations: O(n) worst case and O(1) extra space. Binary searching for target − a[i] for each i is O(n log n); a hash set is O(n) expected and does not need sorted input, but costs O(n) extra space.
Trace on a = [1, 3, 4, 6, 9, 11] with target 13:
| i | j | a[i] + a[j] | Action |
|---|---|---|---|
| 0 | 5 | 1 + 11 = 12 | too small, i += 1 |
| 1 | 5 | 3 + 11 = 14 | too big, j −= 1 |
| 1 | 4 | 3 + 9 = 12 | too small, i += 1 |
| 2 | 4 | 4 + 9 = 13 | return (2, 4) |
The same move-the-index-that-cannot-help idea gives in-place duplicate removal from a sorted array (one read index, one write index), three-sum in O(n²) (fix one element, two-pointer the rest), and the merge step of merge sort, where one index walks each sorted input.
Sliding Window
A window is a contiguous run a[lo:hi] that moves left to right. Instead of recomputing a property of each window from scratch, update it as one element enters on the right and one leaves on the left.
Fixed size. The largest sum of k consecutive elements costs O(nk) by summing every window, and O(n) by sliding:
def max_window_sum(a, k):
"""Largest sum of k consecutive elements (1 <= k <= len(a))."""
s = sum(a[:k])
best = s
for i in range(k, len(a)):
s += a[i] - a[i - k] # a[i] enters, a[i - k] leaves
best = max(best, s)
return best
For [4, 2, 12, 3, 8, 1, 7] and k = 3 the window sums are 18, 17, 23, 12, 16, so the answer is 23. Moving averages over a stream and rolling hashes (Rabin-Karp string search) are fixed windows.
Variable size. The shortest run whose sum is at least a target: grow the window on the right; whenever it is valid, record it and shrink it from the left for as long as it stays valid.
def shortest_at_least(a, target):
"""Length of the shortest run a[lo:hi+1] with sum >= target, or 0 if none.
Requires every a[i] >= 0."""
best = len(a) + 1
s = lo = 0
for hi, x in enumerate(a):
s += x # grow on the right
while s >= target: # shrink from the left while still valid
best = min(best, hi - lo + 1)
s -= a[lo]
lo += 1
return best if best <= len(a) else 0
Trace on a = [2, 3, 1, 2, 4, 3] with target 7:
| hi | a[hi] | Sum after adding | Valid windows recorded while shrinking |
|---|---|---|---|
| 0 | 2 | 2 | none |
| 1 | 3 | 5 | none |
| 2 | 1 | 6 | none |
| 3 | 2 | 8 | [2, 3, 1, 2] (length 4) |
| 4 | 4 | 10 | [3, 1, 2, 4] (4), [1, 2, 4] (3) |
| 5 | 3 | 9 | [2, 4, 3] (3), [4, 3] (2) |
The answer is 2. The inner while can run many times in one iteration, but lo only moves forward, so over the whole run each element enters the window once and leaves at most once: O(n) total in the worst case, amortized O(1) per element. The precondition matters. With non-negative elements, growing a window never lowers its sum and shrinking never raises it. So the first valid window that starts at lo is the shortest one that starts there, and lo can be dropped as soon as it is recorded; and once shrinking makes the window invalid, every window ending at hi with a later start is invalid too, so only growing on the right can help. With negative elements that monotonicity fails and so does the method; Exercise 3.8 handles that case with prefix sums.
Prefix Sums
Precompute p[i] = a[0] + … + a[i − 1], with p[0] = 0. Then the sum of any range a[l:r] is p[r] − p[l]: O(n) to build, O(1) per query, against O(r − l) to add the range up each time.
def prefix_sums(a):
"""p[i] = a[0] + ... + a[i-1], so p has len(a) + 1 entries and p[0] = 0."""
p = [0] * (len(a) + 1)
for i, x in enumerate(a):
p[i + 1] = p[i] + x
return p
def range_sum(p, l, r):
"""Sum of a[l:r] in O(1)."""
return p[r] - p[l]
For a = [10, 20, 25, 30, 35], p = [0, 10, 30, 55, 85, 120], and the sum of a[1:4] is p[4] − p[1] = 85 − 10 = 75 = 20 + 25 + 30. In the standard library this is itertools.accumulate(a, initial=0); NumPy has cumsum.
Prefix sums and the difference arrays of Section 3.6 are inverse operations, the discrete versions of integration and differentiation. The difference array of [10, 20, 25, 30, 35] is [10, 10, 5, 5, 5], and its prefix sums give the original back (that is rebuild in Exercise 3.4). In the other direction, p[i + 1] − p[i] = a[i]. The two make opposite trades:
| Range update | Range query | Use when | |
|---|---|---|---|
| Prefix sums | O(n): every later p[i] changes | O(1) | The array is fixed and queried many times |
| Difference array | O(1) | O(n): rebuild first | Many updates, then one read |
When updates and queries interleave, neither works well; a Fenwick tree or segment tree (Chapter 23) does both in O(log n) worst case.
Two dimensions. Let P[i][j] be the sum of the rectangle of rows 0..i − 1 and columns 0..j − 1. Building a cell adds the element to the rectangles above and to the left, and subtracts their overlap, which was counted twice. A query uses the same inclusion-exclusion in reverse.
def prefix_sums_2d(m):
rows, cols = len(m), len(m[0])
p = [[0] * (cols + 1) for _ in range(rows + 1)]
for i in range(rows):
for j in range(cols):
p[i + 1][j + 1] = m[i][j] + p[i][j + 1] + p[i + 1][j] - p[i][j]
return p
def rect_sum(p, r1, c1, r2, c2):
"""Sum of m[i][j] for r1 <= i < r2 and c1 <= j < c2, in O(1)."""
return p[r2][c2] - p[r1][c2] - p[r2][c1] + p[r1][c1]
For the 3 × 4 matrix of Section 3.3 (values 1 to 12), the table P has rows [0, 0, 0, 0, 0], [0, 1, 3, 6, 10], [0, 6, 14, 24, 36], [0, 15, 33, 54, 78]. The sum of rows 1 to 2 and columns 1 to 2 is P[3][3] − P[1][3] − P[3][1] + P[1][1] = 54 − 6 − 15 + 1 = 34 = 6 + 7 + 10 + 11. Building is O(rows × cols) and every rectangle query is O(1), whatever its size. Graphics calls this a summed-area table and uses it to blur an image with a box filter of any radius at constant cost per pixel; the Viola-Jones face detector calls it an integral image.
3.8 Performance Characteristics
| Operation | Static Array | Dynamic Array | Bit Array |
|---|---|---|---|
| Random Access | O(1) | O(1) | O(1) |
| Sequential Scan | O(n) | O(n) | O(n/word_size) |
| Insert at End | O(n) | O(1)* | O(1) |
| Insert at Position | O(n) | O(n) | O(n/word_size) |
| Delete at Position | O(n) | O(n) | O(n/word_size) |
| Memory | Fixed | 1× to 2× | 1/bit_size |
| Cache Efficiency | Excellent | Excellent | Good |
*Amortized; the append that triggers a resize is O(n) (Section 3.4).
Why Arrays Win in Practice
The table gives a scan O(n), the same as for a linked list in Chapter 4, but the hardware does not treat the two alike. Memory moves between DRAM and the caches in 64-byte lines, so one line holds 16 four-byte ints, and scanning a million-int array (4 MB) misses at most 62,500 times, not a million. Better still, after a few sequential misses the hardware prefetcher starts requesting the following lines before the loop asks for them, so the scan runs at memory bandwidth instead of paying the DRAM latency (on the order of 100 ns) for each line. A linked list gets neither benefit: its nodes can be anywhere, and the address of the next node is unknown until the current node has arrived, so each miss waits for the previous one. Chapter 16 puts the gap at 10× or more for the same O(n) loop.
Binary search (Section 3.7) sits in between. On a large array each early probe lands on a different cache line, and the prefetcher cannot guess the next one; only the last four or so probes, once the range has narrowed to 16 ints, fall inside a single line. This is why a linear scan often matches binary search on arrays of a few dozen elements, and why search structures for large data pack many keys into each cache line or disk block (Chapter 10).
3.9 Real-World Applications
Database Systems: Column stores use columnar arrays for analytical queries Scientific Computing: Dense matrix operations (BLAS, LAPACK) Image Processing: Pixel arrays with convolution operations Signal Processing: Sample buffers with circular buffer patterns Compilers: Symbol tables using open addressing Networking: Packet buffers, ring buffers in device drivers
3.10 Historical Context
The array concept predates electronic computers. In mathematics, matrices and vectors have been studied for centuries. The FORTRAN language (1957) introduced multi-dimensional arrays as a first-class concept, heavily influencing scientific computing.
The dynamic array (vector) concept emerged with languages supporting heap allocation. The Ada language (1983) provided array slicing; modern languages provide richer array operations.
Binary search was first described by John Mauchly in the 1946 Moore School Lectures, but according to Knuth (The Art of Computer Programming, Vol. 3) the published versions worked only for some array lengths until D. H. Lehmer’s in 1960. Getting it right stayed hard: Joshua Bloch’s 2006 report of the (low + high) / 2 overflow covered both the JDK and Programming Pearls. Two-dimensional prefix sums entered graphics as Franklin Crow’s summed-area tables (1984) and computer vision as the integral images of Paul Viola and Michael Jones’s face detector (2001).
Compressed bitmaps grew out of bitmap indexes. Gennady Antoshenkov’s Byte-aligned Bitmap Code (1995) was used in Oracle; Kesheng Wu, Ekow Otoo and Arie Shoshani’s WAH (journal version 2006) aligned the runs to machine words; Daniel Lemire, Owen Kaser and Kamel Aouiche’s EWAH (2010) moved to 64-bit words. Roaring was introduced by Samy Chambi, Daniel Lemire, Owen Kaser and Robert Godin in 2016, and run containers were added in a follow-up paper by Lemire, Gregory Ssi-Yan-Kai and Kaser the same year.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
3.1 ★ Row-major or column-major? The 3 × 4 matrix from Section 3.3 (values 1 to 12) starts at address 0x1000, and each element is 4 bytes.
(a) What is the address of matrix[2][1] in row-major order? In column-major order?
(b) Which value is stored at address 0x1018 under each layout?
Solution
(a) Row-major: base + (i × 4 + j) × 4 = 0x1000 + (2 × 4 + 1) × 4 = 0x1000 + 36 = 0x1024. Column-major: base + (j × 3 + i) × 4 = 0x1000 + (1 × 3 + 2) × 4 = 0x1000 + 20 = 0x1014.
(b) 0x1018 − 0x1000 = 24 bytes = element offset 6.
- Row-major: offset 6 = i × 4 + j, so i = 1, j = 2:
matrix[1][2]= 7. - Column-major: offset 6 = j × 3 + i, so j = 2, i = 0:
matrix[0][2]= 3.
Same bytes, different meaning: the layout is a convention between the writer and the reader of the memory, which is why passing a NumPy (row-major) array to a Fortran (column-major) routine needs either a transpose or a flag.
3.2 ★ Bit array trace. bits is a 2-byte array, initially all zero. Using the operations from Section 3.5, apply in order: set bit 3, set bit 10, set bit 15, clear bit 3. Give both bytes in hex after each step, and the result of testing bit 10 and bit 11 at the end.
Solution
Bit i lives in byte i / 8 at position i % 8.
| Step | Byte, position | bits[0] | bits[1] |
|---|---|---|---|
| start | 0x00 | 0x00 | |
| set 3 | byte 0, bit 3 (0x08) | 0x08 | 0x00 |
| set 10 | byte 1, bit 2 (0x04) | 0x08 | 0x04 |
| set 15 | byte 1, bit 7 (0x80) | 0x08 | 0x84 |
| clear 3 | byte 0, AND with ~0x08 | 0x00 | 0x84 |
Test bit 10: 0x84 & 0x04 = 0x04, nonzero, so set. Test bit 11: 0x84 & 0x08 = 0, so clear.
3.3 ★★ Other growth factors. Section 3.4 doubles the capacity. Many implementations grow by a factor of 1.5 instead (and CPython’s list grows by about 1.125).
(a) For a growth factor r > 1, show that the total number of element copies over n appends is less than n · r / (r − 1). Evaluate the bound for r = 2 and r = 1.5.
(b) What do you give up by choosing a smaller r?
(c) Suppose instead the array grows by a fixed amount k (capacity k, 2k, 3k, …). What is the total copy cost of n appends?
Hint
List the capacities at which copies happen, from the last one backwards. Each is at most 1/r of the next.
Solution
(a) A copy happens when the array is full, and copies every element currently stored, i.e. the current capacity. Let the capacities at which copies happened be c₁ < c₂ < … < cₜ. The last one is less than n (an append found the array full with fewer than n elements). Each capacity is at least r times the previous one, so going backwards: cₜ < n, cₜ₋₁ ≤ cₜ / r < n / r, cₜ₋₂ < n / r², and so on. Therefore
total copies < n (1 + 1/r + 1/r² + …) = n · 1 / (1 − 1/r) = n · r / (r − 1).
- r = 2: fewer than 2n copies, as in Section 3.4.
- r = 1.5: fewer than 3n copies.
A simulation starting from capacity 1 gets close to both bounds (about 2.0n and 3.0n at worst) without exceeding them. Either way, appends are amortized O(1).
(b) Smaller r means more frequent resizes and more total copying (the constant r / (r − 1) grows as r → 1), in exchange for less wasted space: right after a resize the array is only 1/r full, so doubling can leave up to half the allocation empty while 1.5 leaves at most a third empty. Factor 1.5 has a second, allocator-level advantage: the blocks freed by earlier resizes eventually add up to more than the next request, so an allocator that merges adjacent free blocks can reuse them. With factor 2 that never happens, because 1 + 2 + … + 2^(k−1) = 2^k − 1 is always smaller than the next request of 2^(k+1).
(c) Copies happen at sizes k, 2k, 3k, …, up to about n, so the total is k (1 + 2 + … + n/k) ≈ k · (n/k)² / 2 = n² / (2k). That is Θ(n²) total and Θ(n / k) amortized per append. For n = 10,000 and k = 100, it is 495,000 copies, against fewer than 20,000 with doubling. Additive growth only looks cheaper; any constant k loses to any constant factor r > 1.
3.4 ★★ Difference array updates. Implement range_add(diff, l, r, v), which adds v to every element of the original array in the half-open range [l, r) by editing the difference array, and rebuild(diff), which recovers the original array. Then apply these three updates in order to the example in Section 3.6 (original [10, 20, 25, 30, 35]): [1, 3) += 3, then [0, 5) += 1, then [2, 5) −= 2. Show the difference array after each update.
Hint
Adding v to a range raises the step into position l by v and lowers the step out of position r − 1 by v. If r is the length of the array, there is no step out.
Solution
def range_add(diff, l, r, v):
"""Add v to original[l:r] in O(1)."""
diff[l] += v
if r < len(diff):
diff[r] -= v
def rebuild(diff):
"""Prefix sums of diff give back the original array: O(n)."""
out, running = [], 0
for d in diff:
running += d
out.append(running)
return out
diff = [10, 10, 5, 5, 5] # difference array of [10, 20, 25, 30, 35]
range_add(diff, 1, 3, 3)
assert diff == [10, 13, 5, 2, 5]
range_add(diff, 0, 5, 1)
assert diff == [11, 13, 5, 2, 5]
range_add(diff, 2, 5, -2)
assert diff == [11, 13, 3, 2, 5]
assert rebuild(diff) == [11, 24, 27, 29, 34]
| After | Difference array | Original (rebuilt) |
|---|---|---|
| start | [10, 10, 5, 5, 5] | [10, 20, 25, 30, 35] |
| [1, 3) += 3 | [10, 13, 5, 2, 5] | [10, 23, 28, 30, 35] |
| [0, 5) += 1 | [11, 13, 5, 2, 5] | [11, 24, 29, 31, 36] |
| [2, 5) −= 2 | [11, 13, 3, 2, 5] | [11, 24, 27, 29, 34] |
The second and third updates run to the end of the array, so they only touch diff[l]. Check the last row by hand: 34 = 35 + 1 − 2, and 24 = 20 + 3 + 1.
3.5 ★★ Find the bug. This function is supposed to return 1 if bit i is set and 0 otherwise. It compiles (with a warning that is easy to ignore) and passes a test that only checks bit 0.
int is_set(const unsigned char *bits, int i) {
return bits[i / 8] & 1 << i % 8 != 0;
}
What does it actually compute? Give inputs where it is wrong, and fix it.
Hint
In C, != binds more tightly than &.
Solution
C precedence, from tightest: % then << then != then &. So the expression parses as
bits[i / 8] & ((1 << (i % 8)) != 0)
(1 << (i % 8)) != 0 is always 1, so the function returns bits[i / 8] & 1: bit 0 of whichever byte holds bit i, no matter which bit was asked for.
With bits = {0x01, 0x04} (bits 0 and 10 set), is_set(bits, 3) returns 1 (wrong, bit 3 is clear) and is_set(bits, 10) returns 0 (wrong, bit 10 is set). Any test that only probes bits 0, 8, 16, … passes.
Fix with explicit parentheses, as in Section 3.5:
int is_set(const unsigned char *bits, int i) {
return (bits[i / 8] & (1 << (i % 8))) != 0;
}
The warning gcc -Wall prints here (“suggest parentheses around comparison in operand of ‘&’”) points at exactly this line. Bit manipulation is where operator precedence bites most often, because &, | and ^ sit below the comparison operators, against most people’s intuition.
3.6 ★★★ Appends with no slow ones. Doubling gives amortized O(1) appends, but one append in a while copies the whole array. A real-time system (an audio callback, a game frame) cannot afford that single O(n) append. Design a dynamic array whose append does O(1) work in the worst case, while indexing stays O(1). Assume allocating an uninitialized array takes O(1) time.
Hint
When the array of capacity m fills, allocate the 2m array but don’t copy yet. Move a couple of old elements on each subsequent append, and make sure the move finishes before the new array fills.
Solution
Keep two arrays during a migration: old (capacity m, full) and new (capacity 2m). New elements go straight into new at their final index. Each append also copies 2 elements from old to new. Copying m elements at 2 per append takes m/2 appends, and by then new holds m + m/2 < 2m elements, so the migration always finishes before new is full and the next migration is needed. Indexing checks which array currently holds position i.
class IncrementalArray:
"""Dynamic array whose append does O(1) work in the worst case."""
def __init__(self):
self.new = [None] * 2 # array that receives appends
self.old = None # array being drained, or None
self.moved = 0 # old[0:moved] already copied into new
self.n = 0
def append(self, x):
if self.old is None and self.n == len(self.new):
# Start a migration. (Python's [None] * k is not O(1);
# in C this would be an uninitialized malloc.)
self.old, self.new, self.moved = self.new, [None] * (2 * self.n), 0
self.new[self.n] = x
self.n += 1
if self.old is not None:
for _ in range(2): # copy two old elements per append
if self.moved < len(self.old):
self.new[self.moved] = self.old[self.moved]
self.moved += 1
if self.moved == len(self.old):
self.old = None # migration finished
def __getitem__(self, i):
if not 0 <= i < self.n:
raise IndexError(i)
if self.old is not None and self.moved <= i < len(self.old):
return self.old[i] # not copied yet
return self.new[i]
def __len__(self):
return self.n
a = IncrementalArray()
for k in range(2000):
a.append(k)
assert a.old is None or a.n < len(a.new) # migration ends before new fills
assert [a[i] for i in range(len(a))] == list(range(2000))
The tradeoff: every append now does a little more work (up to 3 writes instead of 1), indexing has an extra branch, and during a migration both arrays are live, so peak memory is 3m instead of 2m. Total work is the same Θ(n) as plain doubling; the technique only moves the cost so that no single operation pays for it. This is called deamortization, and the same move-a-little-each-time idea shows up in incremental hash table resizing (Redis does it) and in incremental garbage collectors.
3.7 ★ Find the bug. This binary search returns the index of x in the sorted list a, or −1. It passes search([1, 3, 5], 3) and search([1, 3, 5], 0). Find an input where it fails, explain the failure using the invariant from Section 3.7, and fix it.
def search(a, x):
lo, hi = 0, len(a)
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == x:
return mid
if a[mid] < x:
lo = mid + 1
else:
hi = mid - 1
return -1
Hint
Decide what hi means: the last candidate index, or one past it. Then check whether each line agrees.
Solution
The function mixes two conventions. hi = len(a) sets up a half-open interval [lo, hi), where hi is one past the last candidate. But lo <= hi and hi = mid - 1 belong to a closed interval [lo, hi], where hi itself is a candidate. Under the closed reading the initial interval includes index len(a), which does not exist.
search([1, 3, 5], 7): lo = 0, hi = 3, mid = 1, 3 < 7 so lo = 2; mid = 2, 5 < 7 so lo = 3; now lo = hi = 3, the loop runs again, and a[3] raises IndexError. search([], 1) fails the same way on its first probe. Any x larger than every element triggers it; the passing tests never searched past the end.
Either convention works if used consistently. Closed: start with hi = len(a) - 1 and keep the rest. Half-open, matching lower_bound:
def search(a, x):
lo, hi = 0, len(a) # x, if present, is in a[lo:hi]
while lo < hi:
mid = (lo + hi) // 2
if a[mid] == x:
return mid
if a[mid] < x:
lo = mid + 1
else:
hi = mid # a[mid] > x: exclude mid, keep [lo, mid)
return -1
assert search([1, 3, 5], 7) == -1 and search([], 1) == -1
assert [search([1, 3, 5], x) for x in range(7)] == [-1, 0, -1, 1, -1, 2, -1]
Note that with duplicates this returns some index of x, like Java’s Arrays.binarySearch. Use lower_bound when you need the first.
3.8 ★★ Subarray sums with negative numbers. Count the contiguous runs a[l:r] (with l < r) whose sum is exactly k. Explain why the variable-size sliding window of Section 3.7 cannot do this when a has negative elements, then give an O(n) expected-time algorithm, and run it on a = [3, 4, -7, 1, 3, 3, 1, -4] with k = 7.
Hint
The sum of a[l:r] is p[r] − p[l]. For each r, how many earlier l have p[l] = p[r] − k?
Solution
The window method shrinks from the left as soon as the sum is large enough, and grows on the right while it is too small. That is only correct if adding an element never lowers the sum and removing one never raises it. Here [3, 4] already sums to 7, yet [3, 4, -7, 1, 3, 3] also sums to 7: extending a window past a negative element can bring the sum back down and up again, so no decision about lo or hi is final.
Prefix sums turn the question into counting pairs: a[l:r] sums to k exactly when p[l] = p[r] − k. Scan r from left to right, keeping a hash map from each prefix sum seen so far to how many times it occurred:
from collections import Counter
def count_subarrays_with_sum(a, k):
seen = Counter({0: 1}) # prefix sums so far; p[0] = 0
p = count = 0
for x in a:
p += x
count += seen[p - k] # each earlier p[l] == p - k is one run a[l:r]
seen[p] += 1
return count
assert count_subarrays_with_sum([3, 4, -7, 1, 3, 3, 1, -4], 7) == 4
The prefix sums are p = [0, 3, 7, 0, 1, 4, 7, 8, 4]. Matches: p[2] = 7 pairs with p[0] = 0 ([3, 4]); p[6] = 7 pairs with p[0] and with p[3] = 0 ([3, 4, -7, 1, 3, 3] and [1, 3, 3]); p[7] = 8 pairs with p[4] = 1 ([3, 3, 1]). That is 4 runs, which a brute-force check over all 36 runs confirms. Each step is one hash lookup and one update, so the whole scan is O(n) expected time and O(n) extra space, against O(n²) for checking every run with prefix sums and O(n³) without them.
3.9 ★★ Integer square root. Using first_true from Section 3.7, write isqrt(n), the largest integer v with v² ≤ n, for any n ≥ 0. Trace it for n = 40. How many iterations does it take for n = 10¹⁸, and what changes if you port it to C with 64-bit integers?
Solution
“v² > n” is monotone in v, so the answer is one less than the first v for which it is true. That first v is at most n + 1 (for n ≥ 2 it is at most n, since n² > n; for n = 0 and n = 1 it is 1 and 2), so searching [0, n + 1) is safe: if nothing in range is true, first_true returns hi = n + 1, which is then the right first v.
import math
def first_true(lo, hi, pred):
while lo < hi:
mid = (lo + hi) // 2
if pred(mid):
hi = mid
else:
lo = mid + 1
return lo
def isqrt(n):
"""Largest v with v * v <= n, for n >= 0."""
return first_true(0, n + 1, lambda v: v * v > n) - 1
assert [isqrt(n) for n in range(10)] == [0, 1, 1, 1, 2, 2, 2, 2, 2, 3]
assert all(isqrt(n) == math.isqrt(n) for n in range(10_000))
assert isqrt(10**18) == 10**9
Trace for n = 40:
| lo | hi | mid | mid² | > 40? |
|---|---|---|---|---|
| 0 | 41 | 20 | 400 | yes, hi = 20 |
| 0 | 20 | 10 | 100 | yes, hi = 10 |
| 0 | 10 | 5 | 25 | no, lo = 6 |
| 6 | 10 | 8 | 64 | yes, hi = 8 |
| 6 | 8 | 7 | 49 | yes, hi = 7 |
| 6 | 7 | 6 | 36 | no, lo = 7 |
first_true returns 7, so isqrt(40) = 6.
For n = 10¹⁸ the interval starts with 10¹⁸ + 1 values, so at most ⌈log₂(10¹⁸ + 2)⌉ = 60 iterations. Starting from hi = 2³², which is enough for any 64-bit n, would cut that to at most 33.
In C, two lines overflow. mid * mid exceeds 2⁶³ − 1 once mid > about 3.04 × 10⁹, which happens on the first probe for n = 10¹⁸ (mid = 5 × 10¹⁷); test mid > n / mid instead, which is equivalent for integer division and cannot overflow (mid is 0 only when n = 0, so handle that case first). And lo + hi can overflow for n near 2⁶³, so use lo + (hi - lo) / 2, as in Section 3.7. Python avoids both because its integers are unbounded, at the cost of arbitrary-precision arithmetic on every step.
3.10 ★ Choosing containers. Using the Roaring rules of Section 3.5, give the chunks, the container type of each, and the total container size for each set below. Compare with a sorted array of 32-bit integers.
(a) The 5000 even numbers 0, 2, 4, …, 9998.
(b) The 100,000 consecutive values 0, 1, …, 99,999.
(c) The 1000 values 0, 65,536, 2 × 65,536, …, 999 × 65,536.
Solution
(a) All values are below 65,536, so there is one chunk (high half 0) with 5000 values. That is more than 4096, so an array container is ruled out (it would need 10,000 bytes, more than a bitmap). No two values are consecutive, so a run container needs 5000 runs, 20,000 bytes. The bitmap container wins at 8192 bytes, about 13 bits per value, against 20,000 bytes for the sorted array.
(b) Two chunks. Chunk 0 is full (0 to 65,535): one run, 4 bytes, against 8192 for a bitmap. Chunk 1 holds 65,536 to 99,999, low halves 0 to 34,463: again one run, 4 bytes. Total 8 bytes of containers, against 400,000 bytes for the array. A plain bitmap or an array container could not get close; this is what run containers are for.
(c) 1000 chunks, each holding a single value with low half 0, so 1000 array containers of 2 bytes each. The containers total only 2000 bytes, but every chunk also needs its 2-byte key in the top level, plus a pointer (in memory) or an offset and a cardinality (on disk). That is already 4 bytes per value (2 for the key, 2 for the container) before counting any pointer, offset or cardinality, as much as the 4000-byte sorted array, so here Roaring loses. Its 16-bits-per-value guarantee holds inside containers; when every chunk holds one value, the top level dominates.
r = Roaring(range(0, 10000, 2))
assert [c[0] for c in r.chunks.values()] == ["bitmap"]
r = Roaring(range(100000))
assert {hi: c for hi, c in r.chunks.items()} == {0: ("run", [(0, 65535)]),
1: ("run", [(0, 34463)])}
r = Roaring(x * 65536 for x in range(1000))
assert len(r.chunks) == 1000 and all(c == ("array", [0]) for c in r.chunks.values())
3.11 ★★ Roaring on random data. n distinct 32-bit integers are drawn uniformly at random. Estimate the size of a Roaring bitmap for n = 10⁶ and for n = 10⁹, and compare each with a sorted array of 32-bit integers and with a plain bitmap of 2³² bits. Count 8 bytes of overhead per container, as Roaring’s standard serialized format does (a 2-byte key, a 2-byte cardinality and a 4-byte offset). At what n do the containers switch from arrays to bitmaps?
Hint
There are 65,536 chunks, and with uniform data each gets about n / 65,536 values.
Solution
n = 10⁶. Each chunk gets about 10⁶ / 65,536 ≈ 15 values, so practically every chunk is non-empty (the chance that one is empty is about e⁻¹⁵) and every container is an array. Containers: 10⁶ × 2 bytes = 2 MB. Overhead: 65,536 × 8 bytes = 512 KB. Total about 2.5 MB, against 4 MB for the sorted array and 512 MB for the plain bitmap. Random data has no runs and no dense regions, so the saving over the sorted array comes only from not repeating the high half, which every value in a chunk shares.
n = 10⁹. Each chunk gets about 15,259 values, more than 4096, so every container is an 8 KB bitmap: 65,536 × 8 KB = 512 MB plus 512 KB of overhead, the same as the plain bitmap (which is the right representation at this density), against 4 GB for the sorted array.
The switch happens when a chunk’s expected count crosses 4096, a density of 4096 / 65,536 = 1/16, so at about n = 2³² / 16 ≈ 2.7 × 10⁸. Below that Roaring costs about 16 bits per value plus overhead; above it, a fixed 512 MB. Either way it is never far from the better of the sorted array and the plain bitmap, which is the point of choosing the container per chunk.
Where this connects
- Chapter 4: Linked Lists—The Art of Distributed Storage. The same sequence problem solved with pointers instead of contiguity
- Chapter 16: External Memory and Cache-Oblivious Structures. Why contiguous layout beats pointer-chasing by more than the asymptotics suggest
Chapter 4: Linked Lists—The Art of Distributed Storage
4.1 The Linked List Philosophy
Where arrays store elements contiguously, linked lists store elements anywhere in memory, connecting them via pointers. This distribution enables efficient insertion and deletion at arbitrary positions, at the cost of no direct indexing.
The fundamental trade-off:
- Array: Fast access, slow modification
- Linked list: Slow access (must traverse), fast modification
4.2 Singly Linked Lists
Each node contains data and a pointer to the next node:
struct Node {
element_type data;
struct Node *next;
};
HEAD NULL
│ │
▼ ▼
┌────────┬───────┐ ┌────────┬───────┐ ┌────────┬───────┐ ┌────────┬───────┐
│ Data: A│ Next: ──────→│ Data: B│ Next: ──────→│ Data: C│ Next: ──────→│ Data: D│ Next: │
│ │ │ │ │ │ │ │ │ │ │ │
└────────┴───────┘ └────────┴───────┘ └────────┴───────┘ └────────┴───────┘
Core Operations
Insertion at Head:
void insert_head(Node **head_ref, element_type data) {
Node *new_node = malloc(sizeof(Node));
new_node->data = data;
new_node->next = *head_ref;
*head_ref = new_node;
}
Time: O(1)
Insertion at Position:
void insert_after(Node *prev_node, element_type data) {
if (prev_node == NULL) return;
Node *new_node = malloc(sizeof(Node));
new_node->data = data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
Time: O(1) given position, O(n) to find position
Deletion:
void delete_node(Node **head_ref, element_type key) {
Node *temp = *head_ref;
Node *prev = NULL;
if (temp != NULL && temp->data == key) {
*head_ref = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
Time: O(n) worst case to find, O(1) to delete
Search:
Node* search(Node *head, element_type key) {
Node *current = head;
while (current != NULL) {
if (current->data == key) return current;
current = current->next;
}
return NULL;
}
Time: O(n)
4.3 Doubly Linked Lists
Each node contains data, a pointer to the next node, and a pointer to the previous node:
struct DNode {
element_type data;
struct DNode *next;
struct DNode *prev;
};
NULL NULL
│ │
│ ┌────────┬────────┬───────┐ ┌────────┬────────┬───────┐
│ │ Prev │ Data │ Next │ │ Prev │ Data │ Next │
└────→│ NULL │ A │ ────┼───→│ ────┤ B │ ────┼───→ NULL
└────────┴────────┴───────┘ └────────┴────────┴───────┘
Advantages Over Singly Linked Lists
- Traversal in both directions
- O(1) deletion given a node pointer (no need to find previous)
- O(1) insertion before a given node
- Better for implementing deques
Implementation
Deletion (given node pointer):
void delete_node(DNode *node) {
if (node->prev != NULL)
node->prev->next = node->next;
else
head = node->next; // Was head
if (node->next != NULL)
node->next->prev = node->prev;
free(node);
}
Insertion Before:
void insert_before(DNode **head, DNode *next_node, element_type data) {
DNode *new_node = malloc(sizeof(DNode));
new_node->data = data;
new_node->next = next_node;
new_node->prev = next_node->prev;
if (next_node->prev != NULL)
next_node->prev->next = new_node;
else
*head = new_node; // Was head
next_node->prev = new_node;
}
4.4 Circular Linked Lists
The last node’s next pointer points back to the first node (or for doubly, the first node’s prev points to the last).
Circular Singly:
┌────────┬───────┐ ┌────────┬───────┐ ┌────────┬───────┐
│ Data: A│ Next: ────┼─→│ Data: B│ Next: ────┼─→│ Data: C│ Next: ────┐
│ │ │ │ │ │ │ │ │ │
└────────┴───────┘ └────────┴───────┘ └────────┴───────┘ │
↑ │
└──────────────────────────────────────────────────────────────┘
Circular Doubly:
NULL ◄────────────────────────────────────────────────────────────────► NULL
│ ┌────────┬────────┬───────┐ ┌────────┬────────┬───────┐ │
│ │ Prev │ Data │ Next │ │ Prev │ Data │ Next │ │
└────→│ ● │ A │ ────┼───→│ ────┤ B │ ────┼───→│
└────────┴────────┴───────┘ └────────┴────────┴───────┘ │
▲ │
└──────────────────────────────────────────────────────────────┘
Applications
Round-Robin Scheduling: Each process gets equal CPU time Circular Buffers: Efficient producer-consumer patterns Music Playlists: Seamless looping Undo/Redo History: Recent actions cycle through
4.5 The Sentinel’s Guard
Sentinel nodes (dummy nodes) simplify boundary conditions by eliminating null checks:
// Without sentinel - careful null handling
void insert_first(Node **head, element_type data) {
Node *new_node = malloc(sizeof(Node));
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
// With sentinel - cleaner code
void insert_after(Node *prev, element_type data) {
Node *new_node = malloc(sizeof(Node));
new_node->data = data;
new_node->next = prev->next;
prev->next = new_node;
}
Common sentinel patterns:
- Head sentinel: Dummy node before first real element
- Tail sentinel: Dummy node after last real element
- Both: Simplifies all operations to “insert after/before”
4.6 Pointer Techniques
A handful of pointer patterns solve most problems on singly linked lists. Each runs in O(n) worst-case time with O(1) extra space, and each works by rewiring next fields rather than copying data into an array. The code uses the Python Node class from the exercises at the end of this chapter, with two helpers for building and printing lists:
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def from_list(xs):
head = None
for x in reversed(xs):
head = Node(x, head)
return head
def to_list(node):
out = []
while node:
out.append(node.data)
node = node.next
return out
In-Place Reversal
Walk the list once and turn each next pointer around. Three pointers do it:
def reverse(head):
prev, cur = None, head
while cur:
nxt = cur.next # 1. save the rest of the list
cur.next = prev # 2. turn this node around
prev = cur # 3. it now heads the reversed part
cur = nxt # 4. move on to the rest
return prev
The invariant, true at the top of every iteration: prev is the head of the reversed prefix (the nodes already visited, in reverse order), cur is the head of the untouched suffix, and together the two lists hold every node exactly once. Each iteration moves one node from the front of the suffix to the front of the prefix. When cur is None the suffix is empty and prev is the whole list, reversed.
| Iteration | prev (reversed part) | cur (rest) |
|---|---|---|
| start | None | 1 → 2 → 3 → 4 |
| 1 | 1 | 2 → 3 → 4 |
| 2 | 2 → 1 | 3 → 4 |
| 3 | 3 → 2 → 1 | 4 |
| 4 | 4 → 3 → 2 → 1 | None |
The order of the four statements is the whole difficulty. Step 2 overwrites the only reference to the rest of the list, so step 1 must save it first; Exercise 4.3 shows what happens otherwise. The loop is O(n) time and O(1) space. A recursive version is shorter but uses O(n) stack, which for a long list overflows the stack (or, in Python, hits the recursion limit of 1000).
Fast and Slow Pointers
Two pointers start at the head; slow moves one node per step and fast moves two. After k steps, slow is at index k and fast at index 2k. That alone finds the middle in one pass, without counting the length first:
def middle(head):
"""Node at index n // 2 of a non-empty list of n nodes."""
slow = fast = head
while fast and fast.next:
slow = slow.next # one step
fast = fast.next.next # two steps
return slow
The loop stops when fast has no two nodes left to move over, so slow is at index ⌊n/2⌋: node 3 of 1 → 2 → 3 → 4 → 5, and node 3 of 1 → 2 → 3 → 4 (the second of the two middles).
Cycle detection. If a bug or a malicious input makes some next point back to an earlier node, a plain traversal loops forever. Floyd’s algorithm detects this with the same two pointers. If the list ends, fast reaches None. If it has a cycle, both pointers end up going round it, and fast gains one node on slow at every step. Measured along the cycle, the distance from fast forward to slow therefore drops by exactly 1 per step, so it reaches 0 (fast cannot jump over slow) within λ steps of slow entering the cycle, where λ is the cycle length.
Finding where the cycle starts takes a counting argument. Let μ be the number of steps from the head to the first node of the cycle (the tail length), and suppose the pointers meet after slow has taken k steps, so fast has taken 2k.
- Both pointers are on the same node, and fast has walked the same path as slow plus k more steps. Those extra k steps went round the cycle and returned to the same node, so k is a multiple of λ.
- Slow is in the cycle, k − μ steps past its start.
- Walk μ more steps from the meeting point. That is k − μ + μ = k steps past the start of the cycle, and since k is a multiple of λ, that lands exactly on the start.
- A pointer starting at the head also reaches the start after exactly μ steps.
So move one pointer back to the head and advance both one step at a time. They meet at the first node of the cycle, after μ steps, without either μ or λ being known:
def find_cycle_start(head):
"""First node of the cycle, or None if the list ends."""
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast: # phase 1: they met inside the cycle
slow = head
while slow is not fast: # phase 2: both step once
slow, fast = slow.next, fast.next
return slow
return None
Worked example: nodes 1 to 8, with node 8 linking back to node 4, so μ = 3 and λ = 5.
| Step | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| slow | 2 | 3 | 4 | 5 | 6 |
| fast | 3 | 5 | 7 | 4 | 6 |
They meet at node 6 after k = 5 steps, a multiple of λ, and node 6 is k − μ = 2 steps past node 4. Phase 2 moves the pair (1, 6) to (2, 7), (3, 8), (4, 4): both reach node 4 after μ = 3 steps. In general k is the smallest positive multiple of λ that is at least μ, so phase 1 takes at most μ + λ steps and phase 2 takes μ: O(n) worst case, O(1) space. Remembering visited nodes in a hash set also works, but costs O(n) extra space. The cycle length comes for free as well: from the meeting point, count steps until slow returns to it.
The algorithm never uses the fact that the nodes are a list. It works on any sequence x, f(x), f(f(x)), … where only the current value is stored, which is how it finds the period of a pseudo-random number generator and how Pollard’s rho method factors integers.
Merging Two Sorted Lists
Merging is where the sentinel of Section 4.5 pays off. The result list grows at its tail, and without a sentinel the first node is a special case: there is no tail yet to link after, so the code must pick the head separately and then repeat the same comparison inside the loop. A dummy head gives tail a node to start from, and the real result is dummy.next:
def merge(a, b):
"""Merge two sorted lists by relinking their nodes; stable."""
dummy = tail = Node(None) # sentinel: tail always has a node to link after
while a and b:
if a.data <= b.data: # <= takes from a on ties, so the merge is stable
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a if a else b # splice the leftover run in O(1)
return dummy.next
Invariant: dummy.next through tail holds the nodes taken so far in sorted order, and every node left in a or b is at least tail.data. Merging 1 → 4 → 6 with 2 → 3 → 7 takes 1, 2, 3, 4, 6; then a is empty and the single assignment tail.next = b attaches 7, however long the rest of b is. The merge allocates no nodes apart from the dummy: O(m + n) time in the worst case, O(1) extra space. The same merge on arrays needs an O(m + n) output buffer, because array elements cannot be relinked.
Merge Sort on Linked Lists
Merge sort is the natural sort for linked lists. Split the list in half with fast and slow pointers, sort each half recursively, and merge:
def split_point(head):
"""Last node of the first half: index (n - 1) // 2 of n >= 2 nodes."""
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow
def merge_sort(head):
if head is None or head.next is None:
return head
mid = split_point(head)
right = mid.next
mid.next = None # cut into two lists
return merge(merge_sort(head), merge_sort(right))
assert to_list(merge_sort(from_list([5, 2, 4, 1, 3]))) == [1, 2, 3, 4, 5]
split_point starts fast one node ahead, so it stops at the end of the first half rather than at the start of the second, which middle would return; Exercise 4.8 shows why that difference matters. On 5 → 2 → 4 → 1 → 3 it cuts after 4, giving [5, 2, 4] and [1, 3]; those sort to 2 → 4 → 5 and 1 → 3, and the final merge gives 1 → 2 → 3 → 4 → 5.
The structure fits lists better than arrays on each count:
- The merge needs no buffer. Array merge sort copies into O(n) auxiliary space; the list version relinks nodes in place.
- Only sequential access is used. Splitting and merging both walk forward. Heapsort’s index arithmetic needs random access, and quicksort’s usual protection against its O(n²) worst case (a random or median-of-three pivot) needs cheap access to arbitrary positions.
- It is stable (the
<=inmerge) and its O(n log n) bound is worst case, not average.
Each level of recursion spends O(n) on splitting and O(n) on merging, over ⌈log₂ n⌉ levels: O(n log n) worst-case time. The top-down version above uses O(log n) stack. A bottom-up version, which merges runs of length 1, 2, 4, … in a loop, needs only O(1) extra space; that is what the Linux kernel’s list_sort and libstdc++’s std::list::sort do.
4.7 XOR Linked Lists
XOR linked lists store only the XOR of consecutive node addresses, saving space:
struct XorNode {
element_type data;
uintptr_t npx; // XOR of previous and next pointers
};
The trick: to traverse, you need the previous node’s address to XOR with npx to get the next node’s address.
Traversal:
XorNode* prev = NULL;
XorNode* current = head;
XorNode* next;
while (current != NULL) {
printf("%d ", current->data);
next = (XorNode*)((uintptr_t)prev ^ current->npx);
prev = current;
current = next;
}
Advantages: 50% space reduction for pointers Disadvantages: Can’t traverse backwards without storing previous pointer, debugging is harder
4.8 Unrolled Linked Lists
Each node contains multiple elements in a small array:
┌────────┬───────┐ ┌────────┬───────┐
│ 3 │ A │ B │ C │ ──┼─→│ 2 │ D │ E │ ──┼─→ NULL
│ elements│ │ │ elements│ │
└────────┴───────┘ └────────┴───────┘
Advantages:
- Better cache locality (multiple elements per node)
- Less pointer overhead
- Faster iteration
- Still O(1) insertion at arbitrary positions (with smaller shift)
Used in: CD-ROM filesystems (directory entries), Kyoto Cabinet database, Redis’s quicklist (the encoding of the Redis list type since 3.2: a doubly linked list of packed arrays)
4.9 Performance Characteristics
| Operation | Singly | Doubly | Circular | Unrolled |
|---|---|---|---|---|
| Insert at Head | O(1) | O(1) | O(1) | O(1)* |
| Insert at Tail | O(1)* | O(1) | O(1) | O(1)* |
| Delete at Head | O(1) | O(1) | O(1) | O(1)* |
| Delete at Tail | O(n) | O(1) | O(1)* | O(1)* |
| Delete at Position | O(n) | O(n)* | O(n) | O(n)* |
| Search | O(n) | O(n) | O(n) | O(n) |
| Memory Overhead | Low | Medium | Low | Low-Medium |
| Cache Efficiency | Poor | Poor | Poor | Better |
*With tail pointer or other augmentation
4.10 When to Use Linked Lists
Use Linked Lists When:
- Frequent insertions/deletions at arbitrary positions
- Size is unknown or highly variable
- Memory is fragmented
- No random access needed
- Implementing other structures (stacks, queues)
Avoid Linked Lists When:
- Frequent random access (use arrays)
- Cache performance matters (use arrays or unrolled)
- Memory overhead is a concern (pointers take space)
- Simple iteration is the primary operation (vectors are faster)
4.11 Real-World Applications
Operating Systems:
- Process scheduling queues
- Memory allocation (free lists)
- File system directory entries
- Driver device queues
Databases:
- B-tree leaf nodes (doubly linked for range scans)
- Transaction logs
- Lock chains
Compilers:
- Symbol tables (hash table + linked list chaining)
- Abstract syntax trees (child lists)
Applications:
- Music playlists (doubly linked for bidirectional navigation)
- Browser history (back/forward buttons)
- Undo/redo functionality
- Text buffer implementation (lines as linked list)
4.12 Historical Context
The linked list was invented by Allen Newell, Cliff Shaw, and Herbert A. Simon at RAND Corporation in 1956, as part of the development of the Information Processing Language (IPL), the first AI programming language.
John McCarthy made linked lists the fundamental data structure of LISP (1958) and introduced the names “car” and “cdr” (contents of the address part of register, contents of the decrement part of register) for the two fields of a list cell.
The doubly linked list emerged later as programmers recognized the need for bidirectional traversal.
The tortoise-and-hare cycle detector of Section 4.6 is credited to Robert W. Floyd by Knuth (The Art of Computer Programming, Vol. 2, 1969), although Floyd never published it himself; Richard Brent published a faster variant in 1980. Merge sort is older than linked lists: Knuth attributes it to John von Neumann in 1945.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
4.1 ★ Trace the core operations. Using the singly linked list functions from Section 4.2, what does the list look like after each line? For each delete_node call, say which branch of the function does the work.
Node *head = NULL;
insert_head(&head, 3);
insert_head(&head, 7);
insert_head(&head, 1);
insert_after(head->next, 5);
delete_node(&head, 1);
delete_node(&head, 3);
delete_node(&head, 9);
Solution
| Line | List afterwards |
|---|---|
insert_head(&head, 3) | 3 → NULL |
insert_head(&head, 7) | 7 → 3 → NULL |
insert_head(&head, 1) | 1 → 7 → 3 → NULL |
insert_after(head->next, 5) | 1 → 7 → 5 → 3 → NULL |
delete_node(&head, 1) | 7 → 5 → 3 → NULL |
delete_node(&head, 3) | 7 → 5 → NULL |
delete_node(&head, 9) | 7 → 5 → NULL |
insert_after(head->next, 5):head->nextis the node holding 7, so 5 goes between 7 and 3.delete_node(&head, 1): the key is in the head node, so the firstifhandles it by moving*head_refto the second node. This is why the function takesNode **: it has to be able to change the caller’shead.delete_node(&head, 3): thewhileloop walks withprevone step behindtemp(7, then 5) untiltempreaches 3, thenprev->next = temp->nextunlinks it.previs the 5 node, whosenextbecomes NULL.delete_node(&head, 9): the loop runs off the end,tempis NULL, and theif (temp == NULL) return;line leaves the list unchanged.
4.2 ★ The tail pointer doesn’t help deletion. The table in Section 4.9 lists “Insert at Tail” as O(1) for a singly linked list with a tail pointer, but “Delete at Tail” as O(n). Explain why the tail pointer helps one and not the other, and what a doubly linked list changes.
Solution
Inserting at the tail only touches the old tail node: set tail->next = new_node, then tail = new_node. The tail pointer gives direct access to that node, so it is O(1).
Deleting the tail requires changing the node before it: its next must become NULL, and tail must move to it. A singly linked node has no pointer to its predecessor, so the only way to find it is to walk from the head: O(n). Keeping a pointer to the second-to-last node doesn’t fix this either, because after one deletion you need the third-to-last, and so on.
A doubly linked list stores prev in every node, so the new tail is tail->prev, found in O(1). That one extra pointer per node is the price of O(1) deletion at the tail, and of O(1) deletion of any node you hold a pointer to (Section 4.3). This is why queues (insert at one end, remove at the other) work fine on a singly linked list with a tail pointer, but deques need a doubly linked list or an array.
4.3 ★★ Find the bug. This function is meant to reverse a singly linked list in place and return the new head. On the list 1 → 2 → 3 → 4 it returns a list containing only 1. Why? Fix it.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def reverse(head):
prev = None
cur = head
while cur:
cur.next = prev
prev = cur
cur = cur.next
return prev
Hint
Trace the first iteration and write down what cur.next holds at the moment cur = cur.next runs.
Solution
First iteration: cur is node 1. cur.next = prev sets node 1’s next to None, which destroys the only reference to node 2. Then prev = cur (node 1), and cur = cur.next reads the pointer that was just overwritten: cur becomes None. The loop ends and the function returns node 1, whose next is None. Nodes 2, 3 and 4 are lost (in C, leaked).
The fix is to save the rest of the list before rewiring the pointer:
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def reverse(head):
prev = None
cur = head
while cur:
nxt = cur.next # save the rest of the list first
cur.next = prev # reverse this node's pointer
prev = cur
cur = nxt
return prev
def to_list(node):
out = []
while node:
out.append(node.data)
node = node.next
return out
head = Node(1, Node(2, Node(3, Node(4))))
assert to_list(reverse(head)) == [4, 3, 2, 1]
assert reverse(None) is None
assert to_list(reverse(Node(1))) == [1]
The invariant: at the top of each iteration, prev is the head of the already-reversed prefix and cur is the head of the untouched suffix. Overwriting cur.next before saving it breaks the link to the suffix. The function is O(n) time and O(1) extra space.
4.4 ★★ XOR list by hand. Four nodes A, B, C, D form an XOR linked list (Section 4.7), in that order, at addresses A = 0x10, B = 0x20, C = 0x30, D = 0x40. NULL is 0.
(a) Compute npx for every node.
(b) Traverse the list starting from D with prev = NULL, using the traversal loop from Section 4.7. Show each step.
(c) What do you need, at minimum, to start a traversal in the middle of the list, say at C?
Solution
(a) npx = address of previous XOR address of next.
| Node | prev | next | npx |
|---|---|---|---|
| A | 0x00 | 0x20 | 0x20 |
| B | 0x10 | 0x30 | 0x20 |
| C | 0x20 | 0x40 | 0x60 |
| D | 0x30 | 0x00 | 0x30 |
(A and B happen to have the same npx. That’s fine; npx only means something together with a neighbour’s address.)
(b) Each step computes next = prev ^ current->npx.
| current | prev | next = prev ^ npx | visit |
|---|---|---|---|
| D (0x40) | 0x00 | 0x00 ^ 0x30 = 0x30 (C) | D |
| C (0x30) | 0x40 | 0x40 ^ 0x60 = 0x20 (B) | C |
| B (0x20) | 0x30 | 0x30 ^ 0x20 = 0x10 (A) | B |
| A (0x10) | 0x20 | 0x20 ^ 0x20 = 0x00 (NULL) | A |
Output: D C B A. The same loop walks backwards when started from the tail, so an XOR list can be traversed in both directions; what it needs is the address of one end and the starting neighbour (NULL at either end).
(c) The address of C alone is useless: npx = 0x60 could be any pair of neighbours whose addresses XOR to 0x60. You need the addresses of two adjacent nodes, such as C and B (then next = 0x20 ^ 0x60 = 0x40, D) or C and D (then next = 0x40 ^ 0x60 = 0x20, B). For the same reason you can’t delete a node given only a pointer to it, which takes away one of the doubly linked list’s main advantages from Section 4.3.
4.5 ★★ One sentinel, no special cases. The doubly linked delete_node in Section 4.3 needs two if tests, and insert_before needs one, all for the head and tail cases. Implement a doubly linked list in Python with a single sentinel node that is both the “before head” and “after tail” node (the list is circular through the sentinel). Write push_front, push_back, insert_before(node, data) and delete(node) without any if statements.
Hint
An empty list is a sentinel whose prev and next both point to itself. Then every real node always has a real prev and next object, even when that object is the sentinel.
Solution
class DNode:
def __init__(self, data=None):
self.data = data
self.prev = self
self.next = self
class DList:
def __init__(self):
self.sentinel = DNode() # sentinel.next is the head, sentinel.prev the tail
def insert_before(self, node, data):
new = DNode(data)
new.prev, new.next = node.prev, node
node.prev.next = new
node.prev = new
return new
def push_front(self, data):
return self.insert_before(self.sentinel.next, data)
def push_back(self, data):
return self.insert_before(self.sentinel, data)
def delete(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def __iter__(self):
cur = self.sentinel.next
while cur is not self.sentinel:
yield cur.data
cur = cur.next
lst = DList()
b = lst.push_back("b")
lst.push_front("a")
d = lst.push_back("d")
lst.insert_before(d, "c")
assert list(lst) == ["a", "b", "c", "d"]
lst.delete(b)
lst.delete(d) # deleting the tail: no special case
assert list(lst) == ["a", "c"]
lst.delete(lst.sentinel.next) # deleting the head: no special case
lst.delete(lst.sentinel.next) # list is now empty
assert list(lst) == [] and lst.sentinel.next is lst.sentinel
The branches disappear because the conditions they tested (“is prev NULL?”, “is next NULL?”) can no longer be true: the head’s prev and the tail’s next are the sentinel. The cost is one extra node per list, and iteration must stop at the sentinel instead of at NULL. Fewer branches means fewer places for the head/tail bugs that dominate linked list code; this is the “Both” pattern from Section 4.5 with the two sentinels merged into one, and it is how the Linux kernel’s list_head works.
4.6 ★★★ Unrolled list insertion. Implement insert(i, x) for an unrolled linked list (Section 4.8) whose nodes hold at most B = 4 elements. When the target node is full, split it into two nodes of B/2 elements each, then insert. Then analyse: with n elements and node capacity B, what does one insert cost, and what B minimises it?
Hint
Walk node by node, subtracting each node’s count from i, until i falls inside (or at the end of) the current node. After a split, decide which half the insertion position belongs to.
Solution
import random
B = 4 # node capacity
class UNode:
def __init__(self, items=None):
self.items = items if items is not None else [] # at most B elements
self.next = None
class UnrolledList:
def __init__(self):
self.head = UNode()
self.n = 0
def insert(self, i, x):
"""Insert x so that it ends up at position i (0 <= i <= n)."""
if not 0 <= i <= self.n:
raise IndexError(i)
node = self.head
while i > len(node.items) and node.next is not None: # skip whole nodes
i -= len(node.items)
node = node.next
if len(node.items) == B: # full: split in half
half = B // 2
right = UNode(node.items[half:])
node.items = node.items[:half]
right.next = node.next
node.next = right
if i > half:
node, i = right, i - half
node.items.insert(i, x) # shifts at most B - 1
self.n += 1
def __iter__(self):
node = self.head
while node is not None:
yield from node.items
node = node.next
random.seed(7)
for trial in range(200):
u, ref = UnrolledList(), []
for k in range(random.randint(0, 60)):
i = random.randint(0, len(ref))
u.insert(i, k)
ref.insert(i, k)
assert list(u) == ref
Cost. A split always produces two nodes with B/2 elements, and nodes only grow between splits, so every node except possibly the first holds at least B/2 elements. There are therefore at most about 2n/B nodes. One insert costs:
- O(n/B) to walk to the right node (one step per node, not per element),
- O(B) to shift elements within the node (plus O(B) for a split, which copies half a node).
Total O(n/B + B). This is minimised when n/B = B, i.e. B ≈ √n, giving O(√n) per insert, against O(n) for both a plain array (shifting) and a plain linked list (walking). In practice B is chosen from the hardware instead, so that a node fills one or a few cache lines: the walk then touches n/B cache lines instead of n, which is where the “better cache locality” in Section 4.8 comes from. Pointer overhead also drops from one pointer per element to one pointer per B/2 or more elements.
4.7 ★ Floyd by hand. A list has nodes 1 to 10 in order, and node 10’s next points back to node 3. Run find_cycle_start from Section 4.6.
(a) What are μ and λ? After how many steps of phase 1 do slow and fast meet, and at which node?
(b) Trace phase 2.
(c) How would you compute λ from the meeting point?
Solution
(a) Two steps lead from node 1 to node 3, so μ = 2. The cycle is 3 → 4 → … → 10 → 3, so λ = 8.
| Step | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| slow | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| fast | 3 | 5 | 7 | 9 | 3 | 5 | 7 | 9 |
They meet at node 9 after k = 8 steps. As Section 4.6 predicts, k is the smallest positive multiple of λ that is at least μ, here 8 itself. Node 9 is k − μ = 6 steps past node 3.
(b) Slow restarts at node 1, fast stays at node 9, and both take single steps: (1, 9) → (2, 10) → (3, 3). They meet at node 3 after μ = 2 steps: from node 9, two steps (to 10, then back to 3) complete the lap that the 6 steps from node 3 began.
(c) Keep one pointer at the meeting point and step the other around until it comes back, counting: 9 → 10 → 3 → 4 → 5 → 6 → 7 → 8 → 9 is 8 steps, so λ = 8. Together with μ from phase 2, this also gives the number of distinct nodes, μ + λ = 10.
4.8 ★★ Find the bug. This merge sort uses middle from Section 4.6 instead of split_point. On any list of two or more nodes it raises RecursionError in Python (in C, it overflows the stack). Why? Fix it while still splitting at middle’s node.
def merge_sort(head):
if head is None or head.next is None:
return head
mid = middle(head)
right = mid.next
mid.next = None
return merge(merge_sort(head), merge_sort(right))
Hint
Run it on a two-node list. Which node does middle return, and how long is each half?
Solution
middle returns the node at index ⌊n/2⌋, and the code cuts after it, so the left half has ⌊n/2⌋ + 1 nodes. For n = 2 that is 2: middle returns the second node, right is None, and merge_sort(head) is called again on the same two-node list, forever. Larger lists shrink until some call gets two nodes (n = 3 splits into 2 and 1), so every list of two or more nodes hits the loop. A split is only safe if both halves are non-empty, so each recursive call is on a strictly shorter list.
The fix is to cut before the middle node, which needs the node behind slow:
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def merge(a, b):
dummy = tail = Node(None)
while a and b:
if a.data <= b.data:
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a if a else b
return dummy.next
def merge_sort(head):
if head is None or head.next is None:
return head
prev, slow, fast = None, head, head
while fast and fast.next:
prev, slow, fast = slow, slow.next, fast.next.next
prev.next = None # cut just before the middle node
return merge(merge_sort(head), merge_sort(slow))
def from_list(xs):
head = None
for x in reversed(xs):
head = Node(x, head)
return head
def to_list(node):
out = []
while node:
out.append(node.data)
node = node.next
return out
import random
for _ in range(500):
xs = [random.randint(0, 9) for _ in range(random.randint(0, 30))]
assert to_list(merge_sort(from_list(xs))) == sorted(xs)
With n ≥ 2 the loop runs at least once, so prev is a real node, and the halves have ⌊n/2⌋ and ⌈n/2⌉ nodes, both at least 1. split_point in Section 4.6 reaches the same cut more directly by starting fast one node ahead, so that slow stops on the last node of the first half.
4.9 ★★ Palindrome in O(1) space. Write is_palindrome(head) for a singly linked list using O(1) extra space (no copying into a Python list), and leave the list exactly as it was when the function returns.
Hint
Find the end of the first half, reverse the second half in place, compare the two halves node by node, then reverse the second half again.
Solution
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def reverse(head):
prev, cur = None, head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prev
def is_palindrome(head):
"""True if the list reads the same both ways; O(n) time, O(1) extra space."""
if head is None or head.next is None:
return True
slow, fast = head, head.next # slow stops at the end of the first half
while fast and fast.next:
slow, fast = slow.next, fast.next.next
second = reverse(slow.next) # reverse the second half in place
p, q, result = head, second, True
while q: # second half is never the longer one
if p.data != q.data:
result = False
break
p, q = p.next, q.next
slow.next = reverse(second) # restore the original list
return result
def from_list(xs):
head = None
for x in reversed(xs):
head = Node(x, head)
return head
def to_list(node):
out = []
while node:
out.append(node.data)
node = node.next
return out
for xs in ([1, 2, 3, 2, 1], [1, 2, 2, 1], [1, 2, 3, 1], [1, 2], [7], []):
head = from_list(xs)
assert is_palindrome(head) == (xs == xs[::-1])
assert to_list(head) == xs # list left unchanged
On 1 → 2 → 3 → 2 → 1, slow stops at node 3 (index (n − 1) // 2 = 2, as in split_point), the second half 2 → 1 is reversed to 1 → 2, and the comparison checks 1 = 1 and 2 = 2; the middle element of an odd-length list is never compared, which is correct. The first half has ⌈n/2⌉ nodes and the second ⌊n/2⌋, so stopping when the second half runs out compares every mirrored pair.
Each of the three passes (find the split, reverse, compare) plus the restoring reverse is O(n), so the total is O(n) time and O(1) extra space. The restore step matters: a function called is_palindrome that silently scrambles its argument is a bug waiting for the caller. It is also why this technique is unsafe if another thread reads the list at the same time.
Where this connects
- Chapter 3: Arrays—The Foundation of Contiguous Storage. The contiguous alternative, and when it wins
- Chapter 18: Concurrent Data Structures. Why lock-free versions of these structures are hard
Chapter 5: Stacks and Queues—Ordered Access Patterns
5.1 Stacks: The LIFO Principle
A stack is an ADT supporting two primary operations: push (add to top) and pop (remove from top). The last element pushed is the first to be popped, Last In, First Out.
Mental Model: A stack of plates in a cafeteria. You add plates to the top, and you take plates from the top. You never reach into the middle of the stack.
┌─────────┐
│ TOP │ ← Push(4), Pop() returns 4
├─────────┤
│ 3 │
├─────────┤
│ 2 │
├─────────┤
│ 1 │
└─────────┘
BOTTOM
5.2 Stack Implementation
Array-Based Stack
#define MAX_SIZE 1000
typedef struct {
int top;
element_type data[MAX_SIZE];
} Stack;
void init(Stack *s) { s->top = -1; }
int is_empty(Stack *s) { return s->top == -1; }
int is_full(Stack *s) { return s->top == MAX_SIZE - 1; }
void push(Stack *s, element_type x) {
if (is_full(s)) { /* handle overflow */ }
s->data[++s->top] = x;
}
element_type pop(Stack *s) {
if (is_empty(s)) { /* handle underflow */ }
return s->data[s->top--];
}
element_type peek(Stack *s) {
if (is_empty(s)) { /* handle empty */ }
return s->data[s->top];
}
Linked List-Based Stack
typedef struct StackNode {
element_type data;
struct StackNode *next;
} StackNode;
StackNode *top = NULL;
void push(element_type x) {
StackNode *node = malloc(sizeof(StackNode));
node->data = x;
node->next = top;
top = node;
}
element_type pop() {
if (top == NULL) { /* handle underflow */ }
StackNode *tmp = top;
element_type val = tmp->data;
top = top->next;
free(tmp);
return val;
}
5.3 Stack Applications
Function Call Stack
The most important use of stacks: managing function calls. Each function call pushes a stack frame containing:
- Return address
- Parameters
- Local variables
- Saved registers
int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
fact(4):
fact(4) calls fact(3)
fact(3) calls fact(2)
fact(2) calls fact(1)
fact(1) returns 1
fact(2) returns 2 * 1 = 2
fact(3) returns 3 * 2 = 6
fact(4) returns 4 * 6 = 24
Stack growth:
┌──────────┐
│ fact(1) │ ← Returns, stack shrinks
├──────────┤
│ fact(2) │
├──────────┤
│ fact(3) │
├──────────┤
│ fact(4) │ ← Called first
└──────────┘
Stack overflow occurs when the call stack exceeds its allocated size, often due to infinite recursion.
Expression Evaluation
Stacks enable evaluation of expressions in postfix (Reverse Polish) notation:
Infix: 3 + 4 * 2 / (1 - 5)
Postfix: 3 4 2 * 1 5 - / +
Evaluation:
Push 3
Push 4
Push 2
Multiply: pop 2, pop 4, push 8 Stack: [3, 8]
Push 1
Push 5
Subtract: pop 5, pop 1, push -4 Stack: [3, 8, -4]
Divide: pop -4, pop 8, push -2 Stack: [3, -2]
Add: pop -2, pop 3, push 1 Stack: [1]
Result: 1
Infix to Postfix Conversion (Shunting-yard algorithm):
- Numbers: output immediately
- Operators: pop operators with higher precedence (or equal precedence, for left-associative operators such as
-and/), then push - Left parenthesis: push
- Right parenthesis: pop until left parenthesis
- End of input: pop all remaining operators
Parentheses Matching
int is_balanced(char *expr) {
Stack s;
init(&s);
while (*expr) {
if (*expr == '(' || *expr == '[' || *expr == '{') {
push(&s, *expr);
} else if (*expr == ')' || *expr == ']' || *expr == '}') {
if (is_empty(&s)) return 0;
char top = pop(&s);
if ((top == '(' && *expr != ')') ||
(top == '[' && *expr != ']') ||
(top == '{' && *expr != '}')) {
return 0;
}
}
expr++;
}
return is_empty(&s);
}
Undo/Redo Systems
Applications maintain two stacks: one for undo, one for redo:
typedef struct {
Stack undo;
Stack redo;
Document doc;
} Editor;
void do_action(Editor *ed, Action action) {
push(&ed->undo, save_state(&ed->doc));
apply(action, &ed->doc);
clear_stack(&ed->redo);
}
void undo(Editor *ed) {
if (is_empty(&ed->undo)) return;
State *s = pop(&ed->undo);
push(&ed->redo, save_state(&ed->doc));
restore(s, &ed->doc);
}
void redo(Editor *ed) {
if (is_empty(&ed->redo)) return;
State *s = pop(&ed->redo);
push(&ed->undo, save_state(&ed->doc));
restore(s, &ed->doc);
}
Backtracking Algorithms
Depth-first search, maze solving, and many recursive algorithms naturally use stacks:
void solve_maze(int maze[][], int start_x, int start_y) {
Stack path;
init(&path);
push(&path, (Point){start_x, start_y});
while (!is_empty(&path)) {
Point p = peek(&path);
if (is_goal(p)) {
print_solution(&path);
return;
}
if (!has_unvisited_neighbors(maze, p)) {
pop(&path); // Backtrack
} else {
Point next = get_unvisited_neighbor(maze, p);
mark_visited(maze, next);
push(&path, next);
}
}
}
5.4 Queues: The FIFO Principle
A queue is an ADT where elements are added at the rear and removed from the front. First In, First Out.
Mental Model: A line of people waiting for a bus. New arrivals join at the back; those at the front board first.
FRONT REAR
│ │
▼ ▼
┌────────┬────────┬────────┬────────┬────────┐
│ A │ B │ C │ D │ E │
└────────┴────────┴────────┴────────┴────────┘
↑ ↑
Dequeue() Enqueue(F)
returns A
5.5 Queue Implementation
Simple Array Queue (Inefficient)
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
int size;
} Queue;
// Problem: Array fills up even though elements leave from front
// Solution: Circular queue
Circular Queue
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
} CircularQueue;
int is_empty(CircularQueue *q) {
return q->front == q->rear;
}
int is_full(CircularQueue *q) {
return (q->rear + 1) % MAX_SIZE == q->front;
}
void enqueue(CircularQueue *q, int x) {
if (is_full(q)) { /* handle overflow */ }
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAX_SIZE;
}
int dequeue(CircularQueue *q) {
if (is_empty(q)) { /* handle underflow */ }
int x = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return x;
}
MAX_SIZE = 6, starting from front = rear = 4.
Enqueue 4, 5, 6, then dequeue twice, then enqueue 7:
front
│
▼
┌────┬────┬────┬────┬────┬────┐
│ 6 │ 7 │ -- │ -- │ 4 │ 5 │
└────┴────┴────┴────┴────┴────┘
▲
rear
4 and 5 have been dequeued; their slots still hold the old
values but are free and will be overwritten.
Linked List Queue
typedef struct QNode {
int data;
struct QNode *next;
} QNode;
typedef struct {
QNode *front;
QNode *rear;
} LinkedQueue;
void enqueue(LinkedQueue *q, int x) {
QNode *node = malloc(sizeof(QNode));
node->data = x;
node->next = NULL;
if (q->rear) q->rear->next = node;
q->rear = node;
if (!q->front) q->front = node;
}
int dequeue(LinkedQueue *q) {
if (!q->front) { /* handle underflow */ }
QNode *tmp = q->front;
int x = tmp->data;
q->front = tmp->next;
if (!q->front) q->rear = NULL;
free(tmp);
return x;
}
5.6 Double-Ended Queue (Deque)
A deque allows insertion and deletion at both ends:
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
int size;
} Deque;
void push_front(Deque *d, int x);
void push_back(Deque *d, int x);
int pop_front(Deque *d);
int pop_back(Deque *d);
Applications:
- Implementing both stacks and queues
- Sliding window maximum and minimum (Section 5.9)
- Palindrome checking
- A-Steal algorithm (parallel task scheduling)
- Text editor undo/redo (two deques)
5.7 Priority Queues
A priority queue extracts elements based on priority, not arrival order:
// Higher number = higher priority (max-heap)
// Lower number = higher priority (min-heap)
typedef struct {
element_type *data;
int size;
int capacity;
int (*compare)(element_type, element_type);
} PriorityQueue;
Operations:
- Insert: O(log n)
- Extract min/max: O(log n)
- Peek: O(1)
- Decrease/increase key: O(log n) in a binary heap, given an index that locates the element in O(1)
Implementations:
- Binary heap: Most common, O(log n) worst case
- Fibonacci heap: O(1) amortized insert, used in Dijkstra’s algorithm
- Binomial heap: O(log n) all operations, useful for meldable priority queues
- Array (sorted): O(1) extract-min, O(n) insert
- Array (unsorted): O(n) extract-min, O(1) insert
5.8 Queue Applications
Breadth-First Search
BFS naturally uses a queue to explore graphs level by level:
def bfs(graph, start):
visited = {start}
queue = deque([start])
while queue:
vertex = queue.popleft()
process(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
Task Scheduling
Operating systems use queues to manage processes:
- Ready queue: Processes waiting for CPU
- I/O queues: Processes waiting for devices
- Priority queues: Real-time scheduling
Print Spooling
Multiple print jobs go into a queue; printers process them in order (or by priority).
Producer-Consumer Problem
Queues mediate between threads or processes with different speeds:
from queue import Queue
import threading
def producer(queue):
for i in range(10):
queue.put(i) # Blocks if queue full
def consumer(queue):
while True:
item = queue.get() # Blocks if queue empty
process(item)
queue.task_done()
queue = Queue(maxsize=4) # bounded, so put() can block
threading.Thread(target=producer, args=(queue,)).start()
threading.Thread(target=consumer, args=(queue,)).start()
5.9 Monotonic Stacks and Queues
A monotonic stack is an ordinary stack with one extra rule: before pushing x, pop every element on top that would break sorted order. The contents stay sorted, but that is a side effect. What matters is the pops: when x pops an element, x is the answer to a question about that element, such as “what is the first larger value to my right?” Any problem that asks, for every position, about the nearest larger or smaller element falls to this pattern in O(n).
Next Greater Element
For each index i, find the first j > i with a[j] > a[i], or −1 if there is none. Scanning forward from every i is O(n²) in the worst case (a decreasing array, where every scan runs to the end).
Instead, scan left to right and keep on a stack the indices that have not found their answer yet.
Invariant: the values at the stacked indices are non-increasing from bottom to top. A smaller value cannot sit below a larger one that came after it, because the larger one would have answered it and popped it on arrival.
When x = a[j] arrives, the waiting elements it answers are exactly those with values smaller than x, and the invariant puts all of them at the top. Pop them, record j for each, then push j. Everything left below j is ≥ x, so the invariant still holds.
def next_greater(a):
"""ans[i] = index of the first j > i with a[j] > a[i], or -1 if none."""
ans = [-1] * len(a)
stack = [] # indices still waiting for an answer
for j, x in enumerate(a):
while stack and a[stack[-1]] < x:
ans[stack.pop()] = j # x is the first larger value after it
stack.append(j)
return ans
assert next_greater([2, 7, 3, 5, 4, 6, 8]) == [1, 6, 3, 5, 5, 6, -1]
Trace on a = [2, 7, 3, 5, 4, 6, 8], with the stack shown as values:
| j | a[j] | Popped (index: value), answered by j | Stack after |
|---|---|---|---|
| 0 | 2 | [2] | |
| 1 | 7 | 0: 2 | [7] |
| 2 | 3 | [7, 3] | |
| 3 | 5 | 2: 3 | [7, 5] |
| 4 | 4 | [7, 5, 4] | |
| 5 | 6 | 4: 4, then 3: 5 | [7, 6] |
| 6 | 8 | 5: 6, then 1: 7 | [8] |
The next greater values are 7, 8, 5, 6, 6, 8 and none. Whatever is still on the stack when the scan ends (here the 8) has no greater element to its right.
The same loop answers related questions. Flipping the comparison gives the next smaller element. After the pops at step j, the new top of the stack is the nearest earlier element that is ≥ x, so one pass also yields every element’s previous greater-or-equal element; stock span below uses exactly that. With duplicate values, decide deliberately whether equal elements pop (<=) or stay (<). It changes the answers, and Exercise 5.8 is a problem where getting it wrong double-counts.
Why It Is O(n): Amortized Analysis Again
A single step can pop many elements. Step 6 above pops two, and on [5, 4, 3, 2, 1, 9] the last step pops five, so one step is O(n) in the worst case. But each index is pushed exactly once and popped at most once, so the while loop runs at most n times over the whole scan. The total is O(n) in the worst case, which is amortized O(1) per element: the aggregate method of Section 1.5 (Chapter 1).
The potential method makes the bookkeeping explicit. Let Φ be the number of elements on the stack: it starts at 0 and is never negative. A step that pops k elements and pushes one does k + 1 units of real work and changes Φ by 1 − k, so its amortized cost is (k + 1) + (1 − k) = 2, whatever k is. Each push prepays its own future pop. The dynamic array (Chapter 3, Section 3.4) and the queue built from two stacks (Exercise 5.5) are paid for the same way: every element is moved a constant number of times over its lifetime, however those moves bunch together.
Stock Span
The span of a stock’s price on day i is the number of consecutive days, ending with day i, on which the price was at most the price on day i. It equals i minus the index of the most recent earlier day with a strictly higher price. That is the “previous greater” variant, and it works online: each span is known as soon as that day’s price arrives.
def stock_spans(prices):
"""span[i] = number of consecutive days ending at day i with price <= prices[i]."""
spans = []
stack = [] # indices; prices strictly decreasing
for i, p in enumerate(prices):
while stack and prices[stack[-1]] <= p:
stack.pop() # can never stop a later span that p doesn't
spans.append(i - stack[-1] if stack else i + 1)
stack.append(i)
return spans
assert stock_spans([100, 80, 60, 70, 60, 75, 85]) == [1, 1, 1, 2, 1, 4, 6]
On day 5 (price 75) the stack holds the prices 100, 80, 70, 60. The 60 and the 70 are popped, 80 at index 1 is left on top, and the span is 5 − 1 = 4 (days 2 to 5: 60, 70, 60, 75). Day 2’s 60 is not on the stack at all: day 3’s 70 popped it, and rightly so, because any later price that 60 would stop, 70 stops too, and 70 is nearer.
Largest Rectangle in a Histogram
Bars of width 1 and heights h[0], …, h[n − 1] stand side by side. Find the area of the largest axis-aligned rectangle that fits under them. Trying every start and extending to the right while tracking the minimum height is O(n²).
The largest rectangle is as tall as its shortest bar, say bar i, and at that height it extends as far as it can: left until the nearest bar lower than h[i], right until the nearest bar lower than h[i]. So the answer is the maximum over i of h[i] × (right − left − 1), where left and right are the indices of those two lower bars (−1 and n when there is none). A single monotonic stack pass finds both for every bar. Keep indices whose heights are strictly increasing from bottom to top. When bar j pops bar i, j is the first bar to the right of i that is not taller than h[i], and the index just below i on the stack is the nearest bar to the left that is strictly lower (everything that stood between them was popped by i or by something that i later popped, so it was at least as tall as h[i]).
def largest_rectangle(h):
"""Area of the largest rectangle under a histogram of bar heights h."""
best = 0
stack = [] # indices; heights strictly increasing
for j, x in enumerate(h + [0]): # a height-0 bar at the end flushes the stack
while stack and h[stack[-1]] >= x:
i = stack.pop() # bar j is the first one right of i not taller than h[i]
left = stack[-1] if stack else -1 # nearest bar left of i lower than h[i]
best = max(best, h[i] * (j - left - 1))
stack.append(j)
return best
assert largest_rectangle([2, 1, 5, 6, 2, 3]) == 10
Equal heights need one remark. With >=, a bar is popped by the next bar of the same height, so its rectangle is cut short at that bar. Nothing is lost: the later bar has the same height, inherits the same left boundary (the index below), and computes the full rectangle when it is popped in turn.
Trace on h = [2, 1, 5, 6, 2, 3]:
| j | h[j] | Popped bar i (height): left, width, area | Stack after (heights) | Best |
|---|---|---|---|---|
| 0 | 2 | [2] | 0 | |
| 1 | 1 | 0 (2): left −1, width 1, area 2 | [1] | 2 |
| 2 | 5 | [1, 5] | 2 | |
| 3 | 6 | [1, 5, 6] | 2 | |
| 4 | 2 | 3 (6): left 2, width 1, area 6; 2 (5): left 1, width 2, area 10 | [1, 2] | 10 |
| 5 | 3 | [1, 2, 3] | 10 | |
| 6 | 0 (sentinel) | 5 (3): left 4, width 1, area 3; 4 (2): left 1, width 4, area 8; 1 (1): left −1, width 6, area 6 | [0] | 10 |
The answer is the 5 × 2 rectangle over bars 2 and 3. Each bar is pushed once and popped once, so the pass is O(n) in the worst case with O(n) extra space. The same pass applied row by row finds the largest all-1 rectangle in a 0/1 matrix (Exercise 5.9), and the same stack builds a Cartesian tree in O(n) (Chapter 23).
Monotonic Deque: Sliding Window Maximum
Given an array a and a window size k, output the maximum of every window a[i : i + k]. Recomputing each window is O(nk). A heap (Chapter 9) with lazy deletion of expired entries gets O(n log n). A monotonic deque gets O(n).
A stack is not enough here, because elements also leave the window at the old end. A deque (Section 5.6) provides both ends: the back behaves exactly like a monotonic stack, and the front lets expired indices out.
Invariant: the deque holds indices in increasing order, oldest at the front, and their values are strictly decreasing from front to back. These are exactly the elements that could still be the maximum of the current window or a later one. An element is useless as soon as a newer element at least as large arrives, because the newer one stays in every future window the older one is in. The front is therefore the maximum of the current window.
For each new index i:
- Pop from the back every index whose value is ≤
a[i]. - Push i at the back.
- If the front index has slid out of the window (≤ i − k), pop it from the front.
- Once the first full window is reached (i ≥ k − 1), output
a[front].
from collections import deque
def window_max(a, k):
dq = deque() # indices; their values are strictly decreasing
out = []
for i, x in enumerate(a):
while dq and a[dq[-1]] <= x: # x dominates these: drop them
dq.pop()
dq.append(i)
if dq[0] <= i - k: # front index has left the window
dq.popleft()
if i >= k - 1:
out.append(a[dq[0]])
return out
assert window_max([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
assert window_max([5, 4, 3, 2, 1], 2) == [5, 4, 3, 2]
assert window_max([2, 2, 2], 1) == [2, 2, 2]
Trace on a = [1, 3, -1, -3, 5, 3, 6, 7] with k = 3 (deque shown as values):
| i | a[i] | Deque after step | Output |
|---|---|---|---|
| 0 | 1 | [1] | |
| 1 | 3 | [3] | |
| 2 | −1 | [3, −1] | 3 |
| 3 | −3 | [3, −1, −3] | 3 |
| 4 | 5 | [5] | 5 |
| 5 | 3 | [5, 3] | 5 |
| 6 | 6 | [6] | 6 |
| 7 | 7 | [7] | 7 |
At i = 4 the front, 3 at index 1, has just expired, but the 5 had already cleared the whole deque from the back. Expiry from the front only matters when the maximum is old and nothing larger has arrived since: on [5, 4, 3, 2, 1] with k = 2, every step from i = 2 on pops the front.
Why O(n): each index is pushed onto the deque once and popped at most once, from one end or the other, so all the while loops together do at most n pops, and every deque operation is O(1). At most one front pop is needed per step, because the window advances one index at a time. The bound is O(n) worst case for the whole array and amortized O(1) per element, by the same potential argument as for the stack. Reversing the comparison gives the sliding window minimum. The pattern turns up wherever a rolling maximum or minimum is needed over a stream, and in the dynamic-programming optimization that Chapter 21 calls the monotonic deque. Exercise 5.7 runs a maximum deque and a minimum deque together inside the variable-size sliding window of Chapter 3.
The test for whether a problem fits: the brute force, for each position, scans outward until it meets something larger (or smaller), and once an element is beaten by a nearer one it can never be the answer for anything further away. Then a monotonic stack does the whole job in one pass, or a monotonic deque if old elements must also expire.
5.10 Historical Context
The stack and queue concepts emerged in the 1950s as programmers recognized common access patterns. Alan Turing’s 1949 work on subroutine linkage predated formal stack concepts, the call stack was an informal but essential mechanism.
The term “stack” became standard in the 1960s, replacing earlier terms like “pushdown list.” The queue concept was formalized alongside it.
Edsger Dijkstra’s 1968 paper on “ cooperating sequential processes“ introduced semaphores and discussed bounded buffers (producer-consumer) as fundamental synchronization problems.
Robert Hood and Robert Melville (1981) showed how to make the two-stack queue of Exercise 5.5 run in O(1) worst-case time per operation in pure Lisp, by spreading the reversal over many operations instead of doing it all at once. The problem a monotonic stack solves, finding for every element the nearest smaller value on each side, was named “all nearest smaller values” by Omer Berkman, Baruch Schieber and Uzi Vishkin (1993), who used it as a building block for fast parallel algorithms; the sequential stack algorithm was already standard by then.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
5.1 ★ Evaluate a postfix expression. Evaluate 5 1 2 + 4 * + 3 - with a stack, as in Section 5.3. Show the stack after every token, and give the infix expression it came from.
Solution
Operands are pushed; an operator pops the right operand first, then the left, and pushes the result.
| Token | Action | Stack (bottom → top) |
|---|---|---|
| 5 | push | [5] |
| 1 | push | [5, 1] |
| 2 | push | [5, 1, 2] |
| + | pop 2, pop 1, push 1 + 2 | [5, 3] |
| 4 | push | [5, 3, 4] |
| * | pop 4, pop 3, push 3 × 4 | [5, 12] |
| + | pop 12, pop 5, push 5 + 12 | [17] |
| 3 | push | [17, 3] |
| - | pop 3, pop 17, push 17 − 3 | [14] |
Result: 14. The infix form is 5 + (1 + 2) * 4 - 3. Note the pop order for -: the first value popped (3) is the right operand. Getting that backwards gives −14.
5.2 ★ Circular queue trace. Use the CircularQueue code from Section 5.5 with MAX_SIZE = 5, starting from front = rear = 0. Apply: enqueue 10, 20, 30, 40; check is_full; dequeue twice; enqueue 50, 60. Give front and rear after each step and the final contents of data. How many elements can this queue hold, and why?
Solution
| Step | front | rear | Notes |
|---|---|---|---|
| start | 0 | 0 | empty: front == rear |
| enqueue 10 | 0 | 1 | data[0] = 10 |
| enqueue 20 | 0 | 2 | data[1] = 20 |
| enqueue 30 | 0 | 3 | data[2] = 30 |
| enqueue 40 | 0 | 4 | data[3] = 40 |
| is_full | 0 | 4 | (4 + 1) % 5 == 0, so full |
| dequeue → 10 | 1 | 4 | |
| dequeue → 20 | 2 | 4 | |
| enqueue 50 | 2 | 0 | data[4] = 50, rear wraps to 0 |
| enqueue 60 | 2 | 1 | data[0] = 60; now full again |
Final data = [60, 20, 30, 40, 50], with the live queue being 30, 40, 50, 60 (from front = 2, wrapping). The 20 in data[1] is a stale value in a free slot.
The queue holds at most 4 elements, one fewer than MAX_SIZE. With front == rear meaning “empty”, a completely full array would also have front == rear, and the two states could not be told apart. Keeping one slot empty makes “full” a different condition, (rear + 1) % MAX_SIZE == front. The alternative is to store a size field (as the Deque struct in Section 5.6 does) and use all MAX_SIZE slots.
5.3 ★★ Which outputs can a stack produce? The numbers 1, 2, 3, 4 are pushed in that order, and you may pop at any time (each number is popped exactly once). Which of these output sequences are possible? For each possible one, give the push/pop sequence; for each impossible one, say where it gets stuck. Then give a simple algorithm that decides any case.
(a) 3 1 2 4 (b) 2 4 3 1 (c) 1 3 2 4 (d) 4 1 2 3
Hint
To output x, every number below x must already be pushed. Once x has been popped, whatever is on top of the stack is the only thing that can come out next, apart from numbers not pushed yet.
Solution
(a) 3 1 2 4: impossible. To output 3, push 1, 2, 3 and pop 3. The stack is now [1, 2] with 2 on top. The next output must be 1, but 1 is under 2.
(b) 2 4 3 1: possible. push 1, push 2, pop (2), push 3, push 4, pop (4), pop (3), pop (1).
(c) 1 3 2 4: possible. push 1, pop (1), push 2, push 3, pop (3), pop (2), push 4, pop (4).
(d) 4 1 2 3: impossible. Outputting 4 first leaves [1, 2, 3] with 3 on top, so the next output must be 3, not 1.
Algorithm (simulate greedily): for each wanted output x, push the next unpushed numbers until x has been pushed; then the top of the stack must be x, so pop it, otherwise the sequence is impossible.
def stack_can_produce(out):
stack, next_in = [], 1
for x in out:
while next_in <= x: # push everything up to x
stack.append(next_in)
next_in += 1
if not stack or stack[-1] != x:
return False # x is buried under something else
stack.pop()
return True
assert not stack_can_produce([3, 1, 2, 4])
assert stack_can_produce([2, 4, 3, 1])
assert stack_can_produce([1, 3, 2, 4])
assert not stack_can_produce([4, 1, 2, 3])
Greedy is safe because pushing is the only way to reach x, and popping anything other than x would output the wrong number. It runs in O(n). The forbidden pattern is “a higher number, then a low one, then a middle one” (like 3, 1, 2): out of 24 orderings of 1..4, exactly 14 are producible (in general, the Catalan number C(n)).
5.4 ★★ Shunting-yard and associativity. Convert 8 - 3 - 2 * ( 1 + 4 ) to postfix with the shunting-yard rules in Section 5.3, using precedence * / above + -. Show the operator stack and output after each token. Then show what goes wrong if an operator only pops operators of strictly higher precedence.
Hint
The interesting moment is the second -, which arrives while the first - is on the stack.
Solution
All four operators are left-associative, so an incoming operator pops everything of higher or equal precedence (stopping at a (), then pushes itself.
| Token | Operator stack | Output |
|---|---|---|
| 8 | 8 | |
| - | - | 8 |
| 3 | - | 8 3 |
| - | - | 8 3 - |
| 2 | - | 8 3 - 2 |
| * | - * | 8 3 - 2 |
| ( | - * ( | 8 3 - 2 |
| 1 | - * ( | 8 3 - 2 1 |
| + | - * ( + | 8 3 - 2 1 |
| 4 | - * ( + | 8 3 - 2 1 4 |
| ) | - * | 8 3 - 2 1 4 + |
| end | 8 3 - 2 1 4 + * - |
Postfix: 8 3 - 2 1 4 + * -, which evaluates to (8 − 3) − 2 × 5 = −5, the correct value.
With “strictly higher” only, the second - does not pop the first, and the result is 8 3 2 1 4 + * - -, which means 8 − (3 − 2 × 5) = 15. The parser has made - right-associative. For + and * the mistake is invisible (they are associative), which is why it survives testing.
A Python version with the corrected rule:
PREC = {"+": 1, "-": 1, "*": 2, "/": 2}
def to_postfix(tokens):
out, ops = [], []
for t in tokens:
if t in PREC:
# all four operators are left-associative: pop >= precedence
while ops and ops[-1] in PREC and PREC[ops[-1]] >= PREC[t]:
out.append(ops.pop())
ops.append(t)
elif t == "(":
ops.append(t)
elif t == ")":
while ops[-1] != "(":
out.append(ops.pop())
ops.pop() # discard the "("
else:
out.append(t) # operand
while ops: # end of input: flush the stack
out.append(ops.pop())
return out
assert to_postfix("8 - 3 - 2 * ( 1 + 4 )".split()) == "8 3 - 2 1 4 + * -".split()
assert to_postfix("3 + 4 * 2 / ( 1 - 5 )".split()) == "3 4 2 * 1 5 - / +".split()
A right-associative operator such as exponentiation (2 ^ 3 ^ 2 = 2^9) is the case where “strictly higher” is the correct rule.
5.5 ★★ A queue from two stacks. Implement a FIFO queue using only two stacks (Python lists used only with append and pop()), and show that any sequence of n operations takes O(n) total time, so each operation is amortized O(1), even though a single dequeue can take O(n).
Hint
Pushing a stack’s contents onto another stack reverses their order. Only do that when the second stack is empty.
Solution
class TwoStackQueue:
def __init__(self):
self.inbox = [] # receives enqueues, newest on top
self.outbox = [] # serves dequeues, oldest on top
def enqueue(self, x):
self.inbox.append(x)
def dequeue(self):
if not self.outbox:
while self.inbox: # reverse inbox into outbox
self.outbox.append(self.inbox.pop())
if not self.outbox:
raise IndexError("dequeue from empty queue")
return self.outbox.pop()
q = TwoStackQueue()
for x in (1, 2, 3):
q.enqueue(x)
assert q.dequeue() == 1 # moves 3, 2, 1 into outbox; pops 1
q.enqueue(4) # goes to inbox; outbox still has 2, 3
assert [q.dequeue(), q.dequeue(), q.dequeue()] == [2, 3, 4]
Correctness. Every element in outbox is older than every element in inbox, and outbox has the oldest element on top. Refilling only when outbox is empty preserves both facts: the transfer reverses inbox, so its oldest element ends on top.
Amortized cost. Follow a single element: it is pushed onto inbox once, popped from inbox once, pushed onto outbox once and popped from outbox once. That is at most 4 stack operations per element over its whole life, so n operations cost O(n) in total, amortized O(1) each (aggregate analysis, Chapter 1). A single dequeue that triggers a transfer of k elements costs O(k), so the worst case per operation is O(n). If you need a hard O(1) bound per operation, use the circular queue from Section 5.5 instead. The two-stack queue earns its keep where only stacks are cheap, for example in purely functional languages where an immutable list is a stack.
5.6 ★★ Bounded undo history. The editor in Section 5.3 saves a full state on every action and never forgets any. You must cap it at the last 100 states: when a 101st is saved, the oldest is discarded. Undo still restores the newest state. Which structure should hold the undo history, and why not the array-based Stack from Section 5.2?
Solution
The history now needs two operations at different ends: push and pop at the newest end (save and undo), and remove at the oldest end (discard when over the limit). That is a deque, not a stack.
- Array-based
Stack: discarding the bottom element means shifting all 99 others down, O(n) per action. It works for 100 entries but scales badly and is the wrong shape. - Linked list stack: the bottom node is at the far end of a singly linked chain, so removing it needs a walk (Exercise 4.2). A doubly linked list with head and tail pointers works, at the cost of a node allocation per action.
- Circular buffer of capacity 100 (Section 5.5): save writes at
rearand, if the buffer is full, advancesfrontto drop the oldest; undo stepsrearback by one. Every operation is O(1), there is no allocation after setup, and memory is fixed at 100 slots. This is the right choice.
Python’s collections.deque(maxlen=100) is exactly this:
from collections import deque
undo = deque(maxlen=3) # 3 instead of 100 to keep the example short
for state in ["a", "b", "c", "d", "e"]:
undo.append(state) # appending to a full deque drops the oldest
assert list(undo) == ["c", "d", "e"]
assert undo.pop() == "e" # undo restores the newest state
The redo stack needs no cap: it can never hold more than the undo history did, and it is cleared on every new action.
5.7 ★★★ Longest run with bounded spread. Given an array a and a number limit ≥ 0, find the length of the longest contiguous run a[lo : hi + 1] whose maximum minus minimum is at most limit, in O(n). For example, a = [10, 1, 2, 4, 7, 2] with limit 5 gives 4, for the run [2, 4, 7, 2].
Hint
Combine the variable-size sliding window of Chapter 3 (Section 3.7) with the monotonic deque of Section 5.9. The window needs both its maximum and its minimum.
Solution
Why a sliding window works. Shrinking a run cannot increase its spread and growing it cannot decrease it. So for each right end hi the valid left ends form a range ending at hi, and the smallest valid left end never moves left as hi grows. That is the same monotonicity shortest_at_least relies on in Chapter 3: grow on the right, and shrink from the left only while the window is invalid.
Maintaining max and min. Keep two monotonic deques of indices: maxq with values strictly decreasing (its front is the window maximum, exactly as in window_max) and minq with values strictly increasing (its front is the minimum). When lo advances past a deque’s front index, pop that front.
from collections import deque
def longest_bounded(a, limit):
"""Length of the longest run a[lo:hi+1] with max - min <= limit."""
maxq, minq = deque(), deque() # indices; values decreasing / increasing
best = lo = 0
for hi, x in enumerate(a):
while maxq and a[maxq[-1]] <= x:
maxq.pop()
maxq.append(hi)
while minq and a[minq[-1]] >= x:
minq.pop()
minq.append(hi)
while a[maxq[0]] - a[minq[0]] > limit: # shrink from the left
lo += 1
if maxq[0] < lo:
maxq.popleft()
if minq[0] < lo:
minq.popleft()
best = max(best, hi - lo + 1)
return best
assert longest_bounded([10, 1, 2, 4, 7, 2], 5) == 4
assert longest_bounded([8, 2, 4, 7], 4) == 2
assert longest_bounded([], 3) == 0
The shrink loop never empties a deque: both always contain hi, and once lo reaches hi the spread is 0.
Trace for the example (deques shown as values):
| hi | a[hi] | maxq | minq | lo | best |
|---|---|---|---|---|---|
| 0 | 10 | [10] | [10] | 0 | 1 |
| 1 | 1 | [1] | [1] | 1 | 1 |
| 2 | 2 | [2] | [1, 2] | 1 | 2 |
| 3 | 4 | [4] | [1, 2, 4] | 1 | 3 |
| 4 | 7 | [7] | [2, 4, 7] | 2 | 3 |
| 5 | 2 | [7, 2] | [2] | 2 | 4 |
At hi = 1 the spread 10 − 1 = 9 is too large, so lo moves to 1 and the 10 leaves maxq. At hi = 4 the spread 7 − 1 = 6 is too large, so lo moves to 2 and the 1 leaves minq.
Cost. Each index enters and leaves each deque at most once, and lo advances at most n times in total, so the whole run is O(n) in the worst case, amortized O(1) per element. A brute force over all O(n²) runs, each scanned for its spread, is O(n³).
5.8 ★★ Sum of subarray minimums. The array [3, 1, 2, 4] has 10 contiguous subarrays, and the sum of their minimums is 17. Compute this sum for any array in O(n). Be careful with duplicate values: check your method on [2, 2], whose answer is 6.
Hint
Turn it around: for each i, count the subarrays whose minimum is a[i]. They can stretch left and right until they meet a smaller value.
Solution
Let left[i] be the nearest index before i with a smaller value (or −1) and right[i] the nearest index after i with a smaller value (or n). Then a[i] is the minimum of every subarray a[l : r + 1] with left[i] < l ≤ i ≤ r < right[i], and there are (i − left[i]) × (right[i] − i) of them. The answer is the sum of a[i] times that count.
Duplicates. If both boundaries stop only at strictly smaller values, a subarray whose minimum appears twice is counted once for each copy. On [2, 2] that gives 2 × 1 × 2 + 2 × 2 × 1 = 8, because [2, 2] is counted twice. The fix is to make one side non-strict: left[i] stops at a value < a[i], but right[i] stops at a value ≤ a[i]. Each subarray is then credited to the rightmost position of its minimum only, and [2, 2] gives 2 × 1 × 1 + 2 × 2 × 1 = 6.
One monotonic stack pass computes both arrays: when j pops i (because a[i] ≥ a[j]), j is i’s next index with a value ≤ a[i]; after the pops, the top of the stack is j’s previous index with a strictly smaller value.
def sum_subarray_mins(a):
n = len(a)
left, right = [-1] * n, [n] * n
stack = [] # indices; values strictly increasing
for j, x in enumerate(a):
while stack and a[stack[-1]] >= x: # j is the next index with a value <= a[i]
right[stack.pop()] = j
left[j] = stack[-1] if stack else -1 # last index with a value < a[j]
stack.append(j)
return sum(a[i] * (i - left[i]) * (right[i] - i) for i in range(n))
assert sum_subarray_mins([3, 1, 2, 4]) == 17
assert sum_subarray_mins([2, 2]) == 6
For [3, 1, 2, 4]: left = [-1, -1, 1, 2] and right = [1, 4, 4, 4], so the contributions are 3 × 1 × 1 = 3, 1 × 2 × 3 = 6, 2 × 1 × 2 = 4 and 4 × 1 × 1 = 4, which sum to 17. The pass is O(n) worst case by the argument of Section 5.9; summing the minimums of all O(n²) subarrays directly, extending each start to the right while tracking the minimum, is O(n²).
5.9 ★★ Largest rectangle of 1s. Given a 0/1 matrix with R rows and C columns, find the area of the largest rectangle that contains only 1s, in O(RC) time. Apply it to:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Hint
Fix the row that the rectangle’s bottom edge sits on. What does the matrix above that row look like, column by column?
Solution
For row r, let heights[c] be the number of consecutive 1s in column c ending at row r (0 if the cell is 0). An all-1 rectangle whose bottom edge is on row r is exactly a rectangle under the histogram heights, so the answer is the largest result of largest_rectangle (Section 5.9) over all rows. Each row updates heights in O(C) (add 1, or reset to 0) and runs one O(C) histogram pass, for O(RC) in total, with O(C) extra space.
def maximal_rectangle(grid):
"""Area of the largest all-1 rectangle in a 0/1 matrix."""
if not grid:
return 0
heights = [0] * len(grid[0])
best = 0
for row in grid:
heights = [h + 1 if cell else 0 for h, cell in zip(heights, row)]
best = max(best, largest_rectangle(heights))
return best
| Row | heights | Largest rectangle under it |
|---|---|---|
| 0 | [1, 0, 1, 0, 0] | 1 |
| 1 | [2, 0, 2, 1, 1] | 3 |
| 2 | [3, 1, 3, 2, 2] | 6 |
| 3 | [4, 0, 0, 3, 0] | 4 |
The answer is 6: rows 1 and 2, columns 2 to 4. At row 2 the best histogram rectangle has height 2 and spans the last three bars (heights 3, 2, 2). Checking every rectangle directly would take O(R²C²) candidates, each needing a check of its cells (or O(1) each with the 2-D prefix sums of Chapter 3).
Where this connects
- Chapter 9: Heaps and Priority Queues. The priority queue, when FIFO and LIFO are both the wrong order
- Chapter 21: Algorithm Design Using Data Structures. The stack as the implicit structure behind all recursion
- Chapter 23: Advanced Competitive Programming Data Structures. Cartesian trees, built in O(n) with the monotonic stack of Section 5.9
Chapter 6: Tree Fundamentals and Binary Trees
6.1 The Tree Abstraction
A tree is a hierarchical data structure consisting of nodes connected by edges, with a single root node from which all other nodes are reachable. Trees model many natural hierarchies: organizational charts, file systems, family genealogies, and evolutionary relationships.
Formal Definition: A tree T is a connected acyclic graph. Equivalently, a tree is a set of nodes where:
- There is a distinguished root node r
- Every node (except r) has exactly one parent
- There is a unique path from r to any node
6.2 Tree Terminology
A (Root, Depth 0)
/|\
/ | \
B C D
/| | \
/ | | \
E F G H
/ |
I J
|
(I is descendant of E, B, A; ancestor of itself)
Key Terms:
- Root: The node with no parent (A)
- Parent: Node with children below it (B is parent of E and F)
- Child: Node with parent above it (E and F are children of B)
- Sibling: Nodes with same parent (E and F are siblings)
- Leaf: Node with no children (I, G, H, J)
- Internal node: Node with at least one child (A, B, C, D, E, F)
- Depth: Number of edges from root to node (I has depth 3)
- Height: Number of edges on longest path from node to leaf
- Level: All nodes at same depth
- Path: Sequence of nodes connected by edges
- Subtree: Node and all its descendants
6.3 Tree Properties
For a tree with n nodes:
- Exactly n-1 edges (each node except root has one edge to its parent)
- A binary tree with maximum nodes for a given height is “perfect”
- A tree with minimum height for a given n is “balanced”
The Handshaking Lemma: In any tree: Σ degree(v) = 2(n-1) This follows because each of the n-1 edges contributes 2 to the degree sum.
6.4 Binary Trees
A binary tree is a tree where each node has at most two children, distinguished as left and right.
struct TreeNode {
element_type data;
struct TreeNode *left;
struct TreeNode *right;
};
Types of Binary Trees
Full (Proper) Binary Tree: Every node has 0 or 2 children:
○
/ \
○ ○
/ \
○ ○
Complete Binary Tree: All levels filled except possibly the last, filled left to right:
○
/ \
○ ○
/\ /\
○ ○ ○ ○
Perfect Binary Tree: All internal nodes have 2 children; all leaves at same level:
○
/ \
○ ○
/\ /\
○ ○ ○ ○
Balanced Binary Tree: Height of left and right subtrees differs by at most 1:
○ ○
/ \ / \
○ ○ is balanced ○ ○
/ \
○ ○
6.5 Binary Tree Representations
Pointer-Based Representation
struct Node {
element_type data;
struct Node *left;
struct Node *right;
};
Simple, natural, widely used.
Array Representation (For Complete Trees)
For complete binary trees, store nodes level-by-level in an array:
Array indices:
0
/ \
1 2
/\ /\
3 4 5 6
Array: [A, B, C, D, E, F, G]
Parent(i) = (i - 1) / 2
Left(i) = 2 * i + 1
Right(i) = 2 * i + 2
This representation is space-efficient for complete trees and is used for heaps.
Left-Child Right-Sibling Representation
Convert any general tree to binary tree:
struct GeneralNode {
element_type data;
struct GeneralNode *first_child;
struct GeneralNode *next_sibling;
};
The binary tree has:
- left pointer → first child
- right pointer → next sibling
6.6 Tree Traversals
Traversal is visiting each node in a systematic order.
Preorder (Root, Left, Right)
def preorder(node):
if node is None: return
visit(node) # Process root first
preorder(node.left) # Then all left subtree
preorder(node.right) # Then all right subtree
Use cases: Copy tree, prefix notation, directory listing
Inorder (Left, Root, Right)
def inorder(node):
if node is None: return
inorder(node.left) # Left subtree
visit(node) # Process root
inorder(node.right) # Right subtree
Use cases: BST in sorted order, infix expression evaluation
Postorder (Left, Right, Root)
def postorder(node):
if node is None: return
postorder(node.left) # Left subtree
postorder(node.right) # Right subtree
visit(node) # Process root last
Use cases: Delete tree, postfix evaluation, computing directory sizes
Level Order (Breadth-First)
from collections import deque
def level_order(root):
if root is None: return
queue = deque([root])
while queue:
node = queue.popleft()
visit(node)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
Use cases: Shortest path in unweighted graph, level-by-level processing
Iterative Traversals with an Explicit Stack
The recursive traversals keep their bookkeeping on the call stack, one frame per level, so they need O(h) stack space. On a degenerate tree h is n − 1, and CPython’s default recursion limit of 1000 frames means the recursive inorder raises RecursionError on a chain of about a thousand nodes. In C the same code overflows the thread’s stack. Moving the stack into a list fixes this without changing the asymptotics: still O(n) time and O(h) space, but the space is ordinary heap memory.
Preorder is the easiest: pop a node, visit it, push its children. Push the right child first so that the left one is popped first.
def preorder_iter(root):
stack = [root] if root else []
while stack:
node = stack.pop()
visit(node)
if node.right: stack.append(node.right) # pushed first, popped second
if node.left: stack.append(node.left)
(Replace the stack with a queue, append left before right, and this becomes level_order. Depth-first and breadth-first differ only in the container.)
Inorder cannot visit a node when it first meets it; it has to go down the left side first and come back. The stack holds exactly the nodes whose left subtree is in progress and which have not been visited yet:
def inorder_iter(root):
stack, node = [], root
while stack or node:
while node: # run down the left spine, saving the path
stack.append(node)
node = node.left
node = stack.pop() # leftmost node not yet visited
visit(node)
node = node.right # then its right subtree
On the tree 4 (children 2 and 5), 2 (children 1 and 3):
push 4, 2, 1 stack [4, 2, 1]
pop 1, visit 1 1 has no right child
pop 2, visit 2 go to 2.right = 3: push 3, stack [4, 3]
pop 3, visit 3 stack [4]
pop 4, visit 4 go to 4.right = 5: push 5, stack [5]
pop 5, visit 5 stack empty, node None: done output 1 2 3 4 5
Every node is pushed once and popped once, so the whole traversal is O(n) and the stack never holds more than h + 1 nodes. Split the loop at visit and you have an iterator whose next() is amortized O(1): this is the standard way to iterate over a BST without parent pointers (Chapter 7, Section 7.4).
Postorder is the hardest, because the traversal comes back up to each node twice: once from its left subtree (when it must go right instead of visiting) and once from its right subtree. Remember the last node visited to tell the two apart:
def postorder_iter(root):
stack, node, last = [], root, None
while stack or node:
while node:
stack.append(node)
node = node.left
top = stack[-1]
if top.right and top.right is not last:
node = top.right # right subtree not done yet: go there first
else:
visit(top) # both subtrees done
last = stack.pop()
If top has a right child and we did not just finish it, we are coming back from the left, so we descend right. Otherwise both subtrees are done (the right one was the last thing visited, or there is none), and top is visited. A common shortcut runs preorder with the children pushed in the opposite order (root, right, left) and reverses the output. That is correct, but it holds all n results before producing the first one, so it is no use as a streaming iterator.
Morris Traversal (Threaded Binary Tree)
O(1) space traversal using existing tree structure:
def morris_inorder(root):
current = root
while current:
if current.left is None:
visit(current)
current = current.right
else:
# Find inorder predecessor (rightmost in left subtree)
pre = current.left
while pre.right and pre.right != current:
pre = pre.right
if pre.right is None:
pre.right = current # Create thread
current = current.left
else:
pre.right = None # Remove thread
visit(current)
current = current.right
6.7 The Recursive Tree Function Pattern
Many questions about a binary tree have the same shape: the answer for a node can be computed from the answers for its two children. Height, size, sum of keys, “is it balanced”, “is it a BST”, “how long is the longest path”. The pattern is a single postorder function that returns, for each subtree, a tuple of everything the parent will need:
- Decide what the parent needs to know about a subtree. Sometimes that is more than the final answer.
- Return that tuple for the empty tree (the base case).
- For a node, recurse on both children, then combine their tuples and the node itself into the node’s tuple.
Correctness is a direct induction on the tree: if the two recursive calls return correct tuples for the children’s subtrees, the combine step produces a correct tuple for the node’s subtree. Cost: every node is visited once and the combine step is O(1), so the whole pass is O(n) time and O(h) stack.
Example: height, size and diameter in one pass. The diameter is the number of edges on the longest path between any two nodes. That path bends at exactly one node, its highest, and the longest path bending at a node goes down to the deepest point in each of its subtrees: left height + right height + 2 edges (counting an empty subtree’s height as −1). But the longest path in the whole tree need not bend at the root, so the parent needs two things from each child: the height (a path the parent can extend) and the best diameter found so far (a finished answer it can only compare against).
def summary(node):
"""(height, size, diameter) of the subtree. Height of an empty tree is -1."""
if node is None:
return -1, 0, 0
lh, ls, ld = summary(node.left)
rh, rs, rd = summary(node.right)
through = lh + rh + 2 # longest path that bends at this node
return 1 + max(lh, rh), 1 + ls + rs, max(ld, rd, through)
On this tree the longest path, 5-3-2-4-6, does not touch the root:
1 node (height, size, diameter)
/ 5 (0, 1, 0)
2 3 (1, 2, 1) through = 0 + (-1) + 2
/ \ 6 (0, 1, 0)
3 4 4 (1, 2, 1)
/ \ 2 (2, 5, 4) through = 1 + 1 + 2
5 6 1 (3, 6, 4) through = 2 + (-1) + 2 = 3 < 4
The tempting alternative, calling a separate height() at every node to compute through, gives the same answer but recomputes each subtree’s height once per ancestor: O(n²) on a long chain. Returning the height alongside the answer is what makes the pass linear. Exercise 6.5 uses the same idea for balance checking, and Chapter 7, Section 7.7 maintains subtree sizes in a BST this way.
This is how compilers compute synthesized attributes (a type or constant value for each expression node, from its children’s), how du totals directory sizes, and how dynamic programming on trees is usually written.
6.8 Reconstructing a Tree from Traversals
One traversal sequence does not determine a binary tree: the keys 1, 2, 3 in inorder could come from five different shapes. Two traversals can, if one of them is inorder and the keys are distinct.
Preorder + inorder. The first preorder key is the root. Find it in the inorder sequence: the keys to its left form the left subtree and the keys to its right form the right subtree. In preorder the root is followed by the whole left subtree and then the whole right subtree, so the next keys in preorder belong to the left subtree, and their count is known from the inorder split. Recurse on each side. Since every step is forced, the tree is unique.
With preorder A B D E C F and inorder D B E A F C: the root is A, with D B E on its left and F C on its right. The left subtree’s preorder is B D E, so its root is B, with D left of B and E right of it in inorder. The right subtree’s preorder is C F; F is left of C in inorder, so F is C’s left child:
A
/ \
B C
/ \ /
D E F
As code, a position map makes each split O(1), and a single iterator over the preorder sequence is enough because the recursion builds nodes in exactly preorder order (root, then all of the left subtree, then the right):
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def build(preorder, inorder):
pos = {key: i for i, key in enumerate(inorder)}
it = iter(preorder)
def go(lo, hi): # build the subtree whose keys are inorder[lo:hi]
if lo >= hi:
return None
node = Node(next(it)) # next preorder key is this subtree's root
mid = pos[node.key]
node.left = go(lo, mid)
node.right = go(mid + 1, hi)
return node
return go(0, len(inorder))
This is O(n) time. Searching the inorder list for each root instead of using pos costs O(n log n) on a balanced tree but O(n²) on a chain. Postorder + inorder works the same way, with the root at the end (Exercise 6.3), and so does level order + inorder. Duplicate keys break all of these, because the root’s position in inorder is no longer determined.
Preorder + postorder is not enough in general. Both sequences put a node next to its subtree, but neither says on which side a lone child hangs. The tree “1 with left child 2” and the tree “1 with right child 2” both have preorder 1 2 and postorder 2 1. In general, if k nodes have exactly one child, all 2^k ways of choosing their sides give the same pair of sequences. Inorder is what separates them (2 1 versus 1 2). For a full binary tree, where every node has 0 or 2 children, the ambiguity cannot arise and preorder + postorder does determine the tree: the key after the root in preorder is the left child, and its position in postorder marks where the left subtree ends.
6.9 Serialization and Deserialization
Writing a tree to a file, a socket or a cache, and reading back the identical tree, needs a flat format that records the shape as well as the keys. Section 6.8 used two traversals for that; a single traversal is enough if it also writes a marker for every empty child.
Preorder with null markers:
def serialize(node, out):
if node is None:
out.append('#')
return
out.append(str(node.key))
serialize(node.left, out)
serialize(node.right, out)
def deserialize(tokens):
it = iter(tokens)
def go():
tok = next(it)
if tok == '#':
return None
node = Node(tok) # keys come back as strings
node.left = go() # the left subtree's tokens come next...
node.right = go() # ...then the right subtree's
return node
return go()
The tree of Section 6.8 serializes as A B D # # E # # C F # # #. deserialize reads the tokens in the order serialize wrote them, and by induction each call to go consumes exactly the tokens written for one subtree: a # ends a branch, so no sizes or end markers are needed. A tree with n nodes has n + 1 empty child slots (2n pointer fields, n − 1 of them used by edges), so the output is n keys plus n + 1 markers, and both directions are O(n). Unlike Section 6.8, duplicate keys are fine. Keys are written with str and read back as strings; a real format must encode keys so that they round-trip with their type and cannot be confused with the marker or the separator (escaping, or a length prefix).
Other choices. Level order with null markers is the format LeetCode uses ([1,2,3,null,null,4,5], with trailing nulls dropped); it can be read back with a queue and has no recursion depth problem. Inorder with markers does not work: # A # B # is both “A with right child B” and “B with left child A”, because inorder does not say which key is the parent. For a complete tree, the array layout of Section 6.5 needs no markers at all. And the markers cost little: writing 1 for a node and 0 for an empty slot in preorder records any shape in 2n + 1 bits. That is close to optimal, since there are C(2n, n)/(n + 1) binary tree shapes with n nodes (the Catalan number), roughly 4^n / n^1.5 of them, so any encoding needs about 2n bits. Succinct tree representations (Jacobson, 1989) build on such bit sequences, adding small indexes so that parent and child can be found without decoding the whole tree.
6.10 Expression Trees
Binary expression trees represent arithmetic expressions:
Expression: (3 + 4) * (2 - 1)
*
/ \
+ -
/ \ / \
3 4 2 1
Preorder (prefix): * + 3 4 - 2 1
Inorder (infix): 3 + 4 * 2 - 1 (needs parentheses for correctness)
Postorder (postfix): 3 4 + 2 1 - *
6.11 Binary Space Partitioning Trees
BSP trees recursively divide space with hyperplanes:
│ │
─────┼───── ───────┼──────
│ partition │ partition
─────┼───── ───────┼──────
│ │
Used in:
- 3D graphics (visibility determination)
- Ray tracing
- Collision detection
- CAD systems
6.12 Historical Context
Trees as mathematical structures predate computers. Graph theory, including trees, was studied in the 19th century by Kirchhoff, Cayley, and others. Arthur Cayley (1857) enumerated rooted trees, and in 1889 published what we now call “Cayley’s formula”: there are n^(n-2) labeled trees on n nodes.
The binary tree became central to computer science through:
- Syntax trees in compilers (1950s)
- Binary search trees (1960s)
- Balanced tree variants (1970s)
- B-trees for databases (1970s)
Knuth’s The Art of Computer Programming, Volume 1 (1968), Section 2.3.1, gives inorder traversal with an explicit stack as Algorithm T. The bottom-up computation of Section 6.7 was formalized for compilers in Knuth’s “Semantics of Context-Free Languages” (1968), which introduced synthesized and inherited attributes. Guy Jacobson’s “Space-efficient static trees and graphs” (FOCS 1989) started the study of succinct trees that use about 2n bits for the shape.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
6.1 ★ Read the terminology tree. Use the tree in Section 6.2 (A has children B, C, D; B has E and F; C has G; D has H; E has I; F has J). Give (a) the height of the whole tree, (b) the height of B, (c) the depth of J, (d) the number of edges, and (e) the sum of the degrees of all nodes, treating the tree as an undirected graph. Check (d) and (e) against Section 6.3.
Solution
(a) The longest root-to-leaf paths are A→B→E→I and A→B→F→J, each 3 edges, so the height is 3.
(b) From B the longest downward path is B→E→I (or B→F→J): height 2.
(c) J is reached by A→B→F→J: depth 3.
(d) There are 10 nodes, so 9 edges. Counting directly: every node except A has exactly one edge to its parent, which is 9.
(e) Degrees (parent edge plus child edges): A 3, B 3, C 2, D 2, E 2, F 2, G 1, H 1, I 1, J 1. The sum is 18 = 2 × 9 = 2(n − 1), as the handshaking lemma says.
6.2 ★ Four traversals. Write the preorder, inorder, postorder and level-order sequences for this tree.
F
/ \
B G
/ \ \
A D I
/ \ /
C E H
Solution
- Preorder (root, left, right): F B A D C E G I H
- Inorder (left, root, right): A B C D E F G H I
- Postorder (left, right, root): A C E D B H I G F
- Level order: F B G A D I C E H
The inorder sequence comes out alphabetical because this tree happens to obey the BST property of Chapter 7. Preorder always starts with the root and postorder always ends with it, which is the fact the next exercise relies on.
6.3 ★★ Rebuild a tree from postorder and inorder. A binary tree with distinct keys has postorder 7 4 2 5 8 6 3 1 and inorder 4 7 2 1 5 3 8 6. Draw the tree and give its preorder. Then adapt build from Section 6.8 to take postorder instead of preorder.
Hint
The last postorder key is the root. Read postorder backwards and it lists the root, then the whole right subtree, then the whole left subtree.
Solution
Root is 1 (last in postorder). In the inorder sequence, 4 7 2 is left of 1 and 5 3 8 6 is right of it. The left subtree has 3 keys, so it owns the first 3 postorder keys, 7 4 2, and the right subtree owns 5 8 6 3.
- Left part: postorder
7 4 2, root 2. Inorder4 7lies left of 2, so 2 has only a left subtree, with postorder7 4: its root is 4, and 7 is right of 4 in inorder, so 7 is 4’s right child. - Right part: postorder
5 8 6 3, root 3. Inorder5is left of 3 and8 6is right. So 5 is 3’s left child; the right subtree has postorder8 6, root 6, with 8 to its left in inorder, so 8 is 6’s left child.
1
/ \
2 3
/ / \
4 5 6
\ /
7 8
Preorder: 1 2 4 7 3 5 6 8.
In code, walk the postorder sequence backwards and build the right subtree before the left, because that is the order reversed postorder lists them in:
def build_post(postorder, inorder):
pos = {key: i for i, key in enumerate(inorder)}
it = reversed(postorder) # root, right subtree, left subtree
def go(lo, hi):
if lo >= hi:
return None
node = Node(next(it))
mid = pos[node.key]
node.right = go(mid + 1, hi) # right first
node.left = go(lo, mid)
return node
return go(0, len(inorder))
Building the left subtree first would be wrong: the next key from the reversed iterator is the root of the right subtree. Like build, this is O(n).
6.4 ★★ Array layout. A complete binary tree with n = 12 nodes is stored in an array using the formulas in Section 6.5. (a) Which indices hold leaves? (b) Which internal node has only one child, and what is it? (c) Prove that for any n, the leaves are exactly the indices ⌊n/2⌋ through n − 1. (d) If you used the same formulas for a right-leaning chain of 5 nodes, how large must the array be?
Hint
A node at index i is a leaf exactly when its left child index 2i + 1 is past the end of the array.
Solution
(a) Index i is a leaf when 2i + 1 ≥ 12, that is i ≥ 5.5, so indices 6 through 11 are leaves and 0 through 5 are internal.
(b) Index 5 has left child 2·5 + 1 = 11 (present) and right child 12 (absent). So index 5 has one child, index 11. In a complete tree at most one node can be in this position.
(c) i is internal iff 2i + 1 ≤ n − 1, iff i ≤ (n − 2)/2, iff i ≤ ⌊n/2⌋ − 1. So the internal nodes are 0 through ⌊n/2⌋ − 1 and the leaves are ⌊n/2⌋ through n − 1. This is why build_heap in Chapter 9 starts its loop at n/2 − 1: every larger index is a leaf and already a valid heap.
(d) Following right children from the root visits indices 0, 2, 6, 14, 30 (each is 2i + 2). The array needs 31 slots to hold 5 nodes. In general a chain of height h needs 2^(h+1) − 1 slots, which is why the array layout is reserved for complete trees.
6.5 ★★ Find the bug. The balanced-tree definition in Section 6.4 must hold at every node. This check is meant to test it:
def height(node):
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
def is_balanced(node):
if node is None:
return True
return abs(height(node.left) - height(node.right)) <= 1
Give a tree on which it returns the wrong answer, then write a correct version that runs in O(n).
Hint
It only looks at the root. Build a tree whose root is fine but whose children are not. For the O(n) version, compute heights and balance in the same pass.
Solution
The function compares the two subtree heights at the root and never recurses. This tree has left and right subtrees of height 2 each, so it returns True, but node 2 has a left subtree of height 1 and an empty right subtree (height −1), a difference of 2:
1
/ \
2 3
/ \
4 5
/ \
6 7
Adding the recursive calls (... and is_balanced(node.left) and is_balanced(node.right)) fixes correctness but recomputes heights at every level, which is O(n²) on a long chain. Returning the height and the verdict together is O(n), since each node is visited once:
def balanced_height(node):
"""Height of the subtree, or None if any node in it is unbalanced."""
if node is None:
return -1
lh = balanced_height(node.left)
if lh is None:
return None
rh = balanced_height(node.right)
if rh is None or abs(lh - rh) > 1:
return None
return 1 + max(lh, rh)
def is_balanced(node):
return balanced_height(node) is not None
6.6 ★★ Evaluate and print an expression tree. Using the node layout from this chapter (operators at internal nodes, numbers at leaves), write evaluate(node) and to_infix(node), where to_infix adds the parentheses that Section 6.10 says plain inorder is missing. On the tree for (3 + 4) * (2 - 1) they should return 7 and ((3 + 4) * (2 - 1)). Which traversal order does each function use?
Solution
def evaluate(node):
if node.left is None and node.right is None:
return node.key # a number
a = evaluate(node.left)
b = evaluate(node.right)
if node.key == '+': return a + b
if node.key == '-': return a - b
if node.key == '*': return a * b
if node.key == '/': return a / b
raise ValueError(node.key)
def to_infix(node):
if node.left is None and node.right is None:
return str(node.key)
return '(' + to_infix(node.left) + ' ' + node.key + ' ' + to_infix(node.right) + ')'
evaluate is a postorder traversal: both operands must be computed before the operator at the root can be applied, which is exactly how a stack machine runs 3 4 + 2 1 - *. to_infix is an inorder traversal with a parenthesis emitted before the left subtree and after the right one.
The parentheses matter because two different trees can have the same plain inorder sequence. 8 - 3 - 2 is the inorder of both ((8 - 3) - 2), which is 3, and (8 - (3 - 2)), which is 7.
6.7 ★★★ Why Morris traversal is linear. The inner while loop of morris_inorder walks from current.left down the right pointers to find the predecessor. That walk can be long, and it happens twice per node with a left child. Prove that the total number of inner-loop steps over the whole traversal is at most 2(n − 1), so the traversal is O(n) time. Also argue that the tree is unchanged when the function returns.
Hint
Every step of the inner loop follows a real tree edge of the form (u, u.right). Ask: for how many different values of current can that particular edge be on the walk?
Solution
Which edges a walk uses. When current = c has a left child, the walk starts at c.left and follows right pointers. It stops at the node whose right is either None or a thread back to c, and it never follows that last pointer. So every step it takes is along a real tree edge (u, u.right), and those edges form the right spine of c’s left subtree.
Each edge belongs to one spine. Take a tree edge (u, u.right). Walk up from u while the current node is a right child of its parent. You stop at a node w that is either the root or a left child of some parent c. If w is the root, the edge is on no left subtree’s right spine. Otherwise the edge is on the right spine of c’s left subtree and on no other, because that upward walk is deterministic. So each tree edge is charged to at most one c.
Each spine is walked twice. For a given c, the walk happens once on the first visit (creating the thread) and once when current returns to c through that thread (removing it). Both walks take the same edges.
So the inner loop takes at most 2 steps per tree edge, and there are n − 1 edges: at most 2(n − 1) steps in total. The outer loop moves current once per iteration, and each node becomes current at most twice (on arrival, and on return via its thread if it has a left child), so the outer loop is also O(n). Total: O(n) time, O(1) extra space.
The tree is restored. A thread is created only on the first visit to c (when the predecessor’s right is None) and is removed on the second visit, before current moves to c.right. Every node with a left child is visited twice (traversal enters its left subtree and must come back through the thread to leave it), so every thread created is also removed. The bound is tight up to constants: for a root whose left subtree is a right-leaning chain of n − 1 nodes, the walks take 2(n − 2) steps.
6.8 ★★ Serialize a BST without markers. Section 6.9 needs n + 1 null markers to record a tree’s shape. For a binary search tree (Chapter 7) the plain preorder sequence of keys is enough. (a) Show that inserting the keys of a BST’s preorder sequence, in that order, into an empty BST rebuilds exactly the same tree. (b) That takes O(nh) time. Write an O(n) deserializer instead, and rebuild the tree with preorder 8 3 1 6 4 7 10 14 13.
Hint
For (b), pass down the open interval of keys that may appear in the current subtree, as in the BST validator of Chapter 7, Section 7.6. The next preorder key belongs to the current subtree exactly when it falls in that interval.
Solution
(a) Preorder lists every node after all of its ancestors. So when key x is inserted, all of x’s ancestors in the original tree are already present, and by induction they sit in their original positions. The search for x starts at the root and at each node takes the same branch it would take in the original tree, so it passes through x’s ancestors in order and ends at x’s original parent, whose child slot on x’s side is still empty because x’s descendants come after x in preorder. So x lands in its original position.
(b) The bounds tell each call when its subtree has ended, so no markers are needed:
def bst_from_preorder(keys):
i = 0
def go(lo, hi): # build the subtree whose keys lie in (lo, hi)
nonlocal i
if i == len(keys) or not (lo < keys[i] < hi):
return None
node = Node(keys[i])
i += 1
node.left = go(lo, node.key)
node.right = go(node.key, hi)
return node
return go(float('-inf'), float('inf'))
Each call either consumes a key or returns None at once, and each node makes two calls, so there are at most 2n + 1 calls: O(n). On 8 3 1 6 4 7 10 14 13: 8 is the root; 3 is in (−∞, 8), so it is 8’s left child; 1 is in (−∞, 3), left of 3; 6 is not in (−∞, 1) or (1, 3), so 1 and its subtree end and 6 becomes 3’s right child, in (3, 8); 4 and 7 become 6’s children; 10 fails every interval below 8, so it becomes 8’s right child; 14 is 10’s right child and 13 is 14’s left child. That is the example tree of Chapter 7, Section 7.1.
The saving is real: the shape of a BST is fixed by its keys and the order they were inserted in, and preorder is one order that reproduces it.
6.9 ★★ The largest BST inside a binary tree. Using the pattern of Section 6.7, write a function that returns the number of nodes in the largest subtree (a node together with all its descendants) that satisfies the BST property, in O(n) time. What tuple does each call return?
Hint
A node’s subtree is a BST when both children’s subtrees are BSTs, the left subtree’s maximum is smaller than the node’s key, and the right subtree’s minimum is larger. So each call must report whether it is a BST, its size, its minimum and maximum, and the best answer found inside it.
Solution
def bst_info(node):
"""(size if this subtree is a BST else -1, min key, max key, largest BST size inside)."""
if node is None:
return 0, None, None, 0
ls, lmin, lmax, lbest = bst_info(node.left)
rs, rmin, rmax, rbest = bst_info(node.right)
if (ls >= 0 and rs >= 0
and (lmax is None or lmax < node.key)
and (rmin is None or node.key < rmin)):
size = ls + rs + 1
lo = lmin if lmin is not None else node.key
hi = rmax if rmax is not None else node.key
return size, lo, hi, size
return -1, None, None, max(lbest, rbest)
def largest_bst(root):
return bst_info(root)[3]
The tuple carries two kinds of information, as in summary: things the parent combines (whether the subtree is a BST, its size, its key range) and a finished answer it only compares (the best size inside). A subtree that is not a BST cannot be part of a larger BST, so its min and max are never needed and are returned as None. Each node is visited once with O(1) work: O(n) time, O(h) stack. Checking each node with a separate validator instead would cost O(n) per node, O(n²) in total.
Where this connects
- Chapter 7: Binary Search Trees. Adding an ordering invariant to the tree
- Chapter 20: Data Structure Design Patterns. The composite and iterator patterns these traversals exemplify
Chapter 7: Binary Search Trees
7.1 The BST Property
A Binary Search Tree maintains elements in sorted order:
For every node:
- All nodes in left subtree have keys < node's key
- All nodes in right subtree have keys > node's key
Example:
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
Inorder traversal: 1, 3, 4, 6, 7, 8, 10, 13, 14 (sorted!)
7.2 BST Operations
Search
def bst_search(node, key):
if node is None or node.key == key:
return node
if key < node.key:
return bst_search(node.left, key)
return bst_search(node.right, key)
Time: O(h) where h is height. Worst case O(n) for degenerate tree.
Insertion
def bst_insert(root, key):
if root is None:
return TreeNode(key)
if key < root.key:
root.left = bst_insert(root.left, key)
else:
root.right = bst_insert(root.right, key)
return root
Insert as leaf; find position by following search path.
Deletion
Three cases:
- Leaf node: Simply remove
- One child: Replace node with its child
- Two children: Replace with inorder successor (minimum in right subtree) or inorder predecessor (maximum in left subtree), then delete that successor/predecessor
def bst_delete(node, key):
if node is None: return None
if key < node.key:
node.left = bst_delete(node.left, key)
elif key > node.key:
node.right = bst_delete(node.right, key)
else: # Found the node to delete
if node.left is None: return node.right
if node.right is None: return node.left
# Node has two children
successor = min_value(node.right)
node.key = successor.key
node.right = bst_delete(node.right, successor.key)
return node
Why case 3 is safe. The successor is the smallest key in the right subtree, so it is larger than everything in the left subtree and no larger than anything left in the right subtree. Putting its key into the deleted node keeps the BST property at that node. And because the successor is a minimum, it has no left child, so removing it from the right subtree is always case 1 or case 2.
Worked example: deleting 3 from the tree of Section 7.1. Node 3 has two children, 1 and 6:
bst_delete(8, 3) 3 < 8: recurse into the left subtree
bst_delete(3, 3) found; children 1 and 6, so case 3
min_value(6) 6 → 4; 4 has no left child, so the successor is 4
node.key = 4 the node that held 3 now holds 4
bst_delete(6, 4) 4 < 6: recurse left
bst_delete(4, 4) 4 is a leaf (case 1): return None, so 6.left = None
Before: After:
8 8
/ \ / \
3 10 4 10
/ \ \ / \ \
1 6 14 1 6 14
/ \ / \ /
4 7 13 7 13
Only one node is physically unlinked: the leaf that held 4. The node that held 3 stays in place with a new key. Deleting the root 8 instead shows the other sub-case: its successor is 10, which has a right child, so the second call is case 2 and 14 moves up to become the new root’s right child.
Copying the key is fine for this key-only tree, but a real map also has to move the value, and any outside pointer to the successor’s node (an iterator, a cursor) would suddenly see a different key. That is why std::map, whose erase may invalidate only iterators to the erased element, relinks the successor node into the deleted node’s position instead of copying data.
Minimum and Maximum
def min_value(node):
current = node
while current.left:
current = current.left
return current
def max_value(node):
current = node
while current.right:
current = current.right
return current
7.3 BST Complexity Analysis
| Operation | Average | Worst Case |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
| Min/Max | O(log n) | O(n) |
| Successor/Predecessor | O(log n) | O(n) |
| Traversal | O(n) | O(n) |
Average case assumes randomly inserted keys, yielding trees of height Θ(log n). The constant is larger than for a perfectly balanced tree; see below.
Worst case occurs when keys are inserted in sorted order:
Inserting: 1, 2, 3, 4, 5
1
\
2
\
3
\
4
\
5
Height = n, operations = O(n)
The Height of a Randomly Built BST
“Randomly inserted” has a precise meaning: n distinct keys are inserted into an empty tree, all n! insertion orders equally likely, and there are no deletions. Under that model there are two different questions, with different answers: how deep is a typical node (the average search cost), and how deep is the deepest one (the worst search in that tree)?
It is quicksort’s recursion tree. The first key inserted becomes the root, and every later key is compared with it and sent left or right. After that, the smaller keys build the left subtree among themselves and the larger keys build the right subtree, each still in uniformly random order. That is exactly quicksort with the first element of each subarray as pivot: the root is the first pivot, the two subtrees are the two recursive calls. Each key is compared with precisely its ancestors, so the number of comparisons quicksort makes equals the sum of the depths of all nodes in the BST built from the same sequence (its internal path length). Shuffling the input and building a BST does the same comparisons as quicksort with random pivots.
Average depth. Number the keys 1 to n by rank. Key j is an ancestor of key i exactly when j is the first key inserted from the range between i and j (inclusive). Until some key from that range arrives, i and j follow the same path, because every node on it is outside the range and sends both the same way. The first key from the range to arrive splits them: if it is j, j becomes an ancestor of i; if it is i, i becomes an ancestor of j; if it is strictly between, they go to different subtrees. Each of the |i − j| + 1 keys in the range is equally likely to come first, so
P(j is an ancestor of i) = 1 / (|i − j| + 1)
E[depth of key i] = Σ_{j ≠ i} 1/(|i − j| + 1) = H_i + H_{n−i+1} − 2 (H_m = 1 + 1/2 + ... + 1/m)
Average over all i: 2(1 + 1/n) H_n − 4 ≈ 2 ln n ≈ 1.39 log₂ n
Multiply by n and you have quicksort’s expected comparison count, 2(n + 1)H_n − 4n ≈ 1.39 n log₂ n. So a successful search in a random BST costs on average only about 39% more comparisons than in a perfectly balanced one.
Expected height. The deepest node is much deeper than the average one. Devroye (1986) proved that the expected height is asymptotically α ln n, where α ≈ 4.311 is the solution with α ≥ 2 of α ln(2e/α) = 1. That is about 2.99 log₂ n, three times the height of a perfect tree. Reed (2003) sharpened this to α ln n − β ln ln n + O(1) with β ≈ 1.953, and showed that the variance of the height is O(1): almost every random BST has nearly the same height. The second-order term is large at practical sizes, so measured heights sit well below 4.311 ln n:
| n | perfect tree height ⌊log₂ n⌋ | average depth 2(1 + 1/n)H_n − 4 | 2 ln n | height, simulated | 4.311 ln n |
|---|---|---|---|---|---|
| 1,000 | 9 | 11.0 | 13.8 | 19 to 22 | 29.8 |
| 100,000 | 16 | 20.2 | 23.0 | 38 to 41 | 49.6 |
| 1,000,000 | 19 | 24.8 | 27.6 | 50 | 59.6 |
(The simulated column is three random insertion orders for the first two rows and one for the last.)
What the model does not cover. Real keys often arrive sorted or nearly sorted (timestamps, auto-increment IDs), and then the “average case” never happens: you get the chain above. Treaps (Section 7.10) and the balanced trees of Chapter 8 remove the dependence on input order. Deletions also break the model. Always replacing a deleted node by its successor takes keys from the right side only, and long random sequences of insertions and deletions slowly push the tree away from the random shape; alternating between successor and predecessor reduces the drift (see Historical Context).
7.4 Successor and Predecessor
The inorder successor of a node x is the node with the next larger key; the predecessor is the node with the next smaller key. They are what an ordered-map iterator’s ++ and -- do, and what Java’s TreeMap.higherKey and lowerKey return. The two cases for the successor follow from the order in which inorder visits nodes:
- x has a right subtree. Inorder visits x and then its entire right subtree, starting with that subtree’s leftmost node. So the successor is
min_value(x.right): one step right, then left as far as possible. - x has no right subtree. Then x is the last node visited in some subtree, and the successor is whatever inorder visits after that subtree. Walk up. While x is a right child, its parent was visited before it, so keep climbing. The first time you climb up from a left child into a parent p, x was the maximum of p’s left subtree, so p is next. If you climb past the root, x was the maximum of the whole tree and has no successor.
With parent pointers both cases are direct. Assume each TreeNode has a parent field (which bst_insert and bst_delete must then keep up to date):
def successor_node(x):
if x.right: # case 1: leftmost node of the right subtree
return min_value(x.right)
p = x.parent # case 2: climb until we arrive from a left child
while p and x is p.right:
x, p = p, p.parent
return p # None if x was the maximum
def predecessor_node(x):
if x.left:
return max_value(x.left)
p = x.parent
while p and x is p.left:
x, p = p, p.parent
return p
On the example tree: the successor of 3 is 4 (right to 6, left to 4), of 7 is 8 (7 and 6 are right children, 3 is a left child, so stop at its parent 8), of 13 is 14 (13 is a left child, one step up), and 14 has none (14 and 10 are right children, then the walk leaves the root).
Each call is O(h) in the worst case. Iterating over the whole tree is cheaper than that suggests: starting at min_value(root) and calling successor_node n − 1 times crosses each edge at most twice, once going down and once coming up, so the full walk is O(n) and each step is amortized O(1). This is how ordered-map iterators work in practice: libstdc++’s _Rb_tree_increment and the Linux kernel’s rb_next are this two-case walk on a red-black tree with parent pointers.
Without parent pointers there are two options. To answer one query, search from the root and remember the last node where the search turned the “useful” way. For the predecessor of a key, every time you go right you have passed a node smaller than the key, and every later such node is larger, so the last one is the answer:
def predecessor(root, key):
best = None
node = root
while node:
if node.key < key:
best = node # a candidate; a larger one may be to the right
node = node.right
else:
node = node.left # node.key >= key, so the answer is to the left
return best.key if best else None
predecessor(root, 5) visits 8 (go left), 3 (best = 3, go right), 6 (go left), 4 (best = 4, go right), then None, and returns 4. It is O(h) and works whether or not key is in the tree. The successor is the mirror image (Exercise 7.5). To iterate over the tree instead, keep the path from the root on an explicit stack: that is the iterative inorder traversal of Chapter 6, which also gives amortized O(1) per step, at the cost of O(h) memory instead of a parent pointer in every node.
7.5 Floor, Ceiling and Range Queries
Ordered maps answer four “nearest key” queries, all variants of the descent above:
| Query | Returns | Java TreeMap | C++ std::map |
|---|---|---|---|
| lower(k) | largest key < k | lowerKey | (lower_bound, then step back) |
| floor(k) | largest key ≤ k | floorKey | (upper_bound, then step back) |
| ceiling(k) | smallest key ≥ k | ceilingKey | lower_bound |
| higher(k) | smallest key > k | higherKey | upper_bound |
predecessor(root, key) above is lower(k). Floor differs only in returning the key itself when it is present:
def floor_key(root, key):
best = None
node = root
while node:
if node.key == key:
return key
if node.key < key:
best = node.key # candidate; a larger one may be to the right
node = node.right
else:
node = node.left
return best
Ceiling swaps < for > and left for right. On the example tree, floor(5) = 4, floor(12) = 10, ceiling(12) = 13, ceiling(15) = None. Each is O(h) worst case. These are the queries behind “the price tier for an order of 37 units” (floor over tier boundaries) or “the next scheduled event after now” (ceiling over timestamps).
Range queries. To report every key in [lo, hi] in sorted order, do an inorder traversal but skip any subtree that the BST property says is entirely out of range:
def range_keys(node, lo, hi, out):
if node is None:
return
if lo < node.key: # left subtree may hold keys >= lo
range_keys(node.left, lo, hi, out)
if lo <= node.key <= hi:
out.append(node.key)
if node.key < hi: # right subtree may hold keys <= hi
range_keys(node.right, lo, hi, out)
The output is sorted because the traversal is still inorder. Nothing in range is missed: a left subtree is skipped only when node.key ≤ lo, so all its keys are < lo, and a right subtree only when node.key ≥ hi, so all its keys are > hi.
Cost: O(h + k) worst case for a tree of height h, where k is the number of keys reported. Every visited node is either reported or lies on the search path for lo or on the search path for hi, so at most k + 2(h + 1) nodes are visited (Exercise 7.6 proves it). On the example tree, range_keys(root, 5, 12, out) reports 6, 7, 8, 10 and visits eight nodes: the four reported ones, 3 and 4 (the search path for 5 is 8, 3, 6, 4) and 14 and 13 (the search path for 12 is 8, 10, 14, 13). It never touches 1. On a balanced tree that is O(log n + k): the cost of finding the two ends of the range plus one unit per answer, however large n is. A hash table has no equivalent and must scan all n keys. If you only need how many keys are in range, not the keys themselves, subtree sizes (Section 7.7) answer in O(h).
7.6 Validating a BST
A validator is worth having whenever a tree’s invariant could be broken: in tests for a new balancing scheme, after a tree is loaded from disk or the network, or as a debug assertion after rotations. The classic wrong answer checks each node only against its children:
def is_bst_local(node): # WRONG: only checks parent-child pairs
if node is None:
return True
if node.left and node.left.key >= node.key:
return False
if node.right and node.right.key <= node.key:
return False
return is_bst_local(node.left) and is_bst_local(node.right)
Change the 7 in the example tree to 9. Every parent-child pair is still in order (9 > 6), so is_bst_local returns True, but 9 sits in 8’s left subtree, and bst_search(root, 9) goes right at 8 and reports it missing. The BST property of Section 7.1 is about all nodes in a subtree, and a constraint from far up the tree is invisible to a local check.
Pass the bounds down. Every node in a subtree must lie in an open interval (lo, hi) fixed by its ancestors. Going left from a node tightens the upper bound to that node’s key; going right tightens the lower bound:
def is_bst(node, lo=None, hi=None):
if node is None:
return True
if (lo is not None and node.key <= lo) or (hi is not None and node.key >= hi):
return False
return is_bst(node.left, lo, node.key) and is_bst(node.right, node.key, hi)
On the broken tree: is_bst(8) calls is_bst(3, None, 8), which calls is_bst(6, 3, 8), which calls is_bst(9, 6, 8), and 9 ≥ 8 fails. Using None rather than ±∞ for “no bound” keeps it working for any comparable keys, strings included.
Or check the inorder sequence. A binary tree is a BST (with distinct keys) exactly when its inorder sequence is strictly increasing. With the explicit-stack inorder traversal from Chapter 6, the check can stop at the first violation:
def is_bst_inorder(root):
prev = None
stack, node = [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if prev is not None and node.key <= prev:
return False
prev = node.key
node = node.right
return True
Both versions take O(n) time in the worst case (a valid tree must be read in full) and O(h) space for the recursion or the stack.
7.7 Order Statistics: Augmenting with Subtree Size
Two queries a plain BST answers badly: select(k), the k-th smallest key, and rank(key), how many keys are smaller than a given one. An inorder walk answers both, but in O(n) worst case. Store one extra integer in each node and both drop to O(h).
The augmentation is size, the number of nodes in the node’s subtree, with the invariant
node.size = 1 + size(node.left) + size(node.right) (size of an empty tree = 0)
class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.size = 1 # nodes in this subtree
def size(node):
return node.size if node else 0
def update(node):
node.size = 1 + size(node.left) + size(node.right)
Maintaining it. Insertion and deletion only change the subtrees of nodes on the search path, so bst_insert and bst_delete need one new line each: recompute the size of every node on the way back up the recursion.
def bst_insert(root, key):
if root is None:
return TreeNode(key)
if key < root.key:
root.left = bst_insert(root.left, key)
else:
root.right = bst_insert(root.right, key)
update(root) # new
return root
def bst_delete(node, key):
if node is None:
return None
if key < node.key:
node.left = bst_delete(node.left, key)
elif key > node.key:
node.right = bst_delete(node.right, key)
else:
if node.left is None: return node.right
if node.right is None: return node.left
successor = min_value(node.right)
node.key = successor.key
node.right = bst_delete(node.right, successor.key)
update(node) # new
return node
Recomputing from the children on the way up, rather than adding or subtracting 1 on the way down, is deliberate: deleting a key that is not in the tree changes nothing, and in case 3 the sizes along the path to the successor shrink too. Recomputation gets both right without special cases. The extra work is O(1) per node on the path, so both operations stay O(h). In the balanced trees of Chapter 8 a rotation changes the subtrees of exactly two nodes; recompute the lower one first, then the upper one, and the augmentation survives rebalancing.
Select and rank each walk one root-to-leaf path, using the left subtree’s size to decide where to go. Keys are counted from 0, so select(0) is the minimum:
def select(node, k):
"""The k-th smallest key, counting from 0."""
while node:
left = size(node.left)
if k < left:
node = node.left # the answer is among the left subtree's keys
elif k == left:
return node.key # exactly k keys are smaller than this one
else:
k -= left + 1 # skip the left subtree and this node
node = node.right
raise IndexError(k)
def rank(node, key):
"""How many keys in the tree are smaller than key."""
r = 0
while node:
if key <= node.key:
node = node.left
else:
r += size(node.left) + 1 # this node and its whole left subtree are smaller
node = node.right
return r
The example tree with sizes:
8(9)
/ \
3(5) 10(3)
/ \ \
1(1) 6(3) 14(2)
/ \ /
4(1) 7(1) 13(1)
select(root, 3): at 8, the left size is 5 and 3 < 5, go left. At 3, the left size is 1 and 3 > 1, so k becomes 3 − 2 = 1, go right. At 6, the left size is 1 = k: return 6. (Sorted: 1, 3, 4, 6, …)rank(root, 13): at 8, 13 > 8, add 5 + 1 (r = 6), go right. At 10, add 0 + 1 (r = 7), go right. At 14 and then 13, go left. Return 7: the keys 1, 3, 4, 6, 7, 8, 10.
Counting keys in a range now costs O(h) regardless of how many there are: for integer keys, the count in [lo, hi] is rank(hi + 1) − rank(lo). On the example, [5, 12] holds rank(13) − rank(5) = 7 − 3 = 4 keys, matching what range_keys reported.
On a balanced tree all of this is O(log n) worst case, for one extra integer per node. GNU libstdc++ ships it as a policy-based tree (tree_order_statistics_node_update, with find_by_order and order_of_key), and Redis sorted sets apply the same idea to a skip list, storing a span count on each forward link so ZRANK is O(log n). Size is the simplest instance of a general technique: any field that can be computed from a node and its children’s fields (a subtree sum, a maximum, the largest interval endpoint in an interval tree) can be maintained through inserts, deletes and rotations at no asymptotic cost.
7.8 Self-Balancing BSTs
Self-balancing trees maintain height O(log n) regardless of insertion order.
Height-Balance Definitions
Different balancing criteria define different tree families:
| Tree Type | Balance Criterion |
|---|---|
| AVL | |height(left) - height(right)| ≤ 1 |
| Red-Black | Black-height balanced, no consecutive reds |
| Splay | No explicit criterion, amortized O(log n) |
| Weight-balanced | Size of subtrees within factor |
7.9 Threaded Binary Trees
Threaded trees store threads (pointers) to inorder predecessor/successor instead of null pointers:
struct ThreadedNode {
element_type data;
struct ThreadedNode *left;
struct ThreadedNode *right;
int left_thread; // true if left points to inorder predecessor
int right_thread; // true if right points to inorder successor
};
Threaded Tree:
4
/ \
2 6
/ \
1 8
Threads shown as dashed:
1 ──→ 2 ──→ 4 ──→ 6 ──→ 8
Advantage: O(1) space for traversal (no stack) Disadvantage: More complex insert/delete
7.10 BST Variants
Treaps (BST + Heap)
Combine BST property with random heap priorities:
Treap example (priorities in parentheses):
(10)8
/ \
(30)3 (20)10
/ \ \
(50)1 (40)6 (70)14
The BST property holds on keys; the heap property holds on priorities (a min-heap here: every priority is smaller than its children’s). Random priorities ensure expected O(log n) height.
Skip Lists as BST Alternative
Skip lists can be viewed as a probabilistic alternative to BSTs, with similar complexity but simpler implementation.
AA-Trees
Simplified red-black tree that only allows right children to be red:
- Similar to 2-3 tree representation
- Simpler delete (no complex cases)
- O(log n) guaranteed
7.11 Applications of BSTs
- Ordered maps: Python dict (but actually hash-based), C++ map, Java TreeMap
- Ordered sets: C++ set, Java TreeSet (Python set is hash-based too)
- Database indexes: B+ trees (multi-level BSTs)
- Priority queues: Can implement with additional min-pointer
- Finger trees: For sequence operations with good complexity
7.12 Choosing BST vs Alternatives
Use BST When:
- Need ordered iteration
- Range queries needed
- Insert/delete balance with search
- Can tolerate O(n) worst case (or using balanced variant)
Use Hash Table When:
- Only point queries needed
- Insert/delete heavy
- Can tolerate hash collisions
7.13 Historical Context
The binary search tree was developed independently by several people around 1960. The earliest published descriptions include P. F. Windley (“Trees, forests and rearranging”, The Computer Journal, 1960), A. D. Booth and A. J. T. Colin (Information and Control, 1960), and T. N. Hibbard (“Some combinatorial properties of certain trees with applications to searching and sorting”, Journal of the ACM, 1962). Hibbard’s paper also gave the successor-based deletion of Section 7.2, still called Hibbard deletion, and analysed it: deleting a random key from a random BST leaves a random BST. That does not survive further updates. Knott observed in the 1970s that randomness is lost once another insertion follows, and Eppinger’s simulations (Communications of the ACM, 1983) showed that long random sequences of insertions and Hibbard deletions first improve and then worsen the average path length, while symmetric deletion (alternating successor and predecessor) behaves better.
The average-depth result of Section 7.3 is the same calculation as the average-case analysis of quicksort, which Hoare published in 1961 and 1962. The height took much longer: Devroye proved the 4.311 ln n asymptotic in 1986, and in 2003 Reed and, independently, Drmota determined the second-order term and showed that the variance of the height is bounded.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
7.1 ★ Build a BST by hand. Insert 50, 30, 70, 20, 40, 60, 80, 35, 45, 65 into an empty BST using bst_insert. Draw the result, give its height, and list the nodes bst_search visits when looking for 45 and when looking for 62.
Solution
50
/ \
30 70
/ \ / \
20 40 60 80
/ \ \
35 45 65
Height is 3 (for example 50→30→40→35). Inorder gives 20 30 35 40 45 50 60 65 70 80, sorted as expected.
- Search 45: 50 (go left), 30 (go right), 40 (go right), 45 (found). 4 nodes.
- Search 62: 50 (right), 70 (left), 60 (right), 65 (left), then
None. 4 nodes visited, not found. An unsuccessful search always ends at an empty child slot, and that slot is exactly wherebst_insertwould put 62.
7.2 ★★ Trace all three deletion cases. Starting from the tree in 7.1, run bst_delete for 20, then 30, then 50. For each, say which case of Section 7.2 applies and draw the tree after the final deletion.
Hint
After 20 is gone, look again at how many children 30 has. For 50, find the minimum of its right subtree, and note how many children that node has.
Solution
- Delete 20. It is a leaf (case 1): 30’s left pointer becomes
None. - Delete 30. It now has only a right child, 40 (case 2).
bst_deletereturnsnode.right, so the subtree rooted at 40 (with 35 and 45) moves up to become 50’s left child. - Delete 50. It has two children (case 3). The successor is
min_value(50.right): from 70 go left to 60, which has no left child, so the successor is 60. The root’s key becomes 60, and then 60 is deleted from the right subtree. That node has one child (65), so it is case 2 again: 70’s left child becomes 65.
60
/ \
40 70
/ \ / \
35 45 65 80
Case 3 never recurses into another case 3: the successor is the minimum of a subtree, so it has no left child, and removing it is always case 1 or case 2.
7.3 ★★ How many insertion orders give the perfect tree? Inserting 4, 2, 6, 1, 3, 5, 7 into an empty BST produces the perfect tree of height 2 from Chapter 8. Of the 7! = 5040 orders of the keys 1 to 7, how many produce exactly that tree? As a warm-up, how many of the 6 orders of {1, 2, 3} produce a tree of height 2?
Hint
The first key inserted becomes the root forever. After that, the keys smaller than the root and the keys larger than it build their subtrees independently; only their relative order within each side matters.
Solution
Warm-up: only orders starting with 2 (that is, 2 1 3 and 2 3 1) give the balanced tree. The other 4 of 6 give a chain of height 2.
For 1 to 7: the root must be 4, so 4 comes first. The remaining 6 positions hold the left keys {1, 2, 3} and right keys {5, 6, 7} interleaved in any way: C(6, 3) = 20 ways to choose which positions are left keys. Within the left keys, the order must produce the balanced 3-node tree, which by the warm-up happens in 2 of 6 orders (2 first). Same on the right (6 first). Total:
f(7) = C(6, 3) × f(3) × f(3) = 20 × 2 × 2 = 80
So 80 / 5040 ≈ 1.6% of orders give the perfect tree. A random order still gives expected O(log n) height (Section 7.3), because most of the other 4960 orders give trees that are only slightly worse, not chains. Only 2^(n−1) orders out of n! give a chain: here 64.
7.4 ★★ Validating with duplicates. Section 7.6’s is_bst assumes distinct keys, but bst_insert sends a key equal to the node’s key to the right, so inserting 5, 3, 5 builds a tree that is_bst rejects. (a) State the invariant that every tree built by bst_insert satisfies when duplicates are allowed, and change is_bst to check it. (b) Someone suggests instead relaxing is_bst_inorder to accept a non-decreasing sequence. Give a tree it wrongly accepts, and say what can go wrong.
Hint
The rule is asymmetric: equal keys may appear on one side only. Which of the two bounds becomes inclusive?
Solution
(a) bst_insert goes left only on key < root.key, so the invariant is: every key in the left subtree is strictly smaller than the node’s key, and every key in the right subtree is greater than or equal to it. In bounds form, each subtree’s keys lie in the half-open interval [lo, hi): going left still sets an exclusive upper bound, while going right now sets an inclusive lower bound.
def is_bst_dup(node, lo=None, hi=None):
if node is None:
return True
if (lo is not None and node.key < lo) or (hi is not None and node.key >= hi):
return False
return is_bst_dup(node.left, lo, node.key) and is_bst_dup(node.right, node.key, hi)
The tree from 5, 3, 5 is 5 with left child 3 and right child 5. The right 5 is checked against [5, None), which it satisfies. bst_delete keeps this invariant too: in case 3 the successor is the minimum of the right subtree, so every key left in that subtree is still ≥ it.
(b) The tree “5 with a left child 5” has inorder sequence 5, 5, which is non-decreasing, so the relaxed check accepts it. But bst_insert can never build it, and is_bst_dup rejects it (the left 5 is not < 5). Plain search for 5 still works, but anything that relies on the convention breaks: for example, counting the copies of 5 by finding the first 5 and then looking only in its right subtree reports 1 instead of 2. An inorder sequence cannot tell which side of a node a duplicate is on, so for an asymmetric invariant the bounds version is the one to use.
7.5 ★★ Successor without parent pointers. Section 7.4 finds the predecessor of a key by descending from the root. Write successor(root, key) that returns the smallest key in the tree strictly greater than key (or None), in O(h) time and O(1) extra space, without parent pointers. key need not be in the tree. On the example tree in Section 7.1, what does it return for 7, 6, 5 and 14?
Hint
Walk down as in a search. Every time you go left, the node you just left is a candidate answer, and every later candidate is smaller.
Solution
def successor(root, key):
best = None
node = root
while node:
if key < node.key:
best = node # a candidate; a smaller one may be to the left
node = node.left
else:
node = node.right # node.key <= key, so the answer is to the right
return best.key if best else None
Each iteration moves down one level, so it takes O(h) time. best always holds the smallest key greater than key among the nodes seen so far, and the unexplored subtree is the only place a smaller one could be.
On the tree 8, 3, 10, 1, 6, 14, 4, 7, 13:
- 7: path 8 (best = 8, go left), 3 (right), 6 (right), 7 (right),
None. Returns 8. This is the “go up to the first ancestor you are a left descendant of” case. - 6: path 8 (best 8), 3, 6 (right), 7 (best 7, left),
None. Returns 7, the minimum of 6’s right subtree. - 5: path 8 (best 8), 3, 6 (best 6), 4 (right),
None. Returns 6, even though 5 is not in the tree. - 14: path 8, 10, 14, all going right, so
bestis never set. Returns None.
7.6 ★★★ Range queries in O(h + k). Section 7.5’s range_keys(node, lo, hi, out) appends every key in [lo, hi] to out in sorted order. Prove that it visits at most k + 2(h + 1) nodes, where k is the number of keys reported and h is the tree’s height.
Hint
Show that every visited node whose key is below lo lies on the search path for lo.
Solution
Bound. Visited nodes are of three kinds: in range (exactly k of them), below lo, or above hi.
Take a visited node v with v.key < lo, and look at each step on the path from the root to v. If the step went left from u, the function only does that when lo < u.key, and the search for lo also goes left at u. If the step went right from u, then v is in u’s right subtree, so u.key < v.key < lo, and the search for lo also goes right at u. Every step agrees with the search for lo, so v is on the search path for lo. That path has at most h + 1 nodes.
The symmetric argument puts every visited node above hi on the search path for hi, another h + 1 nodes at most. Total: at most k + 2(h + 1), which is O(h + k). In the example of Section 7.5, k = 4 and h = 3, and the call visits 8 nodes against a bound of 12.
7.7 ★ BST or hash table? For each service, pick a hash table or a balanced BST and give the deciding reason. (a) A session store that maps random session tokens to user IDs; the only operations are insert, lookup by exact token, and delete. (b) A log index keyed by timestamp; the common query is “all events between 10:00 and 10:05”. (c) A leaderboard that must answer “who has the next-highest score after mine?”
Solution
(a) Hash table. Only point queries, and no ordering is ever used. Expected O(1) beats O(log n), and random tokens hash well. A BST here pays for an ordering nobody reads.
(b) Balanced BST (or a B+ tree on disk, Chapter 10). A time-range query is the range_keys pattern of Section 7.5: O(log n + k). A hash table scatters adjacent timestamps across buckets, so it must scan everything.
(c) Balanced BST keyed by score. “Next-highest score” is the successor query of Section 7.4, O(log n). A hash table has no notion of “next” and would need an O(n) scan per query.
The pattern from Section 7.12: if any query involves order (next, previous, min, max, range, sorted iteration), the BST wins; if every query is an exact match, the hash table wins.
7.8 ★★ Sizes under deletion, and counting a range. Start from the size-augmented example tree of Section 7.7. (a) Run bst_delete(root, 3) (the deletion traced in Section 7.2). Which nodes have their size changed, and to what? (b) rank(hi + 1) − rank(lo) counts keys in [lo, hi] only for integers. Write count_range(root, lo, hi) that works for any comparable keys (strings, floats) in O(h), and check it on [5, 12] after the deletion.
Hint
For (b), write a second descent that counts keys ≤ a given key. It differs from rank in one comparison.
Solution
(a) The recursion visits 8, then the node that held 3 (now 4), then 6, then the leaf 4, which is unlinked. update runs on the way back up at each surviving node on that path: 6 becomes 2 (only 7 is left below it), the node now holding 4 becomes 4 (1, 4, 6, 7), and 8 becomes 8. Nothing else changes: 10, 14, 13, 1 and 7 keep their sizes because their subtrees did not change.
(b)
def count_leq(node, key):
"""How many keys in the tree are <= key."""
r = 0
while node:
if key < node.key:
node = node.left
else:
r += size(node.left) + 1
node = node.right
return r
def count_range(root, lo, hi):
if hi < lo:
return 0
return count_leq(root, hi) - rank(root, lo) # (# keys <= hi) - (# keys < lo)
Both descents are O(h). After deleting 3 the keys are 1, 4, 6, 7, 8, 10, 13, 14. count_leq(root, 12): at 8, add 4 + 1 (r = 5), go right; at 10, add 0 + 1 (r = 6), go right; at 14 and 13, go left; result 6. rank(root, 5): at 8 go left; at 4, add 1 + 1 (r = 2), go right; at 6 go left to None; result 2. So 4 keys lie in [5, 12]: 6, 7, 8, 10.
7.9 ★★ Leaves of a random BST. Insert the keys 1 to n (n ≥ 2) in uniformly random order. Using the ancestor rule of Section 7.3, show that key i is a leaf exactly when its neighbours in rank, i − 1 and i + 1 (those that exist), are both inserted before it. Conclude that the expected number of leaves is (n + 1)/3.
Hint
If i has any descendant j < i, then i is an ancestor of j, so i was inserted first among the keys j to i. What does that say about i − 1?
Solution
By the ancestor rule, i is an ancestor of j exactly when i is the first key inserted among those between j and i inclusive. If j < i, that range contains i − 1, so i must arrive before i − 1. Conversely, if i arrives before i − 1, then i is first in the two-key range {i − 1, i}, so i − 1 is a descendant of i. Hence i has a descendant on its left side iff i arrives before i − 1, and symmetrically on its right side iff i arrives before i + 1. So i is a leaf exactly when every existing neighbour arrives before it.
For 2 ≤ i ≤ n − 1, i is a leaf when it is the last of the three keys i − 1, i, i + 1 to arrive. In a random order each of the three is equally likely to be last: probability 1/3. For i = 1 and i = n there is one neighbour, and the probability is 1/2. By linearity of expectation:
E[leaves] = (n − 2) · 1/3 + 2 · 1/2 = (n − 2)/3 + 1 = (n + 1)/3
So about a third of the nodes in a random BST are leaves; in a perfect tree it is about half. Simulation agrees: 20,000 random trees on 50 keys average 17.0 leaves, and (50 + 1)/3 = 17.
Where this connects
- Chapter 8: Self-Balancing Trees. What to do when this degrades to a linked list
- Chapter 17: Persistent Data Structures. Making a BST persistent, so old versions survive updates
Chapter 8: Self-Balancing Trees
8.1 Why Balance Matters
Consider inserting keys in sorted order into a regular BST:
Insert 1, 2, 3, 4, 5, 6, 7:
1
\
2
\
3
\
4
\
5
\
6
\
7
Height = 7, Search = O(7)
Now consider the same in a balanced tree:
Same keys, balanced:
4
/ \
2 6
/ \ / \
1 3 5 7
Height = 3, Search = O(3)
The difference becomes dramatic at scale:
- n = 1,000,000
- Unbalanced height = 1,000,000 → worst case 1M comparisons
- Balanced height ≈ 20 → at most 20 comparisons
8.2 AVL Trees
AVL trees (Adelson-Velsky and Landis, 1962) were the first balanced BST, maintaining balance via height checks.
The Balance Factor
balance_factor(node) = height(left) - height(right)
Allowed values: -1, 0, 1
AVL Tree (balanced): Not AVL (unbalanced):
4 4
/ \ /
2 5 2
/ \ \
1 3 3
Balance factor of root: +1 +2
Rotations
Rotations restructure the tree to restore balance.
Right Rotation (for left-heavy):
Before: After:
z y
/ \ / \
y T4 → x z
/ \ / \ / \
x T3 T1 T2 T3 T4
Node z has balance factor +2 (left-heavy)
Node* rotate_right(Node *z) {
Node *y = z->left;
Node *T3 = y->right;
y->right = z;
z->left = T3;
// Update heights
z->height = 1 + max(height(z->left), height(z->right));
y->height = 1 + max(height(y->left), height(y->right));
return y;
}
Left Rotation (for right-heavy):
Before: After:
z y
/ \ / \
T1 y → z x
/ \ / \ / \
T2 x T1 T2 T3 T4
Left-Right Double Rotation:
Before: After:
z x
/ \ / \
y T4 → y z
/ \ / \ / \
T1 x T1 T2 T3 T4
/ \
T2 T3
AVL Insertion
- Insert as in BST
- Update heights
- Check balance factors from inserted node up
- If balance factor violates, rotate at first unbalanced node
Node* insert_avl(Node *node, int key) {
// Standard BST insert
if (!node) return new_node(key);
if (key < node->key) node->left = insert_avl(node->left, key);
else if (key > node->key) node->right = insert_avl(node->right, key);
else return node; // Duplicate
// Update height
node->height = 1 + max(height(node->left), height(node->right));
// Get balance factor
int balance = get_balance(node);
// Four cases
// Left-Left
if (balance > 1 && key < node->left->key)
return rotate_right(node);
// Right-Right
if (balance < -1 && key > node->right->key)
return rotate_left(node);
// Left-Right
if (balance > 1 && key > node->left->key) {
node->left = rotate_left(node->left);
return rotate_right(node);
}
// Right-Left
if (balance < -1 && key < node->right->key) {
node->right = rotate_right(node->right);
return rotate_left(node);
}
return node;
}
Why is one rotation (single or double) enough for an insertion? Let z be the lowest unbalanced ancestor of the new node. Before the insertion z’s subtree had some height H. The insertion pushed it to H + 1, and that extra level is what unbalanced z. The rotation at z removes exactly that level, so z’s subtree is back to height H, the height it had before the insertion. Every ancestor above z sees the same subtree height as before, so nothing above z can be unbalanced.
AVL Deletion
Deletion starts as BST deletion (Section 7.2): a node with two children takes its successor’s key, and the successor, which has at most one child, is unlinked instead. Then, as with insertion, walk back up the search path, updating heights and rotating wherever a balance factor reaches ±2. Two things are different.
The case is chosen from the child’s balance factor, not the key. The insertion code compares the new key with the child’s key to tell Left-Left from Left-Right. A deletion removes a key from the shorter side, so the key says nothing about the shape of the taller side. Look at the taller child y instead. If y leans the same way as z, or not at all (balance factor 0), do a single rotation; if y leans the other way, do a double rotation. The balance-0 case never arises after an insertion (the child that just grew always leans one way), but it does after a deletion, and there a double rotation would leave a node unbalanced (Exercise 8.8).
One rotation may not finish the job. Say z is left-heavy and lost a level on the right. Before the deletion z had height H, with a left subtree of height H − 1 and a right subtree of height H − 2. After it the right subtree has height H − 3. A single rotation when y leans left, or a double rotation when y leans right, leaves the subtree with height H − 1: one less than before the deletion. So z’s parent now sees a shorter child and may itself be unbalanced, and so may every ancestor above it. Only when y has balance 0 does the single rotation keep height H, and then the walk can stop.
Here is the AVL code in Python, with the four cases folded into one rebalance that insertion and deletion share. Heights follow the C code: an empty tree has height 0 and a leaf has height 1.
class Node:
def __init__(self, key):
self.key = key
self.left = self.right = None
self.height = 1
def height(node):
return node.height if node else 0
def get_balance(node):
return height(node.left) - height(node.right)
def update(node):
node.height = 1 + max(height(node.left), height(node.right))
def rotate_right(z):
y = z.left
z.left, y.right = y.right, z
update(z)
update(y)
return y
def rotate_left(z):
y = z.right
z.right, y.left = y.left, z
update(z)
update(y)
return y
def rebalance(node):
update(node)
balance = get_balance(node)
if balance > 1: # left-heavy
if get_balance(node.left) < 0: # Left-Right: straighten first
node.left = rotate_left(node.left)
return rotate_right(node) # Left-Left, or child balance 0
if balance < -1: # right-heavy, the mirror image
if get_balance(node.right) > 0: # Right-Left
node.right = rotate_right(node.right)
return rotate_left(node) # Right-Right, or child balance 0
return node
def insert_avl(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert_avl(node.left, key)
elif key > node.key:
node.right = insert_avl(node.right, key)
else:
return node # duplicate
return rebalance(node)
def delete_avl(node, key):
if node is None:
return None # key not present
if key < node.key:
node.left = delete_avl(node.left, key)
elif key > node.key:
node.right = delete_avl(node.right, key)
else:
if node.left is None:
return node.right
if node.right is None:
return node.left
successor = min_value(node.right) # Section 7.2
node.key = successor.key
node.right = delete_avl(node.right, successor.key)
return rebalance(node)
delete_avl calls rebalance at every node on the way back up, so it handles the cascade without any special code. For simplicity it keeps rebalancing after the height stops changing; those extra calls find nothing to do.
Worked example: a deletion that rotates twice. The tree below is a Fibonacci tree, the thinnest AVL tree of its height (Exercise 8.4; heights here count nodes, as in the code, so they are one more than in that exercise). Every internal node is left-heavy, with balance factor +1. Delete 12.
Before (height 5): After deleting 12 (height 4):
8 5
/ \ / \
5 11 3 8
/ \ / \ / \ / \
3 7 10 12 2 4 7 10
/ \ / / / / / \
2 4 6 9 1 6 9 11
/
1
delete_avl(12) 12 is a leaf: return None, so 11.right = None
rebalance(11) heights: left (10) = 2, right = 0, balance +2
child 10 has balance +1: Left-Left, rotate_right(11)
the subtree is now 10 with children 9 and 11, height 2 (was 3)
rebalance(8) heights: left (5) = 4, right (10) = 2, balance +2
child 5 has balance +1: Left-Left, rotate_right(8)
5 is the new root; tree height 4 (was 5)
Both ancestors of the deleted leaf needed a rotation, because each rotation made its subtree one shorter, which unbalanced the next node up. In bigger Fibonacci trees the cascade keeps going: deleting the right leaf of the 232-node Fibonacci tree of height 11 causes 5 rotations, about one for every two levels. An insertion into any AVL tree never needs more than 2.
Cost. Each level of the path does O(1) work: update a height and do at most one single or double rotation. Deletion is therefore O(log n) worst case, with O(log n) rotations in the worst case, against O(1) rotations for insertion.
Testing it. A balanced tree can return the right answers while silently breaking its invariant, so check the invariant, not just the answers. After every operation, compare the tree’s in-order keys with a sorted Python list that receives the same operations, and verify every node’s stored height and balance factor:
import bisect
import random
def min_value(node): # Section 7.2
while node.left:
node = node.left
return node
def check_avl(node, lo=None, hi=None):
"""Return the keys in order; fail if order, a height or a balance is wrong."""
if node is None:
return []
assert (lo is None or lo < node.key) and (hi is None or node.key < hi)
keys = check_avl(node.left, lo, node.key) + [node.key] \
+ check_avl(node.right, node.key, hi)
assert node.height == 1 + max(height(node.left), height(node.right))
assert abs(get_balance(node)) <= 1
return keys
root, reference = None, []
for _ in range(5000):
key = random.randrange(300)
if random.random() < 0.5:
root = insert_avl(root, key)
if key not in reference:
bisect.insort(reference, key)
else:
root = delete_avl(root, key)
if key in reference:
reference.remove(key)
assert check_avl(root) == reference
The children are checked before the parent, so each stored height is compared against children whose heights have already been verified.
AVL Properties
- Height ≤ 1.44 log₂(n+1) (tight bound)
- Search, insert, delete: O(log n)
- Insert may require at most 2 rotations
- Delete may require up to O(log n) rotations
- Better for read-heavy workloads
8.3 Red-Black Trees
Red-black trees use color bits instead of heights, enabling simpler rebalancing.
Red-Black Properties
- Every node is either red or black
- Root is black
- All leaves (NIL) are black
- Red nodes cannot have red children (no red-red)
- Every path from a node to descendant leaves has the same number of black nodes
Valid Red-Black Tree:
B(30)
/ \
R(10) R(40)
/ \ / \
B(5) B(20) B(35) B(50)
Path black counts (from any node):
30→5: B,R,B = 2 black nodes
30→20: B,R,B = 2 black nodes
30→35: B,R,B = 2 black nodes
30→50: B,R,B = 2 black nodes
Why Properties Guarantee Balance
From property 5, all paths from root to leaves have the same black count. Combined with property 4 (no consecutive reds), the longest path is at most twice the shortest. A subtree whose root has black-height bh contains at least 2^bh - 1 nodes, so the black-height of the root is at most log₂(n+1), and the tree height is at most 2 × log₂(n+1) = O(log n).
Rotations and Recoloring
Red-black operations are more complex but use fewer rotations than AVL.
Insertion Cases:
Case 1: Uncle is red
Recolor parent, uncle to black, grandparent to red
Case 2: Uncle is black, triangle
Rotate child up
Case 3: Uncle is black, line
Rotate parent up
void insert_rb(Node **root, int key) {
// Standard BST insert
Node *new = bst_insert(*root, key);
new->color = RED;
// Fix violations
fix_violation(root, new);
}
void fix_violation(Node **root, Node *z) {
while (z != *root && is_red(z) && is_red(z->parent)) {
Node *parent = z->parent;
Node *grandparent = parent->parent;
// Parent is left child
if (parent == grandparent->left) {
Node *uncle = grandparent->right;
if (is_red(uncle)) { // Case 1
parent->color = BLACK;
uncle->color = BLACK;
grandparent->color = RED;
z = grandparent;
} else {
if (z == parent->right) { // Case 2
rotate_left(root, parent);
z = parent;
parent = z->parent;
}
// Case 3
parent->color = BLACK;
grandparent->color = RED;
rotate_right(root, grandparent);
}
} else { // Parent is right child (symmetric)
// ... mirror cases
}
}
(*root)->color = BLACK;
}
Deletion and the Double Black
Deletion is where red-black trees earn their reputation. Start with BST deletion (Section 7.2): if the node has two children, copy in its successor’s key and remove the successor instead. Either way, the node y that is physically unlinked has at most one child, x (possibly a NIL leaf), which takes y’s place.
- y was red. No path lost a black node, and y’s neighbours were black, so no red-red appears. Done.
- y was black and x is red. Color x black. The paths through x get their black node back. Done.
- y was black and x is black (usually x is NIL). Every path through x now has one black node too few, breaking property 5. Pretend x carries an extra black: it is double black and counts twice. The counts are now correct, and the rest of the algorithm moves the extra black around until it can be dropped.
Let x be a left child, p its parent and w its sibling (the cases for a right child are mirror images). w cannot be NIL: before the deletion, every path down x’s side passed through the removed black node y, so every path down w’s side contains a black node too, besides its final NIL.
| Case | Situation | Action | Then |
|---|---|---|---|
| 1 | w is red | Rotate left at p; swap the colors of p and w | x has a black sibling: go to case 2, 3 or 4 |
| 2 | w is black, both its children black | Color w red; move the extra black up to p | p red: color it black, done. p black: p is double black, repeat one level up |
| 3 | w is black, near child (w.left) red, far child black | Rotate right at w; swap the colors of w and its old near child | Now the far child is red: case 4 |
| 4 | w is black, far child (w.right) red | Rotate left at p; w takes p’s color; p and the far child become black | Done |
In case 2, coloring w red removes one black from every path on w’s side, matching the shortage on x’s side; the whole subtree at p is now one short, which is what moving the extra black up to p records. In case 4 the rotation puts p, now black, above x, giving x’s paths the black node they were missing, while w (in p’s old position and color) and the far child (now black) keep the counts on the other side. If the extra black reaches the root, drop it: every path loses one black node at once, which property 5 allows.
Cost. Case 2 can repeat up the tree, but it only recolors. A case 1 rotation is followed by case 2 with a red parent (which stops) or by case 3 or 4 (which stop), so a deletion makes at most 3 rotations (cases 1, 3, 4) and O(log n) recolorings: O(log n) worst case. AVL deletion may need a rotation on many levels; this bounded number of structural changes is one reason libraries prefer red-black trees for update-heavy maps.
Worked example. Insert 10, 20, …, 100 in order, then delete 10:
Before: After deleting 10:
B40 B60
/ \ / \
B20 B60 B40 B80
/ \ / \ / \ / \
B10 B30 B50 R80 B20 B50 B70 B90
/ \ \ \
B70 B90 R30 R100
\
R100
remove 10 10 is a black leaf: its NIL is double black (x), p = 20, w = 30
case 2 at 20 w = 30 is black with black (NIL) children: color 30 red,
the extra black moves to 20, which is black, so continue
case 4 at 40 x = 20, p = 40, w = 60 is black, far child 80 is red:
rotate left at 40; 60 takes 40's color (black);
40 and 80 become black. Done
Every root-to-NIL path still has 3 black nodes before the NIL, and no red node has a red child. The recoloring and rotation look arbitrary here; Section 8.4 shows that they are a B-tree merge followed by a B-tree borrow.
AVL vs Red-Black Comparison
| Aspect | AVL | Red-Black |
|---|---|---|
| Balance criterion | Stricter | More relaxed |
| Tree height | ≤ 1.44 log₂(n) | ≤ 2 log₂(n) |
| Search performance | Better | Slightly worse |
| Insert performance | More rotations | Fewer rotations |
| Delete performance | Up to O(log n) rotations | At most 3 rotations |
| Memory overhead | Height field | Color bit |
| Use case | Read-heavy | Write-heavy |
8.4 Red-Black Trees Are 2-3-4 Trees
The five red-black properties and the case analyses above look like a list of tricks. They are a B-tree in disguise. A 2-3-4 tree is a B-tree of order 4 (Chapter 10): every node holds 1, 2 or 3 keys and has 2, 3 or 4 children, and all leaves are at the same depth. Take any red-black tree and merge every red node into its parent. Each black node, together with its red children, becomes one 2-3-4 node:
| 2-3-4 node | Red-black encoding |
|---|---|
2-node [b] | a black node with no red children |
3-node [a b] | a black node with one red child (b black with red left child a, or a black with red right child b) |
4-node [a b c] | the middle key b, black, with red children a and c |
Run the merge backwards and any 2-3-4 tree becomes a red-black tree. The correspondence is not one-to-one, because a 3-node can lean either way.
What the Rules Mean
With the 2-3-4 tree in view, each red-black property states a B-tree fact:
- No red node has a red child keeps every group to one black node and at most two red children, so a node never holds more than 3 keys.
- Every path has the same number of black nodes: each 2-3-4 node contains exactly one black node, so a path’s black count is the number of 2-3-4 levels it crosses. Equal black counts means all 2-3-4 leaves are at the same depth, which is the B-tree invariant and the whole source of the balance.
- The root is black because the top of every group is black.
- The height bound follows in one line. A 2-3-4 tree of n keys has at most log₂(n + 1) levels, since every node has at least 2 children, and each level becomes at most two red-black levels (a black node and a red child). So the red-black height is at most 2 log₂(n + 1), the bound of Section 8.3.
Insertion Is Splitting
A new red-black node is red, which means a new key joins an existing 2-3-4 leaf. That matches B-tree insertion, which always adds to a leaf.
- Parent is black. The leaf was a 2-node or a 3-node, and the key fits: a 2-node becomes a 3-node, and a 3-node becomes a 4-node already in the standard shape (black middle, two red children). Done.
- Case 1, red uncle. The parent and the uncle are both red children of the grandparent, so the grandparent’s group is a 4-node, and the new key would be its fourth. The B-tree answer is to split: the middle key moves up into the parent node and the two halves become separate nodes. Recoloring does exactly that. The grandparent turns red, which moves it up into its own parent’s group; the parent and uncle turn black, so they become the tops of two separate nodes. If the grandparent’s parent is also red, the node above has overflowed in turn: continue from there, as a B-tree split propagates upward. When the split reaches the root, recoloring the root black creates a new top level, the only way either tree grows taller.
- Cases 2 and 3, black uncle. The grandparent’s group is a 3-node (the black uncle belongs to a different node), so there is room for the new key, and the result is a 4-node. But its three keys form a chain of two red links instead of a black middle key with two red children. The rotations reshape the chain into that standard form. The 2-3-4 tree does not change; only its encoding does.
The figure shows Case 1. Inserting 80 under red 70 meets the 4-node [50 60 70]. Coloring 50 and 70 black and 60 red splits it: 60 joins the root, which becomes the 4-node [20 40 60], and 80 joins 70 to form the 3-node [70 80]. The parent of 60 is black, so the process stops there with no rotation at all.
Deletion Is Borrowing and Merging
Deletion maps onto Chapter 10’s B-tree deletion in the same way. Removing a red node, or a black node with a red child, takes a key out of a 3-node or 4-node, which still has a key left. A double black is an underflow: a 2-node has lost its only key. The four cases are the B-tree repairs:
- Case 2 (black sibling, both children black): the sibling is a 2-node, so there is nothing to borrow. Merge: the parent key comes down and joins the sibling, and coloring w red puts the two in one group. If p was red, the parent node had keys to spare; coloring p black finishes the merge. If p was black, the parent was itself a 2-node and is now empty: the underflow moves up a level, just as a B-tree merge can propagate to the root. When it reaches the root, the tree loses a level.
- Cases 3 and 4 (black sibling with a red child): the sibling is a 3-node or 4-node. Borrow through the parent: the parent key comes down into the empty node and a sibling key goes up to replace it (from a 4-node sibling, the key nearest x comes across as well). Case 4’s rotation does this in one step; case 3 only reshapes the sibling so that case 4’s rotation applies.
- Case 1 (red sibling): w is red, so it is in the same group as p. The parent’s 2-3-4 node is a 3-node encoded with the wrong lean, and x’s red-black sibling is not its 2-3-4 sibling. The rotation flips the lean, and nothing in the 2-3-4 tree changes. After it, x’s sibling is a real 2-3-4 sibling, and case 2, 3 or 4 applies.
Here is the worked deletion of Section 8.3 again, as a 2-3-4 tree:
Before: [40]
/ \
[20] [60 80]
/ \ / | \
[10] [30] [50] [70] [90 100]
Delete 10: [10] is empty. Its sibling [30] is a 2-node, so merge:
20 comes down and joins 30, giving [20 30]. Now [20]'s old node is empty
(case 2 with a black parent). Its sibling [60 80] is a 3-node, so borrow:
40 comes down, 60 goes up (case 4).
After: [60]
/ \
[40] [80]
/ \ / \
[20 30] [50] [70] [90 100]
Read the “after” tree of Section 8.3 back through the table above and you get exactly this.
This view explains why the classic algorithm has so many cases. A 2-3-4 tree has one operation for each situation (add a key, split, merge, borrow), but the binary encoding has several shapes for each 3-node and 4-node in transit, and each shape has its own case and its own mirror image. Rudolf Bayer introduced the structure in 1972 as the symmetric binary B-tree, a binary representation of B-trees with “horizontal” links where red links are now; the red and black colors came later. The next section shows what happens when the encoding is restricted to one shape per node.
8.5 Left-Leaning Red-Black Trees
Robert Sedgewick’s left-leaning red-black tree (LLRB, 2008) removes the choice. It adds one rule: a red node must be a left child. Thinking of a red node as a red link from its parent, the invariant is:
- Red links lean left.
- No node has two red links touching it.
- Every path from the root to a NIL link has the same number of black links.
Rule 2 forbids a red node with a red child and also a black node with two red children, so there are no 4-nodes. An LLRB tree is a 2-3 tree in which each 3-node is drawn one way, black on top with a red left child. Each 2-3 tree has exactly one LLRB encoding, so the mirror-image cases disappear.
Insertion
A new key is attached with a red link, as before. Then, on the way back up the recursion, three local fixes repair whatever the insertion broke, in this order:
RED, BLACK = True, False
class LLRBNode:
def __init__(self, key):
self.key = key
self.left = self.right = None
self.color = RED # a new key joins an existing node
def is_red(h):
return h is not None and h.color == RED
def rotate_left(h): # a red right link now leans left
x = h.right
h.right, x.left = x.left, h
x.color, h.color = h.color, RED
return x
def rotate_right(h): # a red left link now leans right
x = h.left
h.left, x.right = x.right, h
x.color, h.color = h.color, RED
return x
def flip_colors(h): # split a temporary 4-node
h.color = not h.color
h.left.color = not h.left.color
h.right.color = not h.right.color
def fix_up(h):
if is_red(h.right) and not is_red(h.left):
h = rotate_left(h) # right-leaning 3-node
if is_red(h.left) and is_red(h.left.left):
h = rotate_right(h) # 4-node as a chain of two reds
if is_red(h.left) and is_red(h.right):
flip_colors(h) # balanced 4-node: split it
return h
def llrb_insert(root, key):
root = _insert(root, key)
root.color = BLACK
return root
def _insert(h, key):
if h is None:
return LLRBNode(key)
if key < h.key:
h.left = _insert(h.left, key)
elif key > h.key:
h.right = _insert(h.right, key)
return fix_up(h)
(These rotate_left and rotate_right belong with LLRBNode, not with the AVL code of Section 8.2: they move colors, not heights.)
Each line of fix_up is one 2-3 tree situation. A red right link with a black left link is a 3-node leaning the wrong way: rotate it left. Two red links in a row on the left are a 4-node drawn as a chain: rotate right to balance it. Two red children are a balanced 4-node: flip the colors, which splits it and passes the middle key up as a red link to the parent, where the next fix_up call deals with it. The three classic insertion cases and their mirror images all reduce to these three lines, applied at every node on the search path.
Insertion is O(log n) worst case. Sedgewick’s paper also gives a variant that calls flip_colors on the way down, before the recursive calls; it splits 4-nodes top-down and keeps them, so it is the 2-3-4 version. The code above, with the flip last, is the 2-3 version used in Sedgewick and Wayne’s Algorithms (4th edition).
Deletion
Deletion uses the same plan as Chapter 10’s single-pass B-tree deletion: never step down into a node that has only one key, so that the key to be removed is never the only key in its leaf. move_red_left makes sure the left child is not a 2-node before the descent goes left. It first flips colors, merging the parent key and both children into a temporary 4-node; if the right sibling was a 3-node, it then borrows from it instead, with two rotations and a flip back. On the way back up, fix_up cleans up the temporary 4-nodes and right-leaning links left behind.
def move_red_left(h):
# h is red and h.left is a 2-node: give h.left a red link
flip_colors(h) # merge h.left, h, h.right
if is_red(h.right.left): # sibling is a 3-node: borrow
h.right = rotate_right(h.right)
h = rotate_left(h)
flip_colors(h)
return h
def move_red_right(h):
flip_colors(h)
if is_red(h.left.left):
h = rotate_right(h)
flip_colors(h)
return h
def delete_min(h):
if h.left is None:
return None
if not is_red(h.left) and not is_red(h.left.left):
h = move_red_left(h)
h.left = delete_min(h.left)
return fix_up(h)
def llrb_delete(root, key): # key must be in the tree
if not is_red(root.left) and not is_red(root.right):
root.color = RED
root = _delete(root, key)
if root is not None:
root.color = BLACK
return root
def _delete(h, key):
if key < h.key:
if not is_red(h.left) and not is_red(h.left.left):
h = move_red_left(h)
h.left = _delete(h.left, key)
else:
if is_red(h.left):
h = rotate_right(h) # lean right so a red link goes down
if key == h.key and h.right is None:
return None # h is a red leaf: drop it
if not is_red(h.right) and not is_red(h.right.left):
h = move_red_right(h)
if key == h.key:
successor = h.right
while successor.left:
successor = successor.left
h.key = successor.key
h.right = delete_min(h.right)
else:
h.right = _delete(h.right, key)
return fix_up(h)
The precondition matters: with an absent key, the descent can reach h.left.left on a missing child. Check membership first (an O(log n) search) when the caller cannot guarantee it. Both operations are O(log n) worst case.
The same kind of test as for the AVL tree checks every LLRB rule after every operation:
import bisect
import random
def check_llrb(h, lo=None, hi=None):
"""Return (black height, keys in order); fail if any LLRB rule is broken."""
if h is None:
return 0, []
assert (lo is None or lo < h.key) and (hi is None or h.key < hi)
assert not is_red(h.right) # red links lean left
assert not (is_red(h) and is_red(h.left)) # never two reds in a row
black_left, left = check_llrb(h.left, lo, h.key)
black_right, right = check_llrb(h.right, h.key, hi)
assert black_left == black_right # perfect black balance
return black_left + (not is_red(h)), left + [h.key] + right
root, reference = None, []
for _ in range(5000):
key = random.randrange(300)
if random.random() < 0.5:
root = llrb_insert(root, key)
if key not in reference:
bisect.insort(reference, key)
elif key in reference:
root = llrb_delete(root, key)
reference.remove(key)
assert not is_red(root)
assert check_llrb(root)[1] == reference
Trade-offs
The LLRB insertion is short enough to write from memory, and that is its real contribution: it makes the 2-3 correspondence visible in code. But it is not a better red-black tree in every respect.
- Deletion is still fiddly. The deletion code is more than twice the length of the insertion code, and it is harder to check by eye, because it deliberately creates temporary right-leaning links and 4-nodes and relies on
fix_upto remove them later. - More rotations. A classic insertion makes at most 2 rotations. The LLRB insertion keeps rotating on the way up to restore the left lean, sometimes at many levels. Inserting 100,000 random keys with the code above averaged about 1.19 rotations per insertion, with up to 13 in a single insertion; the classic algorithm averaged about 0.58 on the same keys.
- Recursion without parent pointers. That makes the code short, but production trees usually keep parent pointers anyway, for iterators and for deleting a node the caller already holds, and then the classic bottom-up fix-up is just as natural. Java’s
TreeMap(adapted from Cormen, Leiserson and Rivest), libstdc++’sstd::mapand the Linux kernel’srbtreeall use the classic algorithm.
Arne Andersson’s AA tree (1993, Chapter 7) made the mirror-image choice earlier, requiring red links to lean right; its two fix-up steps, skew and split, play the role of fix_up’s three lines.
8.6 Splay Trees
Splay trees (Sleator and Tarjan, 1985) use a different strategy: instead of maintaining invariants, they “splay” accessed nodes to the root.
The Splay Operation
When accessing a node, perform rotations to bring it to the root:
- Zig: Node is child of root
- Zig-Zig: Node and parent are both left/right children
- Zig-Zag: Node is left, parent is right (or vice versa)
Zig-Zig (left-left):
g x
/ \ / \
p T4 → T1 p
/ \ / \
x T3 T2 g
/ \ / \
T1 T2 T3 T4
Zig-Zag (left-right):
g x
/ \ / \
p T4 → p g
/ \ / \ / \
T1 x T1 T2 T3 T4
/ \
T2 T3
Amortized Analysis
Using the potential method with potential = Σ log₂(size(i)), each splay operation costs O(log n) amortized.
Key property: Recently accessed elements are near the root (temporal locality). For repeated access to same element, splay trees are optimal.
Splay Tree Properties
- O(log n) amortized for insert, delete, search
- O(n) worst case for a single operation
- No balance information needed (simpler implementation)
- Adaptive: good for locality of reference
- No guaranteed worst-case (unlike AVL, Red-Black)
- Can be made partially persistent
8.7 Scapegoat Trees
Scapegoat trees maintain balance by rebuilding subtrees when they become too unbalanced.
Balance Criterion
A tree is α-weight-balanced if for every node: size(child) ≤ α × size(node)
Typical α is strictly between 0.5 and 1 (α = 0.5 demands near-perfect balance; α close to 1 allows almost any shape)
Insertion
- Insert as in BST
- Walk back to root tracking path
- If height > log_1/α (n), find scapegoat and rebuild
The scapegoat is not necessarily the deepest unbalanced node; any node on the path that restores balance works.
Properties
- No rotations needed (simpler than AVL/Red-Black)
- O(log n) amortized insert/delete
- O(log n) worst-case search
- Simple to implement
- Good for systems where rotations are expensive
8.8 Treaps
Treaps combine BST with random heap priorities.
Why Random Priorities Work
With random priorities:
- Expected height = O(log n)
- Probability of O(n) height = negligible
- No explicit balancing needed
import random
class TreapNode:
def __init__(self, key, priority=None):
self.key = key
self.priority = priority or random.random()
self.left = None
self.right = None
def treap_insert(root, node):
if not root:
return node
if node.key < root.key:
root.left = treap_insert(root.left, node)
if root.left.priority < root.priority:
root = rotate_right(root)
else:
root.right = treap_insert(root.right, node)
if root.right.priority < root.priority:
root = rotate_left(root)
return root
8.9 Performance Comparison
| Tree Type | Search | Insert | Delete | Balance | Memory |
|---|---|---|---|---|---|
| BST (unbalanced) | O(n) | O(n) | O(n) | None | Low |
| AVL | O(log n) | O(log n) | O(log n) | Strict | Height |
| Red-Black | O(log n) | O(log n) | O(log n) | Relaxed | 1 bit |
| Splay | O(log n)* | O(log n)* | O(log n)* | Amortized | None |
| Scapegoat | O(log n) | O(log n)* | O(log n)* | Rebuild | None |
| Treap | O(log n)* | O(log n)* | O(log n)* | Probabilistic | Priority |
*Amortized or expected
8.10 Real-World Usage
| Tree Type | Real-World Uses |
|---|---|
| Red-Black | Linux kernel (completely fair scheduler), Java’s TreeMap/TreeSet, C++ STL (typically) |
| AVL | Databases with frequent lookups, file systems |
| Splay | Network routing (LRU caches), memory allocators |
| Treap | Skip list alternative in some databases |
8.11 Historical Context
Georgy Adelson-Velsky and Evgenii Landis described the AVL tree in 1962 (“An algorithm for the organization of information”, Doklady Akademii Nauk SSSR), the first binary search tree with a worst-case O(log n) height guarantee.
Rudolf Bayer, co-inventor of the B-tree (Chapter 10), introduced symmetric binary B-trees in 1972 (Acta Informatica): B-trees of order 4 stored as binary nodes, the structure of Section 8.4. Leonidas Guibas and Robert Sedgewick recast them in 1978 with the red and black coloring (“A dichromatic framework for balanced trees”, FOCS), and used the coloring as a common framework for many balanced-tree schemes. The double-black formulation of deletion in Section 8.3 follows Cormen, Leiserson and Rivest’s Introduction to Algorithms (1990). Sedgewick returned to the structure thirty years later with the left-leaning variant of Section 8.5 (2008).
Daniel Sleator and Robert Tarjan introduced splay trees in “Self-adjusting binary search trees” (Journal of the ACM, 1985). Scapegoat trees are named in Igal Galperin and Ronald Rivest’s 1993 paper (SODA); Arne Andersson had described essentially the same partial-rebuilding scheme in 1989. Treaps come from Cecilia Aragon and Raimund Seidel’s “Randomized search trees” (FOCS 1989; journal version by Seidel and Aragon in Algorithmica, 1996). The shape they rely on, a tree that is a BST on keys and a heap on a second value, is Jean Vuillemin’s Cartesian tree (1980).
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
8.1 ★ AVL insertion by hand. Insert 10, 20, 30, 40, 50, 25 into an empty AVL tree using insert_avl. For each insertion that triggers a rotation, name the node where the imbalance is detected and which of the four cases applies. Draw the final tree.
Solution
Balance factor is height(left) − height(right), as in Section 8.2.
- 10, 20: no imbalance. 10 has right child 20.
- 30: path 10→20→30. At 10 the balance factor is −2 and 30 > 20 (the right child’s key), so Right-Right at 10:
rotate_left(10). Tree: 20 with children 10 and 30. - 40: goes right of 30. Balance factors are −1 at 30 and −1 at 20. No rotation.
- 50: path 20→30→40→50. 40 is at −1, 30 is at −2, and 50 > 40, so Right-Right at 30:
rotate_left(30). Tree: 20 with children 10 and 40; 40 has children 30 and 50. - 25: goes 20→40→30, left of 30. 30 is at +1, 40 is at +1, but 20 has a left subtree of height 0 and a right subtree of height 2 (edges), so −2. 25 < 40 (the right child’s key), so Right-Left at 20:
rotate_right(40)makes 30 the root of that subtree, thenrotate_left(20)lifts 30 to the top.
30
/ \
20 40
/ \ \
10 25 50
Every node now has balance factor −1, 0 or +1, and inorder is still 10 20 25 30 40 50. Three insertions caused rotations, and each was fixed at the lowest unbalanced ancestor with at most two rotations, as Section 8.2 says.
8.2 ★ Is it a red-black tree? For each tree, say whether it is a valid red-black tree. If not, name the violated property from Section 8.3. (B = black, R = red; missing children are black NIL leaves.)
(a) B10 (b) B10 (c) B10 (d) R10
/ \ / \ / \ / \
R5 R15 B5 R15 B5 B15 B5 B15
\ / \ \
R20 B12 B20 B20
Solution
(a) Invalid, property 4. R15 has a red child R20. Black counts are fine (every root-to-NIL path has one black node before NIL), so only the no-red-red rule fails.
(b) Valid. No red node has a red child, and every root-to-NIL path has exactly 2 black nodes before NIL: 10 and 5, or 10 and 12, or 10 and 20.
(c) Invalid, property 5. The path 10→15→NIL (15’s empty left side) has 2 black nodes; the path 10→15→20→NIL has 3. Recoloring 20 red would fix it.
(d) Invalid, property 2. The root is red. Recoloring the root black is always safe: it adds one black node to every path equally. That is why fix_violation ends with (*root)->color = BLACK.
8.3 ★★ Red-black insertion by hand. Insert 10, 20, 30, 15, 13 into an empty red-black tree, using the three insertion cases of Section 8.3 (and their mirror images when the parent is a right child). For each insertion, say which cases fire and draw the tree.
Hint
New nodes are red. “Line” means the new node and its parent are on the same side (both left children or both right children); “triangle” means they are on opposite sides.
Solution
-
10: becomes the root and is colored black.
B10. -
20: red, right child of black 10. Parent is black, nothing to fix.
-
30: red, right child of red 20. The uncle (10’s left) is NIL, black. 30 and 20 are both right children: a line, so Case 3 (mirror): color 20 black, 10 red, rotate left at 10.
B20 / \ R10 R30 -
15: goes 20→10→right. Red parent R10, and the uncle R30 is red: Case 1. Color 10 and 30 black, 20 red, move z up to 20. 20 is the root, so the loop stops and the root is recolored black. The black-height of the tree just grew by one.
B20 / \ B10 B30 \ R15 -
13: goes 20→10→15→left. Red parent R15, and the uncle (10’s left) is NIL, black. 13 is a left child of 15, which is a right child of 10: a triangle, so Case 2 (mirror): rotate right at 15, making 13 the parent of 15. Now z is 15 and its parent is 13, a line, so Case 3 (mirror): color 13 black, 10 red, rotate left at 10.
B20 / \ B13 B30 / \ R10 R15
Every root-to-NIL path has 2 black nodes, and no red node has a red child.
8.4 ★★ The thinnest AVL trees. Let N(h) be the minimum number of nodes in an AVL tree of height h (edges). (a) Show N(h) = N(h − 1) + N(h − 2) + 1 and compute N(0) through N(6). (b) What is the largest possible height of an AVL tree with 20 nodes? (c) Use N(h) = F(h + 3) − 1, where F is the Fibonacci sequence with F(1) = F(2) = 1, to derive the bound h ≤ 1.44 log₂(n + 1) from Section 8.2.
Hint
A minimum AVL tree of height h has a root, one subtree of height h − 1, and the other subtree as short as the balance rule allows.
Solution
(a) An AVL tree of height h needs one subtree of height h − 1. The other can be at most one shorter, so the smallest choice is height h − 2. Both subtrees must themselves be minimal, giving N(h) = N(h − 1) + N(h − 2) + 1, with N(0) = 1 (one node) and N(1) = 2 (root and one child).
| h | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| N(h) | 1 | 2 | 4 | 7 | 12 | 20 | 33 |
(b) N(5) = 20 and N(6) = 33 > 20, so a 20-node AVL tree can have height 5, but not 6. A perfectly balanced 20-node tree has height 4, so the AVL tree is at most one level worse here.
(c) N(h) + 1 satisfies the Fibonacci recurrence: (N(h) + 1) = (N(h − 1) + 1) + (N(h − 2) + 1), with N(0) + 1 = 2 = F(3) and N(1) + 1 = 3 = F(4). So N(h) = F(h + 3) − 1. By induction, F(k) ≥ φ^(k − 2), where φ = (1 + √5)/2 ≈ 1.618 (it holds for k = 1, 2, and φ^(k−3) + φ^(k−4) = φ^(k−2) because φ² = φ + 1). An AVL tree with n nodes and height h therefore has
n ≥ N(h) = F(h + 3) − 1 ≥ φ^(h + 1) − 1
so h + 1 ≤ log_φ(n + 1) = log₂(n + 1) / log₂ φ ≈ 1.44 log₂(n + 1), and h < 1.44 log₂(n + 1). This is the source of the 1.44 constant, and also of the name “Fibonacci trees” for these worst-case AVL shapes.
8.5 ★★ Splay a chain. Insert 5, 4, 3, 2, 1 into a plain BST, giving a left-leaning chain with 5 at the root. (a) Splay node 1 to the root using the zig, zig-zig and zig-zag steps of Section 8.6, working from the bottom up. Draw the tree after each step and give the final height. (b) Then splay node 3 and draw the result.
Hint
Each step looks at x, its parent p and its grandparent g. Apply the rule, then repeat with x’s new parent and grandparent. Use the subtree labels in the zig-zig diagram to see where each subtree goes.
Solution
(a) Start: 5→4→3→2→1, all left children; height 4.
Step 1, zig-zig (x = 1, p = 2, g = 3, both left children). By the diagram, x becomes the subtree root, p becomes x’s right child, and g becomes p’s right child. All T subtrees are empty. The result replaces 3 as the left child of 4:
5
/
4
/
1
\
2
\
3
Step 2, zig-zig (x = 1, p = 4, g = 5, both left children). Here T2 (1’s right subtree) is the chain 2→3, and it becomes 4’s left subtree:
1
\
4
/ \
2 5
\
3
Final height 3, down from 4. Node 1 went from depth 4 to the root, and the total depth of all nodes fell from 10 to 8. That roughly-halving of the access path is what pays for the amortized O(log n) bound; a plain move-to-root by single rotations would leave a chain of height 4 behind.
(b) 3 is the right child of 2, and 2 is the left child of 4: a zig-zag (x = 3, p = 2, g = 4). x moves up with p as its left child and g as its right child; 4 keeps 5 as its right child. 3 is now the right child of the root 1, so a final zig rotates 3 above 1:
3
/ \
1 4
\ \
2 5
Height 2. Two accesses turned a height-4 chain into a nearly balanced tree.
8.6 ★★ A treap’s shape is determined by its keys and priorities. Using the min-heap convention of treap_insert (smaller priority nearer the root), draw the treap holding these keys and priorities. Then prove that for distinct keys and distinct priorities, the treap is the same no matter what order the keys are inserted in.
| key | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| priority | 0.6 | 0.2 | 0.9 | 0.1 | 0.5 | 0.3 |
Hint
Which node must be the root? Once the root is fixed, which keys must go in its left subtree?
Solution
The root must hold the smallest priority, 0.1, so the root is 4. By the BST property, keys {1, 2, 3} form its left subtree and {5, 6} its right. Apply the same rule to each side: on the left the smallest priority is 0.2, so 2 is that subtree’s root, with 1 on its left and 3 on its right. On the right the smallest is 0.3, so 6 is the root of that side, and 5 is its left child.
4 (0.1)
/ \
2 (0.2) 6 (0.3)
/ \ /
1 (0.6) 3 (0.9) 5 (0.5)
Uniqueness, by induction on the number of keys. With zero keys the treap is empty. Otherwise, the heap property forces the root to be the key with the minimum priority (priorities are distinct, so it is unique). The BST property then forces every smaller key into the left subtree and every larger key into the right. Each subtree is itself a treap on fewer keys, so by induction each is unique. Insertion order never enters the argument.
This is why random priorities give expected O(log n) height: the treap has exactly the shape of a plain BST built by inserting the keys in increasing priority order, and with random priorities that order is a uniformly random permutation. Section 7.3’s average case then applies, whatever order the keys actually arrive in.
8.7 ★★★ Prove the red-black height bound. (a) Let bh(x) be the number of black nodes on any path from x down to a NIL leaf, counting the NIL but not x itself. Prove by induction that the subtree rooted at x contains at least 2^bh(x) − 1 internal (non-NIL) nodes, and conclude that a red-black tree with n nodes has height at most 2 log₂(n + 1). (b) Show that the factor of 2 can really occur by drawing a valid red-black tree whose longest root-to-NIL path has twice as many nodes as its shortest.
Hint
For (a), relate bh of a child to bh of its parent; the answer depends on the child’s color. Then use property 4 to say what fraction of any root-to-leaf path must be black.
Solution
(a) Claim: subtree(x) has at least 2^bh(x) − 1 internal nodes. Induct on the height of x.
-
Base: x is NIL. bh(x) = 0 and the subtree has 0 ≥ 2⁰ − 1 = 0 internal nodes.
-
Step: x is internal with children c₁ and c₂. A black child has bh(c) = bh(x) − 1 and a red child has bh(c) = bh(x), so bh(c) ≥ bh(x) − 1 either way (property 5 makes bh well defined). Each child has smaller height, so by induction the subtree of x has at least
(2^(bh(x)−1) − 1) + (2^(bh(x)−1) − 1) + 1 = 2^bh(x) − 1
internal nodes.
Now let the tree have height h. Take a longest path from the root down to a NIL. Below the root it has h + 1 nodes (h internal nodes, then the NIL). Property 4 says no two reds are adjacent, and the NIL is black, so at least half of them are black: bh(root) ≥ (h + 1)/2 ≥ h/2. Applying the claim to the root:
n ≥ 2^(h/2) − 1, so h/2 ≤ log₂(n + 1), so h ≤ 2 log₂(n + 1).
This is the argument behind the one-line summary in “Why Properties Guarantee Balance”. Note the direction: the black-height is at most log₂(n + 1), which caps the height.
(b) Root B10 with a short left side and a long right side:
B10
/ \
B5 R20
/ \
B15 B30
\
R40
Check: every root-to-NIL path has 2 black nodes before the NIL (10 and 5, 10 and 15, or 10 and 30), and red nodes 20 and 40 have only black children (including NIL). The shortest root-to-NIL path is 10→5 (2 nodes); the longest is 10→20→30→40 (4 nodes). The longest path alternates black and red and the shortest is all black, which is exactly the extreme that property 4 allows.
8.8 ★★ Why deletion looks at the child’s balance factor. The AVL tree below is what insert_avl builds from 20, 10, 60, 5, 40, 80, 30, 70. (a) Delete 5 with delete_avl. Which node becomes unbalanced, which rotation is done, and does the walk up need to continue? (b) The C insert_avl picks the case by comparing the key with the child’s key. Since 5 < 60, that test would choose Right-Left. Do that double rotation instead and show that the result is not an AVL tree.
20
/ \
10 60
/ / \
5 40 80
/ /
30 70
Hint
Compute the balance factor of 60 before deciding anything. It is the case that never happens after an insertion.
Solution
(a) Removing the leaf 5 leaves 10 as a leaf (height 1). At 20 the left height is 1 and the right height (60) is 3, so the balance factor is −2. The taller child 60 has balance 0: its subtrees 40 and 80 both have height 2. rebalance sees get_balance(node.right) > 0 is false and does a single rotate_left(20):
60
/ \
20 80
/ \ /
10 40 70
/
30
20 has balance 1 − 2 = −1 and 60 has balance 3 − 2 = +1, so the tree is valid. Its height is 4, the same as before the deletion, so no ancestor could be affected and the walk could stop here. (This is the one case where a deletion’s rotation does not shorten the subtree.)
(b) The double rotation first does rotate_right(60), lifting 40, then rotate_left(20):
40
/ \
20 60
/ \ \
10 30 80
/
70
Node 60 has an empty left subtree and a right subtree of height 2: balance −2. The double rotation is right only when the inner grandchild (40) is the taller part of 60’s subtree. When 60 is balanced, moving 40 up leaves 80’s whole subtree hanging under 60 with nothing on the other side. Insertion never meets this case because the child that just grew always leans one way, which is why the C code can get away with comparing keys.
8.9 ★★ Red-black deletion, two views. Start again from the red-black tree that inserting 10, 20, …, 100 produces (the “before” tree of the worked deletion in Section 8.3) and delete 40, the root. (a) Trace the deletion: which node is physically removed, and which cases of the double-black table fire? Draw the result. (b) Redo it on the corresponding 2-3-4 tree (Section 8.4) and check that the two results correspond.
Hint
40 has two children, so its successor is removed instead. Look at the color of the double black’s sibling first.
Solution
(a) The successor of 40 is 50, the minimum of the right subtree. 50’s key is copied into the root, and the node that held 50, a black leaf, is unlinked. Its NIL is double black, with parent p = 60 and sibling w = 80.
- Case 1: w = 80 is red. Rotate left at 60 and swap the colors of 60 and 80: 80 is now black, with red left child 60. x’s new sibling is 70, black.
- Case 2: 70 is black with two black (NIL) children. Color 70 red and move the extra black to p = 60. 60 is red, so color it black. Done.
B50
/ \
B20 B80
/ \ / \
B10 B30 B60 B90
\ \
R70 R100
Every root-to-NIL path still has 3 black nodes, and no red node has a red child. The repair took one rotation and four color changes.
(b) The 2-3-4 tree is [40] at the root, with children [20] (over [10] and [30]) and [60 80] (over [50], [70] and [90 100]). Deleting 40 from an internal node replaces it with its successor 50 from a leaf, which leaves the leaf [50] empty. Its 2-3-4 sibling is [70], a 2-node, so merge: the separating key 60 comes down and joins 70, giving [60 70], and the parent [60 80] shrinks to [80]. The parent still has a key, so the repair stops.
[50]
/ \
[20] [80]
/ \ / \
[10] [30] [60 70] [90 100]
Reading the red-black result as groups gives exactly this. Case 1 did not change the 2-3-4 tree: the 3-node [60 80] was encoded with 60 on top, which made 80 the red-black sibling of the empty node even though its real 2-3-4 sibling was [70]. The rotation re-encoded the same 3-node with 80 on top. Case 2 with a red parent is a merge that the parent can absorb.
8.10 ★★ LLRB insertion by hand. Insert 1, 2, 3, 4, 5, 6, 7 in that order into an empty LLRB tree with llrb_insert (Section 8.5). After each insertion, say which of the three lines of fix_up fire (and at which node), draw the tree, and give the 2-3 tree it encodes.
Solution
Red nodes are marked R; everything else is black.
| Insert | fix_up actions | LLRB tree | 2-3 tree |
|---|---|---|---|
| 1 | none | 1 | [1] |
| 2 | rotate left at 1 (red right link) | 2 with left child R1 | [1 2] |
| 3 | flip at 2 (two red children); the root is then reset to black | 2 with children 1 and 3 | [2] over [1], [3] |
| 4 | rotate left at 3 | 2 with children 1 and 4; 4 has left child R3 | [2] over [1], [3 4] |
| 5 | flip at 4, which makes 4 red, a red right link of 2; then rotate left at 2 | 4 with children R2 and 5; 2 has children 1 and 3 | [2 4] over [1], [3], [5] |
| 6 | rotate left at 5 | as before, but 6 replaces 5, with left child R5 | [2 4] over [1], [3], [5 6] |
| 7 | flip at 6, then flip at 4 (2 and 6 are both red); the root is reset to black | perfect tree: 4; 2, 6; 1, 3, 5, 7; all black | [4] over [2], [6], over [1], [3], [5], [7] |
After 5: After 7:
B4 B4
/ \ / \
R2 B5 B2 B6
/ \ / \ / \
B1 B3 B1 B3 B5 B7
Insertion 5 shows a split propagating: the flip at 4 splits the temporary 4-node [3 4 5] and sends 4 up as a red right link, and the rotation at 2 makes [2 4] a left-leaning 3-node. Insertion 7 splits two 4-nodes in a row, [5 6 7] and then [2 4 6], and the second split happens at the root, so the tree gains a level. Sorted input, the worst case for a plain BST, gives a perfectly balanced tree here, and that continues: inserting 1 to 2^k − 1 in order gives a perfect all-black tree (checked with the code above for every k up to 12).
Where this connects
- Chapter 7: Binary Search Trees. The unbalanced baseline these structures fix
- Chapter 10: Multiway Search Trees and B-Trees. The 2-3-4 trees and B-tree splits, borrows and merges that red-black trees encode (Section 8.4)
- Chapter 21: Algorithm Design Using Data Structures. Why skip lists trade rotations for randomness
Chapter 9: Heaps and Priority Queues
9.1 The Heap Property
A heap is a complete binary tree satisfying the heap property:
- Max-heap: Parent ≥ Children (root is maximum)
- Min-heap: Parent ≤ Children (root is minimum)
Max-Heap:
90
/ \
80 70
/ \ / \
50 40 60 30
/ \
10 20
Min-Heap:
10
/ \
20 30
/ \ / \
50 40 60 70
9.2 Heap Array Representation
Heaps are typically stored in arrays due to their completeness:
Array representation of max-heap:
Index: 0 1 2 3 4 5 6 7 8
Array: [90 | 80 | 70 | 50 | 40 | 60 | 30 | 10 | 20]
↑
Root
Parent(i) = (i - 1) / 2
LeftChild(i) = 2 * i + 1
RightChild(i) = 2 * i + 2
The complete tree property guarantees no “holes” in the array.
9.3 Heap Operations
Maintaining the Heap Property: Heapify
Heapify restores the heap property at a node by “sifting down” larger children:
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}
Heapify at index 1 (value 30):
Before: After:
90 90
/ \ / \
[30] 70 → 50 70
/ \ / \
50 40 30 40
Building a Heap
Two approaches:
- Insert each element: O(n log n)
- Heapify from bottom up: O(n)
void build_heap(int arr[], int n) {
// Index of last non-leaf node = n/2 - 1
for (int i = n/2 - 1; i >= 0; i--)
heapify(arr, n, i);
}
Why O(n)? Most nodes are near leaves, requiring few swaps.
Extract Maximum/Minimum
int extract_max(int arr[], int *n) {
if (*n <= 0) return -1;
if (*n == 1) return arr[--(*n)];
int max = arr[0];
arr[0] = arr[--(*n)];
heapify(arr, *n, 0);
return max;
}
Insert
void insert(int arr[], int *n, int key) {
int i = (*n)++;
arr[i] = key;
// Sift up
while (i > 0 && arr[(i - 1) / 2] < arr[i]) {
swap(&arr[i], &arr[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
9.4 Heap Sort
Heap sort uses a heap to sort in O(n log n):
void heap_sort(int arr[], int n) {
// Build max heap
build_heap(arr, n);
// Extract elements
for (int i = n - 1; i > 0; i--) {
swap(&arr[0], &arr[i]); // Move max to end
heapify(arr, i, 0); // Heapify reduced heap
}
}
Worked trace on [4, 10, 3, 5, 1] (n = 5). The build phase calls heapify at i = 1, then i = 0; each extraction step swaps the root to the end and heapifies the shrunken prefix. The sorted tail is shown after the bar.
| step | action | array |
|---|---|---|
| build, i = 1 | 10 ≥ 5, 1: no swap | [4, 10, 3, 5, 1] |
| build, i = 0 | 4 sinks: swap with 10, then with 5 | [10, 5, 3, 4, 1] |
| i = 4 | swap 10 to the end, heapify size 4: 1 sinks past 5, 4 | [5, 4, 3, 1 | 10] |
| i = 3 | swap 5 to the end, heapify size 3: 1 sinks past 4 | [4, 1, 3 | 5, 10] |
| i = 2 | swap 4 to the end, heapify size 2: 3 ≥ 1, no swap | [3, 1 | 4, 5, 10] |
| i = 1 | swap 3 to the end | [1 | 3, 4, 5, 10] |
Each extraction costs one root-to-leaf heapify, at most ⌊log₂ n⌋ swaps, which is where the O(n log n) bound comes from.
Properties:
- In-place: O(1) extra space
- Not stable (equal elements may change relative order)
- O(n log n) worst case
- Good for embedded systems (no recursion, predictable)
9.5 Priority Queue Implementation
Heaps implement priority queues efficiently. This one is a min-priority queue (smallest priority first), the convention of Python’s heapq and of Dijkstra’s algorithm; flip the two < comparisons for a max-priority queue.
class PriorityQueue:
"""Min-priority queue: pop returns the item with the smallest priority."""
def __init__(self):
self.heap = []
def push(self, item, priority):
self.heap.append((priority, item))
self._sift_up(len(self.heap) - 1)
def pop(self):
if not self.heap:
return None
top = self.heap[0][1]
last = self.heap.pop()
if self.heap:
self.heap[0] = last
self._sift_down(0)
return top
def peek(self):
return self.heap[0][1] if self.heap else None
def _sift_up(self, i):
h = self.heap
while i > 0 and h[i][0] < h[(i - 1) // 2][0]:
h[i], h[(i - 1) // 2] = h[(i - 1) // 2], h[i]
i = (i - 1) // 2
def _sift_down(self, i):
h, n = self.heap, len(self.heap)
while True:
smallest = i
for c in (2 * i + 1, 2 * i + 2):
if c < n and h[c][0] < h[smallest][0]:
smallest = c
if smallest == i:
return
h[i], h[smallest] = h[smallest], h[i]
i = smallest
push and pop are O(log n) worst case, peek is O(1). The sifts compare only h[i][0], the priority, so items with equal priorities never get compared with each other; Section 9.8 shows why that matters when you use heapq directly.
9.6 Indexed Priority Queues and Decrease-Key
Dijkstra’s and Prim’s algorithms need a fourth operation: decrease-key(item, p), which lowers the priority of an item already in the queue (a shorter path to vertex v has just been found). Lowering a key can only break the heap property between that node and its parent, so the repair is a sift-up, O(log n). The hard part is finding the node. Heap order only relates ancestors to descendants; it says nothing about where a given item sits, so locating vertex v means scanning the array, O(n). With one decrease-key per edge, that turns Dijkstra into O(E · V).
The position map
Keep a second structure, pos, mapping each item to its current index in the heap array, and maintain the invariant heap[pos[x]] == x for every item x in the heap. Elements only move by swaps, and a swap moves exactly two elements, so every swap also updates two map entries: constant extra work, and no operation changes its asymptotic cost. decrease-key becomes “look up pos[x], change the priority, sift up”.
When the items are integers 0 to n − 1 (vertex ids), pos is a plain array; Sedgewick and Wayne’s IndexMinPQ keeps the heap of ids and its inverse as exactly this pair of arrays. The version below uses dictionaries so that any hashable item works, and builds on the sifts of Section 9.5 with every swap routed through _swap:
class IndexedMinHeap:
"""Min-heap of distinct items with priorities, plus a position map."""
def __init__(self):
self.heap = [] # items, in heap order
self.prio = {} # item -> current priority
self.pos = {} # item -> index of the item in self.heap
def __len__(self):
return len(self.heap)
def contains(self, item):
return item in self.pos
def insert(self, item, priority):
if item in self.pos:
raise KeyError(f"{item!r} is already in the heap")
self.heap.append(item)
self.prio[item] = priority
self.pos[item] = len(self.heap) - 1
self._sift_up(len(self.heap) - 1)
def pop(self):
"""Remove and return (item, priority) with the smallest priority."""
self._swap(0, len(self.heap) - 1)
item = self.heap.pop()
del self.pos[item]
if self.heap:
self._sift_down(0)
return item, self.prio.pop(item)
def decrease_key(self, item, priority):
if priority > self.prio[item]:
raise ValueError("decrease_key cannot increase a priority")
self.prio[item] = priority
self._sift_up(self.pos[item])
def _less(self, i, j):
return self.prio[self.heap[i]] < self.prio[self.heap[j]]
def _swap(self, i, j):
h = self.heap
h[i], h[j] = h[j], h[i]
self.pos[h[i]] = i # every move updates the map
self.pos[h[j]] = j
def _sift_up(self, i):
while i > 0 and self._less(i, (i - 1) // 2):
self._swap(i, (i - 1) // 2)
i = (i - 1) // 2
def _sift_down(self, i):
n = len(self.heap)
while True:
smallest = i
for c in (2 * i + 1, 2 * i + 2):
if c < n and self._less(c, smallest):
smallest = c
if smallest == i:
return
self._swap(i, smallest)
i = smallest
insert, pop and decrease_key do O(log n) comparisons and swaps in the worst case, and contains is O(1). With dictionaries each map access is O(1) on average (Chapter 12); with integer ids and arrays it is O(1) worst case. An increase-key is the mirror image (sift down instead of up), and deleting an arbitrary item is “swap it with the last element, pop, then sift the moved element up or down”.
Worked trace. Insert A:5, B:3, C:8, D:6, E:4. The heap and map are then:
heap: [B:3, E:4, C:8, D:6, A:5] pos: A→4 B→0 C→2 D→3 E→1
decrease_key('D', 1) reads pos[D] = 3 in O(1) instead of searching. D’s parent is index 1 (E:4): swap, so pos[D] = 1, pos[E] = 3. Its parent is now index 0 (B:3): swap, so pos[D] = 0, pos[B] = 1. Two swaps, four map updates:
heap: [D:1, B:3, C:8, E:4, A:5] pos: A→4 B→1 C→2 D→0 E→3
Dijkstra on top of it keeps each vertex in the heap at most once, so the heap never holds more than V entries:
def dijkstra_indexed(graph, source):
"""graph[u] is a list of (v, weight) pairs with weight >= 0.
Returns distances to the vertices reachable from source."""
dist = {source: 0}
pq = IndexedMinHeap()
pq.insert(source, 0)
while pq:
u, d = pq.pop() # d is final: there are no stale entries
for v, w in graph[u]:
if v not in dist: # first time v is reached
dist[v] = d + w
pq.insert(v, d + w)
elif pq.contains(v) and d + w < dist[v]:
dist[v] = d + w
pq.decrease_key(v, d + w)
return dist
V pops and at most E decrease-keys give O((V + E) log V) worst case.
The alternative: lazy deletion
Instead of changing an entry, push a new (priority, item) entry and leave the old one where it is. An item can now have several entries; only the one with the smallest priority is current. When an entry is popped, check whether it is still current and skip it if not. Chapter 11 does exactly this in both Dijkstra’s algorithm (if d > dist[u]: continue) and Prim’s algorithm (if v in visited: continue), because Python’s heapq has no decrease-key.
Each relaxation pushes at most one entry, so the heap holds up to E entries instead of V. Every push and pop is then O(log E), and since E ≤ V², log E ≤ 2 log V: the total is still O(E log V), the same bound as the indexed version. The price is memory, O(E) instead of O(V), and the work of popping stale entries. The same trick deletes arbitrary items: mark the entry as removed and skip it when it surfaces (the heapq documentation gives this recipe).
Which to use:
- Lazy deletion is the default when the heap comes from a library: Python’s
heapq, C++’sstd::priority_queueand Java’sPriorityQueuehave no decrease-key (Java’sremove(Object)is a linear scan). It is also simpler and often faster in practice, because entries are plain tuples in one array and no map is updated on every swap. Sparse graphs, where E is a small multiple of V, lose little memory to stale entries. - An indexed heap is better when memory must stay proportional to the live items (dense graphs with many improvements can fill a lazy heap with up to E entries); when you need to read or change an item’s current priority, as a scheduler re-prioritising a task or a simulation cancelling an event does; when you need increase-key or delete without accumulating garbage; or when a d-ary heap (Section 9.7) is meant to make decrease-key cheap.
Node-based heaps (binomial, Fibonacci, pairing: Sections 9.9 to 9.11) solve the same “find the element” problem differently: insert returns a pointer to the node, a handle, which the caller keeps and passes back to decrease-key.
9.7 d-ary Heaps
Nothing forces two children per node. In a d-ary heap each node has up to d children, stored in the same level-by-level array:
Parent(i) = (i - 1) / d
Child(i, j) = d * i + j for j = 1, ..., d
With d = 2 these are the formulas of Section 9.2. The height is about log_d n = log₂ n / log₂ d, so the tree is shallower. The two sifts generalise directly (min-heap shown):
def dary_sift_up(a, i, d):
while i > 0 and a[i] < a[(i - 1) // d]:
p = (i - 1) // d
a[i], a[p] = a[p], a[i]
i = p
def dary_sift_down(a, i, d):
n = len(a)
while True:
first = d * i + 1 # children are first .. first + d - 1
if first >= n:
return
c = min(range(first, min(first + d, n)), key=a.__getitem__)
if a[c] >= a[i]:
return
a[i], a[c] = a[c], a[i]
i = c
Build-heap runs dary_sift_down from the last internal node, (n − 2) // d, down to 0, still O(n).
The trade-off. A sift-up does one comparison per level, so insert and decrease-key cost O(log_d n) worst case: larger d is strictly better for them. A sift-down must find the smallest of d children at every level (d − 1 comparisons) and compare it with the sinking element, so extract-min costs O(d log_d n): beyond some point, larger d makes it worse. For n = 10⁶:
| d | levels (log_d n) | sift-up comparisons | sift-down comparisons (d log_d n) |
|---|---|---|---|
| 2 | 19.9 | 19.9 | 39.9 |
| 4 | 10.0 | 10.0 | 39.9 |
| 8 | 6.6 | 6.6 | 53.2 |
| 16 | 5.0 | 5.0 | 79.7 |
Why d = 4 often beats d = 2 in practice. The table shows the 4-ary heap doing the same number of comparisons in a sift-down as the binary heap (4 per level, half the levels), half the comparisons in a sift-up, and half the element moves in both. The bigger win is memory. The d children of a node are adjacent in the array, so one cache line fetch brings in all of them: four 16-byte (priority, id) entries fill exactly one 64-byte line if the array is aligned so that each sibling group starts on a line boundary. In a large binary heap every level below the top few is a separate cache miss; the 4-ary heap has half the levels and so roughly half the misses (Chapter 16 covers why misses dominate). LaMarca and Ladner measured this effect in 1996. Production libraries agree: .NET’s PriorityQueue<TElement, TPriority> is a 4-ary min-heap, and Go’s runtime keeps its timers in a 4-ary heap.
Choosing d for Dijkstra. Dijkstra does V extract-mins and up to E decrease-keys, for a total of O(V · d log_d V + E log_d V). Choosing d ≈ E/V (at least 2) balances the two terms and gives O(E log_(E/V) V). On a dense graph with E = V^(1+ε) that is O(E/ε), linear in E for any fixed ε, with nothing fancier than an array. On a sparse graph E/V is a small constant and d = 2 to 4 is the right choice anyway. Treat E/V as a starting point for tuning: the cost model above charges a decrease-key to every edge, and real runs relax far fewer.
9.8 Heap Patterns
Three problems come up again and again, and each is a few lines with a heap.
Top k of a stream
To keep the k largest of n values arriving one at a time, keep a min-heap holding the k largest seen so far. For each new x, the only question is whether x beats the weakest of the current k, and the min-heap keeps that weakest value at the root: if x > heap[0], replace the root with x (heapq.heapreplace, one pop and push in a single sift). Each value costs at most one O(log k) operation, so the total is O(n log k) worst case with O(k) memory, against O(n log n) time and O(n) memory for sorting everything. A max-heap would put the best value at the root, which is the one you never evict. For the k smallest, mirror it with a max-heap of size k. Exercise 9.6 asks you to write it; heapq.nlargest(k, iterable) and heapq.nsmallest are the library versions.
k-way merge
To merge k sorted lists with N elements in total, keep a heap of the current head of each list. Pop the smallest, output it, and push the next element of the list it came from:
import heapq
def k_way_merge(lists):
heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap)
out = []
while heap:
value, i, j = heapq.heappop(heap) # j-th element of list i
out.append(value)
if j + 1 < len(lists[i]):
heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
return out
k_way_merge([[1, 4, 9], [2, 3, 10], [5, 6]]) returns [1, 2, 3, 4, 5, 6, 9, 10]. The heap never holds more than k entries, so each of the N steps is O(log k) and the merge is O(N log k) worst case, against O(N k) for scanning all k heads at every step. On equal values the tuple comparison falls through to the list index i, which is unique, so it never compares anything further. heapq.merge(*iterables) does the same thing lazily, as a generator, which is what you want when the inputs are files too big for memory.
This is the merge phase of external merge sort, which merges hundreds of sorted runs in one pass (Chapter 16), of LSM-tree compaction, which merges sorted runs into one, and of a search engine combining sorted posting lists.
Running median
To report the median after every value of a stream, split the values seen so far into two heaps: low, a max-heap holding the smaller half, and high, a min-heap holding the larger half. Keep two invariants:
- Order: every value in
lowis ≤ every value inhigh, that is, max(low) ≤ min(high). - Balance: len(low) = len(high) or len(low) = len(high) + 1.
Then the median is max(low) when the count is odd and the average of max(low) and min(high) when it is even, both readable at the roots in O(1).
import heapq
class RunningMedian:
def __init__(self):
self.low = [] # max-heap of the smaller half (values negated)
self.high = [] # min-heap of the larger half
def add(self, x):
if not self.low or x <= -self.low[0]:
heapq.heappush(self.low, -x)
else:
heapq.heappush(self.high, x)
# restore balance: len(low) - len(high) must be 0 or 1
if len(self.low) > len(self.high) + 1:
heapq.heappush(self.high, -heapq.heappop(self.low))
elif len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def median(self):
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2
Choosing the side by comparing with max(low) preserves the order invariant. If the sizes are then off by one too many, moving the top of the bigger heap across preserves it too, because that top is the largest of low (or the smallest of high), so it lands on the correct side of every value in the other heap. Each add is at most two pushes and one pop: O(log n) worst case.
Worked trace on the stream 5, 15, 1, 3, 8, 7, 9, 10:
| add | goes to | rebalance | low | high | median |
|---|---|---|---|---|---|
| 5 | low (empty) | {5} | {} | 5 | |
| 15 | high (15 > 5) | {5} | {15} | 10 | |
| 1 | low (1 ≤ 5) | {1, 5} | {15} | 5 | |
| 3 | low (3 ≤ 5) | move 5 to high | {1, 3} | {5, 15} | 4 |
| 8 | high (8 > 3) | move 5 to low | {1, 3, 5} | {8, 15} | 5 |
| 7 | high (7 > 5) | {1, 3, 5} | {7, 8, 15} | 6 | |
| 9 | high (9 > 5) | move 7 to low | {1, 3, 5, 7} | {8, 9, 15} | 7 |
| 10 | high (10 > 7) | {1, 3, 5, 7} | {8, 9, 10, 15} | 7.5 |
The two heaps store every value, so memory is O(n). A sliding-window median must also delete the value that leaves the window from whichever heap holds it, which needs lazy deletion or an indexed heap (Section 9.6). For approximate quantiles of an unbounded stream in fixed memory, use a sketch such as t-digest (Chapter 14).
Python heapq idioms
heapq is a set of functions over a plain list, not a class, and it is a min-heap: h[0] is the smallest element. heapify is the O(n) bottom-up build of Section 9.3; heappush and heappop are O(log n); heapreplace(h, x) pops then pushes and heappushpop(h, x) pushes then pops, each with a single sift.
- Max-heap: push
-xand read-h[0]. This works for numbers; for (priority, item) tuples, negate only the priority. Python 3.14 addedheappush_max,heappop_max,heapify_maxand related functions; on earlier versions, negate. heapq.nlargest(k, iterable, key=None)andnsmallestare the top-k pattern above, O(n log k). For k = 1,maxandminare faster; for k close to n,sorted(iterable)[:k]is.heapq.merge(*iterables, key=None)is the lazy k-way merge.- Tie-breakers. Tuples compare element by element, so two entries with equal priorities fall through to comparing their payloads. That fails outright for payloads without an order, and is wasted work for the rest. Put a unique, increasing counter between the priority and the payload:
import heapq
import itertools
tasks, counter = [], itertools.count()
def push(task, priority):
heapq.heappush(tasks, (priority, next(counter), task))
push({"name": "backup"}, 2)
push({"name": "email"}, 1)
push({"name": "report"}, 1) # ties with "email" on priority
print(heapq.heappop(tasks)[2]) # {'name': 'email'}: the counter broke the tie
Without the counter the third push raises TypeError: '<' not supported between instances of 'dict' and 'dict'. The counter also makes equal priorities come out first-in, first-out, which a heap otherwise does not guarantee (heaps are not stable).
9.9 Binomial Heaps
Binomial heaps support efficient meld (merge) operations.
Binomial Trees
A binomial tree B_k has:
- 2^k nodes
- Height k
- Made by linking two B_(k-1) trees
B_0: ○ (1 node)
B_1: ○ (2 nodes)
│
○
B_2: ○ (4 nodes)
/│
○ ○
│
○
B_3: ○ (8 nodes)
/│\
○ ○ ○
/│ │
○ ○ ○
│
○
Binomial Heap Structure
A binomial heap is a collection of binomial trees satisfying:
- Each binomial tree is a min-heap (or max-heap)
- At most one binomial tree of each order k
- Trees are stored in a root list by increasing order
Binomial Heap (7 nodes):
- B_2 tree (4 nodes)
- B_1 tree (2 nodes)
- B_0 tree (1 node)
Root list, by increasing order:
B_0 B_1 B_2
○ → ○ → ○ → NULL
│ /│
○ ○ ○
│
○
Operations:
- Insert: O(1) amortized, O(log n) worst case (create new B_0, merge)
- Extract-min: O(log n) (remove min, merge remaining trees)
- Meld: O(log n)
- Decrease-key: O(log n)
9.10 Fibonacci Heaps
Fibonacci heaps achieve O(1) amortized insert and decrease-key, making them ideal for algorithms like Dijkstra’s.
Structure
- Roots of trees form a circular doubly-linked list
- One pointer to minimum element
- Trees are heap-ordered but not necessarily binomial
- Lazy consolidation: don’t immediately consolidate after deletions
Fibonacci Heap:
○20 ←── minimum
/│\
○ ○ ○
││││
○ ○ ○ ○
...
Actual structure varies, no fixed binomial structure
Amortized Analysis
Potential function: Φ = number of trees + 2 × marked nodes
| Operation | Actual | Amortized |
|---|---|---|
| Insert | O(1) | O(1) |
| Union | O(1) | O(1) |
| Find-min | O(1) | O(1) |
| Extract-min | O(n) | O(log n) |
| Decrease-key | O(1)* | O(1) |
| Delete | O(n) | O(log n) |
*Plus one unit per cascading cut; the potential pays for the cuts. Extract-min’s actual cost is linear in the number of roots, which can be n after n inserts.
Why “Fibonacci”?
A node of degree k roots a subtree of at least F(k+2) ≥ φ^k nodes, where F is the Fibonacci sequence and φ ≈ 1.618 is the golden ratio. That gives the name, and it means a node has at most log_φ n ≈ 1.44 log₂ n children.
9.11 Pairing Heaps
Pairing heaps are simpler than Fibonacci heaps with similar (often better) practical performance.
Structure
- Multiway trees with heap ordering
- Roots linked in a list
- No balance information stored
Operations
class PairingNode:
def __init__(self, value):
self.value = value
self.child = None # leftmost child
self.sibling = None # next sibling to the right
def link(a, b):
# Link two heaps; the smaller root becomes the parent
if a is None: return b
if b is None: return a
if b.value < a.value:
a, b = b, a
b.sibling = a.child
a.child = b
return a
def extract_min(root):
# Remove root, link children in pairs left to right,
# then link the pairs together right to left
pairs = []
node = root.child
while node:
first, second = node, node.sibling
node = second.sibling if second else None
first.sibling = None
if second:
second.sibling = None
pairs.append(link(first, second))
result = None
for p in reversed(pairs):
result = link(p, result)
return result
Empirical Performance
Despite weaker theoretical guarantees (decrease-key is not known to be O(1) amortized), pairing heaps:
- Perform as well as or better than Fibonacci heaps in practice
- Are much simpler to implement
- Are cache-friendly
9.12 Applications of Heaps
Sorting: Heap sort Priority queues: Task scheduling, event simulation Graph algorithms: Dijkstra’s (with decrease-key), Prim’s Data compression: Huffman coding Operating systems: Timer queues, CPU scheduling Statistics: Kth largest/smallest elements Stream processing: Sliding window median
9.13 Historical Context
The heap was introduced by J.W.J. Williams in 1964 as part of heap sort. The binary heap structure was further analyzed by Floyd in 1964, who proved that heapify works in O(n) time.
Fibonacci heaps were introduced by Fredman and Tarjan in 1987, revolutionizing graph algorithms by enabling faster shortest paths.
Binomial heaps were introduced by Vuillemin in 1978, providing efficient meld operations.
Donald B. Johnson introduced d-ary heaps in 1975 for minimum spanning trees, and in 1977 used them for shortest paths in sparse graphs with d chosen from the ratio E/V. LaMarca and Ladner’s 1996 study of how caches affect heaps is the standard reference for why a cache-aligned 4-ary heap beats a binary one.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
9.1 ★ Is it a heap? Using the index formulas of Section 9.2, decide which of these arrays are max-heaps. For any that is not, name the first index whose value is larger than its parent’s.
(a) [50, 30, 40, 10, 20, 35, 5]
(b) [50, 40, 30, 35, 45, 10, 20]
(c) [9, 9, 8, 7, 9]
Solution
Check every i ≥ 1 against Parent(i) = (i − 1) / 2.
(a) Yes. 50 ≥ 30, 40; 30 ≥ 10, 20; 40 ≥ 35, 5.
(b) No. Index 4 holds 45, and its parent is index (4 − 1)/2 = 1, which holds 40. (Index 3, holding 35, is fine: 35 ≤ 40.)
(c) Yes. 9 ≥ 9, 8 at the root; index 1 (9) ≥ its children 7 and 9. The heap property is ≥, so equal keys are allowed anywhere.
9.2 ★ Insert, then extract. Start from the max-heap array in Section 9.2, [90, 80, 70, 50, 40, 60, 30, 10, 20]. Run insert with key 85, then extract_max. Show the array after each, and list every swap.
Solution
Insert 85. It goes at index 9. Its parent is index 4 (40): swap. Now at index 4, parent index 1 (80): swap. Now at index 1, parent index 0 (90): 90 ≥ 85, stop. Two swaps.
[90, 85, 70, 50, 80, 60, 30, 10, 20, 40]
extract_max. Returns 90. The last element, 40, moves to index 0 and n becomes 9. heapify(arr, 9, 0): children are 85 (index 1) and 70 (index 2), so swap with 85. At index 1: children 50 (index 3) and 80 (index 4), so swap with 80. At index 4: children would be at 9 and 10, both ≥ n, so stop.
[85, 80, 70, 50, 40, 60, 30, 10, 20]
Both operations walk one root-to-leaf path, so each is O(log n): here at most 3 levels.
9.3 ★★ Two ways to build a heap. Build a max-heap from [1, 2, 3, 4, 5, 6, 7] in two ways: (a) with build_heap, showing the array after each heapify call; (b) by calling insert for 1, 2, …, 7 in turn on an empty heap. Count the swaps in each. Are the two heaps the same?
Hint
For (a), n = 7, so the loop runs i = 2, 1, 0. Remember that heapify keeps sifting down after a swap.
Solution
(a) build_heap:
| step | array | swaps |
|---|---|---|
| start | [1, 2, 3, 4, 5, 6, 7] | |
| heapify(i = 2): 3 vs 6, 7 | [1, 2, 7, 4, 5, 6, 3] | 1 |
| heapify(i = 1): 2 vs 4, 5 | [1, 5, 7, 4, 2, 6, 3] | 1 |
| heapify(i = 0): 1 vs 5, 7, then 1 vs 6, 3 | [7, 5, 6, 4, 2, 1, 3] | 2 |
4 swaps, result [7, 5, 6, 4, 2, 1, 3].
(b) Repeated insert. Each new key is the largest so far, so it sifts all the way to the root:
| insert | array after | swaps |
|---|---|---|
| 1 | [1] | 0 |
| 2 | [2, 1] | 1 |
| 3 | [3, 1, 2] | 1 |
| 4 | [4, 3, 2, 1] | 2 |
| 5 | [5, 4, 2, 1, 3] | 2 |
| 6 | [6, 4, 5, 1, 3, 2] | 2 |
| 7 | [7, 4, 6, 1, 3, 2, 5] | 2 |
10 swaps, result [7, 4, 6, 1, 3, 2, 5].
Both are valid max-heaps but they are different arrays: a set of keys has many valid heap layouts. Sorted ascending input is the worst case for repeated insertion (every key climbs to the root, about n log n swaps in total), which is the gap between the O(n log n) and O(n) approaches in Section 9.3.
9.4 ★★ Why build_heap is O(n). Section 9.3 says “most nodes are near leaves”. Make that precise. (a) For a perfect heap with n = 2^k − 1 nodes, heapify on a node at height h does at most h swaps. Show that the total number of swaps is at most n − log₂(n + 1), and check the value for n = 15. (b) Contrast this with building by repeated insert, where a node at depth d may do d swaps.
Hint
There are 2^(k−1−h) nodes at height h. Sum h × 2^(k−1−h) over h = 0, …, k − 1.
Solution
(a) In a perfect tree with k levels there are 2^(k−1) leaves (height 0), 2^(k−2) nodes at height 1, and so on, up to 1 node (the root) at height k − 1. Each does at most h swaps, so the total is at most
S = Σ_{h=0}^{k−1} h × 2^(k−1−h) = 2^k − k − 1.
(One way to see this: the sum satisfies S(k) = 2 S(k − 1) + (k − 1), since the root contributes k − 1 and its two subtrees each contribute S(k − 1); 2^k − k − 1 satisfies the same recurrence with S(1) = 0.) Since n = 2^k − 1 and k = log₂(n + 1),
S = n − log₂(n + 1) < n.
For n = 15 (k = 4): 8 leaves × 0 + 4 × 1 + 2 × 2 + 1 × 3 = 11 = 15 − 4. Running build_heap on [0, 1, ..., 14] (ascending, so every key wants to sink as far as possible) does exactly 11 swaps.
(b) With repeated insert, the cost of a node is its depth, not its height. Half the nodes are at depth k − 1, so the total can reach about (n/2) × log₂ n, which is Θ(n log n). build_heap wins because the many nodes near the bottom are the cheap ones; repeated insert makes them the expensive ones.
9.5 ★★ Find the bug. This Python port of heap_sort returns unsorted output:
def sift_down(a, n, i):
while True:
largest = i
l, r = 2 * i + 1, 2 * i + 2
if l < n and a[l] > a[largest]:
largest = l
if r < n and a[r] > a[largest]:
largest = r
if largest == i:
return
a[i], a[largest] = a[largest], a[i]
i = largest
def heap_sort(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down(a, n, i)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, n, 0)
Trace it on [3, 1, 2], find the bug, and fix it.
Solution
[3, 1, 2] is already a max-heap, so the build loop changes nothing.
- end = 2: swap a[0], a[2] →
[2, 1, 3]. 3 is now in its final place. Butsift_down(a, 3, 0)still treats index 2 as part of the heap: 2 < 3, so it swaps them back →[3, 1, 2]. - end = 1: swap a[0], a[1] →
[1, 3, 2].sift_down(a, 3, 0): largest child is 3 →[3, 1, 2].
Result: [3, 1, 2], unchanged and unsorted.
The bug is the size passed to sift_down in the second loop. After moving the maximum to a[end], the heap is only a[0:end]; the sorted tail must be out of reach. The C version in Section 9.4 gets this right with heapify(arr, i, 0). Fix:
def heap_sort(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down(a, n, i)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, end, 0) # the heap is a[0:end]
With the fix, [3, 1, 2] becomes [1, 2, 3].
9.6 ★★ Top k of a stream. You receive n numbers one at a time and must report the k largest at the end, using O(k) memory and O(n log k) time. Implement top_k(stream, k) with Python’s heapq (a min-heap). Why a min-heap, when you want the largest values?
Hint
Keep the best k seen so far. When a new value arrives, which of the current k is the one it would replace?
Solution
import heapq
def top_k(stream, k):
heap = [] # min-heap holding the k largest seen so far
for x in stream:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]: # beats the smallest of the current top k
heapq.heapreplace(heap, x)
return sorted(heap, reverse=True)
top_k([5, 1, 9, 3, 7, 2, 8], 3) returns [9, 8, 7].
The question for each new value is “is it bigger than the weakest member of the current top k?”, so the structure must expose the minimum of those k in O(1): a min-heap of size k. Each element costs at most one O(log k) push or replace, so the total is O(n log k) time and O(k) space. A max-heap of all n items would also work but costs O(n) memory, which a stream may not allow. This is the “Kth largest” application in Section 9.12: after the loop, heap[0] is the k-th largest value.
9.7 ★★★ Binomial heap insertion is a binary counter. (a) Because B_k has 2^k nodes and a binomial heap holds at most one tree of each order (Section 9.9), a heap with n nodes contains B_k exactly when bit k of n is 1. Which trees make up a 13-node heap? (b) Inserting creates a B_0 and then links equal-order trees until all orders are distinct. How many links does inserting into a 7-node heap cause, and what is the result? (c) Prove that n inserts into an empty binomial heap perform fewer than n links in total, so insert is O(1) amortized even though a single insert can take Θ(log n) time.
Hint
Linking two B_j trees into one B_(j+1) is a carry in binary addition. Use the number of trees as a potential, or count how often each bit can flip from 1 to 0.
Solution
(a) 13 = 1101 in binary, so the heap holds B_3, B_2 and B_0 (8 + 4 + 1 nodes).
(b) 7 = 111: the heap holds B_0, B_1, B_2. The new B_0 links with the existing B_0 to make a B_1, which links with the existing B_1 to make a B_2, which links with the existing B_2 to make a B_3. 3 links, and the result is a single B_3 with 8 nodes, just as 111 + 1 = 1000 has three carries.
(c) Each link combines two trees into one, so it reduces the number of trees by 1, and each insert adds 1 tree. Let T be the number of trees, which starts at 0 and is never negative. After n inserts, (trees created) − (links) = T_final ≥ 1, so links ≤ n − 1 < n.
So n inserts cost O(n) in total: O(1) amortized per insert. A single insert into a heap with n = 2^k − 1 nodes still does k links, which is the O(log n) worst case. Counting the links per insert for n = 0 to 15 gives 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4 (the number of trailing 1 bits of the current size), summing to 15 for 16 inserts.
9.8 ★★ Keep the map honest. Continue the worked trace of Section 9.6 from heap: [D:1, B:3, C:8, E:4, A:5]. (a) Run pop(), then decrease_key('C', 2), and show heap and pos after each. (b) Suppose _sift_down swapped with a plain h[i], h[smallest] = h[smallest], h[i] instead of calling _swap. Redo the pop(), then call decrease_key('A', 0) followed by pop(). What comes out, and why?
Solution
(a) pop() first swaps index 0 with the last index, so A:5 is at the root (pos[A] = 0), then removes D. _sift_down(0): A:5 against B:3 and C:8, swap with B; A is now at index 1, whose only child is index 3 (E:4), swap again. It returns ('D', 1):
heap: [B:3, E:4, C:8, A:5] pos: A→3 B→0 C→2 E→1
decrease_key('C', 2) reads pos[C] = 2; its parent is index 0 (B:3), so one swap:
heap: [C:2, E:4, B:3, A:5] pos: A→3 B→2 C→0 E→1
(b) The heap array after the buggy pop() is the same, [B, E, C, A], but the two swaps inside the sift-down never touched the map, which still says A→0, B→1, C→2, E→3 (A→0 was written by the _swap at the start of pop). decrease_key('A', 0) reads pos[A] = 0, sets A’s priority to 0 and sifts up from index 0, which does nothing. A:0 is left at index 3 below E:4 and B:3, so the heap property is broken, and the next pop() returns ('B', 3) while A has priority 0. The failure surfaces far from the cause, which is why every move in an indexed heap must go through one function that updates the map.
9.9 ★★ Choosing d for Dijkstra. Use the cost model of Section 9.7: V · d · log_d V comparisons for the extract-mins plus E · log_d V for the decrease-keys. (a) For V = 10⁴ and E = 10⁶, evaluate it for d = 2, 4, 16 and d = E/V = 100. (b) Show that the exact minimiser satisfies d(ln d − 1) = E/V, and find it for these numbers. (c) The model counts comparisons only. Name one effect that pushes the best d in practice lower, and one that pushes it higher.
Hint
Write log_d V = ln V / ln d and minimise (V d + E) / ln d.
Solution
(a) log₂ 10⁴ ≈ 13.29, so:
| d | V · d · log_d V | E · log_d V | total |
|---|---|---|---|
| 2 | 0.27 M | 13.29 M | 13.55 M |
| 4 | 0.27 M | 6.64 M | 6.91 M |
| 16 | 0.53 M | 3.32 M | 3.85 M |
| 100 | 2.00 M | 2.00 M | 4.00 M |
At d = E/V the two terms are equal, which is what “balancing” means. The binary heap is more than 3 times worse than d = 16 or d = 100, because on a graph this dense the decrease-keys dominate and a binary heap makes them pay for 13 levels.
(b) The cost is ln V × g(d) with g(d) = (V d + E) / ln d. Then g′(d) = [V ln d − (V d + E)/d] / (ln d)², which is zero when V d ln d = V d + E, that is d(ln d − 1) = E/V. For E/V = 100 this gives d ≈ 38, with total ≈ 3.49 M. The cost curve is flat near its minimum: anything from about 16 to 100 is within 15%. So d ≈ E/V is the right order of magnitude, not the exact optimum.
(c) Lower: most relaxations do not improve a distance, so real runs do far fewer than E decrease-keys, which shifts weight to extract-min, where large d costs more. Higher: the d children of a node are contiguous, so scanning them costs about one cache miss whatever d is, up to a cache line’s worth; counting misses rather than comparisons favours d up to 4 or 8.
9.10 ★★ Find the bug: running median. A colleague “simplifies” RunningMedian.add from Section 9.8 to keep the sizes balanced without any comparisons:
def add(self, x):
if len(self.low) <= len(self.high):
heapq.heappush(self.low, -x)
else:
heapq.heappush(self.high, x)
Find a stream of three values on which median() is wrong, say which invariant breaks, and fix add while keeping it O(log n).
Solution
The balance invariant always holds, but nothing maintains the order invariant. On 1, 2, 3: 1 goes to low, 2 to high, 3 to low. Now low = {1, 3} and high = {2}, so median() returns max(low) = 3, but the median of {1, 2, 3} is 2. The order invariant max(low) ≤ min(high) is broken (3 > 2).
One fix is the original add. Another that needs no case analysis is to push every value through both heaps, so whatever crosses over is guaranteed to be the extreme of its side:
def add(self, x):
heapq.heappush(self.low, -x)
heapq.heappush(self.high, -heapq.heappop(self.low)) # largest of low moves up
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
After the first two lines, the value moved to high is the largest in low, so the order invariant holds. The last two lines move the smallest of high back when high has become too big, which also preserves order. That is at most three pushes and two pops, O(log n) worst case.
Where this connects
- Chapter 11: Graphs, Modeling Relationships. Dijkstra and Prim with lazy deletion, the main consumers of decrease-key
- Chapter 19: Emerging and Specialized Structures. Why Fibonacci heaps win on paper and lose in practice
- Chapter 21: Algorithm Design Using Data Structures. The greedy algorithms that are built on this structure
Chapter 10: Multiway Search Trees and B-Trees
10.1 Beyond Binary: The Need for Multiway Trees
Binary trees require O(log n) levels, which means O(log n) disk accesses for large trees stored on disk. If each level requires a disk read, this is still costly.
B-trees solve this by allowing more than two children per node:
Binary tree for 1 million keys:
Height ≈ 20 (with good balance)
Disk accesses for search: 20
B-tree with 1000 children per node:
Height ≈ 3
Disk accesses for search: 3
This dramatic reduction in height makes B-trees ideal for disk-based storage.
10.2 B-Tree Definition
A B-tree of order m satisfies:
- Every node has at most m children
- Every internal node (except root) has at least ⌈m/2⌉ children
- The root has at least 2 children (unless it’s a leaf)
- A node with k children contains k-1 keys
- All leaves appear at the same depth
B-tree of order 5 (max 4 keys, 5 children):
┌───────────────┐
│ 20 │ 40 │ 60 │
└───────────────┘
/ │ │ \
[0-20) [20-40) [40-60) [60+)
Minimum degree and the height bound
The algorithms below are easiest to state with the minimum degree t ≥ 2, the notation of CLRS: every node except the root holds between t − 1 and 2t − 1 keys (so an internal one has between t and 2t children), and a non-empty root holds between 1 and 2t − 1. This is a B-tree of even order m = 2t. The code calls the two limits MAX_KEYS = 2t − 1 and MIN_KEYS = t − 1. The even order is what makes single-pass updates work: a full node of 2t − 1 keys splits around its median into two legal nodes of t − 1 keys (Section 10.3), and two minimal nodes plus the separator between them merge into a node of exactly 2t − 1 keys (Section 10.4). Exercise 10.6 asks what goes wrong with an odd order.
The lower limit is what bounds the height. Count edges, so a tree of height h has h + 1 levels and a search reads at most h + 1 nodes. The thinnest tree of height h has a root with one key and two children, then at least 2t nodes at depth 2, and in general at least 2t^(d−1) nodes at depth d ≥ 1, each with at least t − 1 keys. So
n ≥ 1 + (t − 1) × Σ_{d=1}^{h} 2t^(d−1) = 1 + 2(t^h − 1) = 2t^h − 1,
and therefore h ≤ log_t((n + 1)/2) in the worst case.
Put in numbers: with 8-byte keys and 8-byte child pointers, t = 500 (up to 999 keys and 1,000 children per node) fills a 16 KB page, InnoDB’s default page size. For n = 10⁹ keys, log₅₀₀(5 × 10⁸) ≈ 3.22, so h ≤ 3: no root-to-leaf path has more than 4 nodes. The tree cannot be shorter either: with every node full, 3 levels hold at most 1000³ − 1 = 999,999,999 keys, one short of a billion. Every such tree has exactly 4 levels, whatever order the keys arrived in. Since a node is one page and one page is one disk read, a cold lookup costs 4 reads. The root is always cached, which makes it 3, and the second level (at most 1,000 pages, about 16 MB) usually fits in the buffer pool as well, leaving 2. A balanced binary tree over the same keys has about log₂ 10⁹ ≈ 30 levels. Exercise 10.3 repeats the calculation for m = 200.
10.3 B-Tree Operations
Search
Similar to BST but with linear search within nodes:
def btree_search(node, key):
i = 0
while i < len(node.keys) and key > node.keys[i]:
i += 1
if i < len(node.keys) and key == node.keys[i]:
return (node, i) # Found
if node.is_leaf:
return None # Not found
return btree_search(node.children[i], key)
Insert
- Find leaf where key belongs
- Insert key (split if node is full)
def btree_insert(root, key):
if len(root.keys) == MAX_KEYS:
# Split root
new_root = split_root(root)
root = new_root
_insert(root, key)
return root
def _insert(node, key):
i = 0
while i < len(node.keys) and key > node.keys[i]:
i += 1
if node.is_leaf:
node.keys.insert(i, key)
else:
if len(node.children[i].keys) == MAX_KEYS:
split_child(node, i)
if key > node.keys[i]:
i += 1
_insert(node.children[i], key)
Splitting Nodes
When a node is full, split it:
Overflowing node with 5 keys (order 5 allows at most 4):
┌─────────────────┐
│10│20│30│40│50│ ← Split into:
└─────────────────┘
↓
┌───────┐ ┌───────┐
│10│20│ │ │40│50│ (two nodes)
└───┴───┘ └───┴───┘
│
┌───┴───┐
│ 30 │ ← Median key goes up
└───────┘
10.4 Deletion
Insertion can only overflow a node. Deletion has two new problems: removing a key can underflow a node (leave it with fewer than t − 1 keys), and the key may sit in an internal node, where taking it out would leave two children with no separator between them.
Bayer and McCreight’s original algorithm deletes first and repairs underflow on the way back up, which may cascade to the root. The version here, from CLRS, mirrors the proactive splitting of Section 10.3. Insertion never descends into a full node; deletion never descends into a minimal one. The invariant is:
Whenever the deletion moves into a node other than the root, that node has at least t keys, one more than the minimum.
With that guarantee, the node can lose a key (to a leaf deletion below, or to a merge of two of its children) and still be legal, so nothing ever has to be fixed on the way back up. The deletion is a single pass from root to leaf, with no parent pointers and no stack of ancestors.
At a node x, find the first position i with key <= x.keys[i], exactly as search does. Then one of three cases applies.
Case 1: the key is in x and x is a leaf. Remove it. By the invariant x had at least t keys (or is the root), so it still has at least t − 1.
Case 2: the key is x.keys[i] and x is internal. Let y = x.children[i] be the child just left of the key and z = x.children[i + 1] the child just right of it.
- 2a. If y has at least t keys, find the key’s predecessor k′, the largest key in y’s subtree (follow the rightmost child down to a leaf). Overwrite the key with k′, then recursively delete k′ from y. The invariant holds for y because it has t keys.
- 2b. Otherwise, if z has at least t keys, do the same with the successor, the smallest key in z’s subtree.
- 2c. Otherwise y and z both have t − 1 keys. Merge them: move the key down from x into y, append all of z’s keys and children to y, and remove the key and the pointer to z from x. y now holds (t − 1) + 1 + (t − 1) = 2t − 1 keys, including the key to delete, so recursively delete the key from y.
Case 3: the key is not in x and x is internal. If the key is in the tree at all, it is in the subtree c = x.children[i]. If c has at least t keys, just descend. If it has only t − 1, top it up first:
- 3a. Borrow (a rotation through the parent). If an adjacent sibling has at least t keys, move the separator between them down from x into c, and move the sibling’s nearest key up into x to replace it. If the nodes are internal, the sibling’s nearest child pointer moves across with it, so c gains one key and one child. This is the multiway version of a BST rotation: in-order sequence and key counts in x are unchanged.
- 3b. Merge. If both adjacent siblings (or the only one) have t − 1 keys, merge c with a sibling and the separator between them, as in 2c. The merged node has 2t − 1 keys and x loses one.
Then descend into c (or the merged node). If x is a leaf and the key is not in it, the key is not in the tree, and the deletion stops.
Shrinking the root. The root is the one node allowed to have fewer than t keys, so a merge in case 2c or 3b can take its only key. The root is then an empty node with a single child, and that child becomes the new root. This is the mirror image of a root split: the tree loses a level on every path at once, which is the only way its height decreases, so the leaves stay at the same depth.
Worked example
Take t = 2, so every non-root node holds 1 to 3 keys. Inserting 10, 20, 30, 40, 50, 60 into an empty tree with the code from Section 10.3 gives
[20 40]
/ | \
[10] [30] [50 60]
Now delete 30, 10, 50 and 40, in that order.
-
Delete 30 (case 3a, borrow). At the root, 30 is not present and belongs in child 1,
[30], which has t − 1 = 1 key. Its left sibling[10]is also minimal, but its right sibling[50 60]has 2 keys. Rotate: the separator 40 comes down into the child, giving[30 40], and 50 goes up to replace it. Then case 1 removes 30 from the leaf.[20 50] / | \ [10] [40] [60] -
Delete 10 (case 3b, merge). 10 belongs in child 0,
[10], which is minimal. It has no left sibling, and its right sibling[40]is minimal too. Merge[10], the separator 20 and[40]into[10 20 40]; the root drops to[50]. Case 1 removes 10.[50] / \ [20 40] [60] -
Delete 50 (case 2a). 50 is in the root, which is internal. The left child
[20 40]has 2 keys, so 50 is overwritten by its predecessor 40, and 40 is deleted from the left child by case 1. Result:[40]with children[20]and[60]. -
Delete 40 (case 2c, then the root shrinks). 40 is in the root and both children are minimal. Merge
[20], 40,[60]into[20 40 60]. The root has no keys left, so[20 40 60]becomes the root and the height drops from 1 to 0. Case 1 removes 40, leaving the single leaf[20 60].
Borrowing is tried first because it is local: three nodes change, no node is freed, and the parent keeps its key count. Merging frees a node but costs the parent a key, which is why the parent must have had t keys to begin with.
Cost
Each level does a constant number of node operations: at most one borrow or merge, which touches the node, one sibling and the parent, and shifts O(t) keys. Cases 2a and 2b add a walk down to find the predecessor or successor, along the same path the recursive delete then follows. So deletion reads and writes O(h) = O(log_t n) nodes and does O(t log_t n) CPU work, worst case, not amortized. The cost is the same order as bottom-up deletion, but the single pass has a practical advantage shared with proactive splitting: once the deletion has moved below a node, nothing further down can change that node, so a concurrent implementation can release its lock immediately instead of holding locks on the whole path.
The price is some unnecessary work. The fix-ups happen on the way down whether or not they turn out to be needed, so deleting a key that is not in the tree may still borrow or merge. The tree stays valid either way.
What real databases do instead
Production B+ trees mostly do not enforce the minimum occupancy on deletion.
- PostgreSQL never merges partly full index pages. A page is removed only once it is completely empty, and that happens later, during VACUUM.
- InnoDB (MySQL) merges a page with a neighbour only when its fill drops below
MERGE_THRESHOLD, 50% by default. - Many engines do not even remove the record at once. InnoDB marks deleted records and a background purge removes them later; SQL Server leaves “ghost records” for a cleanup task. The delete itself only flips a flag.
The reasons are practical. Deletes are often followed by inserts into the same key ranges, so merging a page at half full and splitting it again shortly after is wasted I/O and log volume. A merge or borrow modifies three pages (two siblings and the parent), each of which must be locked and logged for crash recovery, and that is the part of a B-tree that is hardest to make concurrent. Johnson and Shasha showed that unless deletes outnumber inserts, freeing pages only when they are empty costs little space utilization compared with merging at half full. The cost is that the height bound from Section 10.2 no longer holds in terms of the current number of keys: a tree that grew to a billion keys and then lost most of them keeps its height. Rebuilding the index (REINDEX, OPTIMIZE TABLE) compacts it, typically by bulk loading (Section 10.6).
10.5 A Complete Implementation
Here is the whole B-tree in one listing: search, insertion with proactive splitting, and single-pass deletion. Search and insertion are the code from Section 10.3, with split_child and split_root filled in. T is the minimum degree t; keys are assumed distinct, as in a unique index.
T = 2 # minimum degree
MAX_KEYS = 2 * T - 1
MIN_KEYS = T - 1
class BNode:
def __init__(self, is_leaf):
self.keys = []
self.children = []
self.is_leaf = is_leaf
def btree_search(node, key):
i = 0
while i < len(node.keys) and key > node.keys[i]:
i += 1
if i < len(node.keys) and key == node.keys[i]:
return (node, i)
if node.is_leaf:
return None
return btree_search(node.children[i], key)
# ---- insertion: never descend into a full node ----
def split_child(parent, i):
"""Split the full child parent.children[i] around its median."""
full = parent.children[i]
mid = len(full.keys) // 2 # T - 1, since the node holds 2T - 1 keys
right = BNode(full.is_leaf)
right.keys = full.keys[mid + 1:]
if not full.is_leaf:
right.children = full.children[mid + 1:]
full.children = full.children[:mid + 1]
median = full.keys[mid]
full.keys = full.keys[:mid]
parent.keys.insert(i, median)
parent.children.insert(i + 1, right)
def split_root(root):
new_root = BNode(is_leaf=False)
new_root.children.append(root)
split_child(new_root, 0)
return new_root
def btree_insert(root, key):
if len(root.keys) == MAX_KEYS:
root = split_root(root) # the only way the tree grows taller
_insert(root, key)
return root
def _insert(node, key):
i = 0
while i < len(node.keys) and key > node.keys[i]:
i += 1
if node.is_leaf:
node.keys.insert(i, key)
else:
if len(node.children[i].keys) == MAX_KEYS:
split_child(node, i)
if key > node.keys[i]:
i += 1
_insert(node.children[i], key)
# ---- deletion: never descend into a minimal node ----
def btree_delete(root, key):
_delete(root, key)
if not root.keys and not root.is_leaf:
root = root.children[0] # the only way the tree grows shorter
return root
def _delete(node, key):
"""Delete key from node's subtree. node is the root or has at least T keys."""
i = 0
while i < len(node.keys) and key > node.keys[i]:
i += 1
found = i < len(node.keys) and node.keys[i] == key
if found and node.is_leaf: # case 1
node.keys.pop(i)
elif found: # case 2
left, right = node.children[i], node.children[i + 1]
if len(left.keys) > MIN_KEYS: # 2a: predecessor
node.keys[i] = max_key(left)
_delete(left, node.keys[i])
elif len(right.keys) > MIN_KEYS: # 2b: successor
node.keys[i] = min_key(right)
_delete(right, node.keys[i])
else: # 2c: merge
merge(node, i)
_delete(left, key)
elif not node.is_leaf: # case 3
if len(node.children[i].keys) == MIN_KEYS:
i = fill_child(node, i)
_delete(node.children[i], key)
# otherwise: a leaf without the key, so the key is not in the tree
def max_key(node):
while not node.is_leaf:
node = node.children[-1]
return node.keys[-1]
def min_key(node):
while not node.is_leaf:
node = node.children[0]
return node.keys[0]
def fill_child(parent, i):
"""Give the minimal child parent.children[i] an extra key (case 3).
Returns the index of the child that now covers the same key range."""
if i > 0 and len(parent.children[i - 1].keys) > MIN_KEYS:
borrow_from_left(parent, i)
elif i < len(parent.keys) and len(parent.children[i + 1].keys) > MIN_KEYS:
borrow_from_right(parent, i)
elif i < len(parent.keys):
merge(parent, i)
else:
merge(parent, i - 1) # the last child merges into its left sibling
i -= 1
return i
def borrow_from_left(parent, i):
child, left = parent.children[i], parent.children[i - 1]
child.keys.insert(0, parent.keys[i - 1]) # separator comes down
parent.keys[i - 1] = left.keys.pop() # sibling's last key goes up
if not left.is_leaf:
child.children.insert(0, left.children.pop())
def borrow_from_right(parent, i):
child, right = parent.children[i], parent.children[i + 1]
child.keys.append(parent.keys[i])
parent.keys[i] = right.keys.pop(0)
if not right.is_leaf:
child.children.append(right.children.pop(0))
def merge(parent, i):
"""Merge children i and i + 1 of parent around the separator keys[i]."""
left = parent.children[i]
right = parent.children.pop(i + 1)
left.keys.append(parent.keys.pop(i))
left.keys.extend(right.keys)
left.children.extend(right.children)
The predecessor in case 2a is found by a separate walk (max_key) before the recursive delete follows the same path. A disk-based version would fetch those pages once and keep them in the buffer pool, so the walk costs no extra reads.
Testing it
Deletion has many cases and most bugs only show up several operations later, so test it against something too simple to get wrong: a sorted Python list. The test applies random inserts and deletes to both, and after every operation checks the B-tree invariants:
- every non-root node has between
MIN_KEYSandMAX_KEYSkeys, and an internal root has at least one key, - every internal node has exactly one more child than keys,
- all leaves are at the same depth,
- an in-order traversal equals the reference list. This checks sorted order within nodes and between separators in one go, since any misplaced key would show up out of order.
import random
from bisect import bisect_left
def check(root):
"""Assert the B-tree invariants and return the keys in order."""
keys, leaf_depths = [], set()
def walk(node, depth):
assert len(node.keys) <= MAX_KEYS
assert node is root or len(node.keys) >= MIN_KEYS
if node.is_leaf:
assert not node.children
leaf_depths.add(depth)
keys.extend(node.keys)
else:
assert len(node.children) == len(node.keys) + 1
for j, child in enumerate(node.children):
walk(child, depth + 1)
if j < len(node.keys):
keys.append(node.keys[j])
assert root.is_leaf or root.keys
walk(root, 0)
assert len(leaf_depths) <= 1
return keys
def random_test(t, ops, key_range, seed):
global T, MAX_KEYS, MIN_KEYS
T, MAX_KEYS, MIN_KEYS = t, 2 * t - 1, t - 1
rng = random.Random(seed)
root, ref = BNode(is_leaf=True), []
for step in range(ops):
p_insert = 0.7 if step < ops // 2 else 0.3 # grow, then shrink
key = rng.randrange(key_range)
j = bisect_left(ref, key)
present = j < len(ref) and ref[j] == key
if rng.random() < p_insert:
if not present:
root = btree_insert(root, key)
ref.insert(j, key)
else:
root = btree_delete(root, key) # absent keys too
if present:
ref.pop(j)
assert check(root) == ref
assert (btree_search(root, key) is not None) == (key in ref)
for t in (2, 3, 4):
for seed in range(1000):
random_test(t, ops=200, key_range=100, seed=seed)
print("3000 random sequences passed")
The insert probability starts at 0.7 and drops to 0.3 halfway, so each sequence grows a tree several levels deep and then shrinks it, often back to an empty leaf, which exercises root shrinking. A small key range makes repeated and absent keys common. The 3,000 sequences (600,000 operations) run in a few seconds and reach every branch of _delete and fill_child; t = 2 matters most, because with only 1 to 3 keys per node, borrows and merges happen constantly.
10.6 B+ Trees
B+ trees are optimized for range queries, common in databases.
Differences from B-trees
- Only leaves store data/values; internal nodes store only keys
- Leaves are linked (usually doubly-linked)
- Internal nodes are routing nodes (like telephone switching)
B+ Tree (internal nodes):
┌───────────────────┐
│ 20 │ 40 │ 60 │
└───────────────────┘
/ │ │ \
[0-20) [20-40) [40-60) [60+)
Leaves (linked for range queries):
┌──┬──┐ ┌──┬──┬──┐ ┌──┬──┐ ┌──┬──┐
│10│15│ → │25│30│35│ → │40│50│ → │60│70│ → NULL
└──┴──┘ └──┴──┴──┘ └──┴──┘ └──┴──┘
Advantages:
- More keys fit in internal nodes (higher fan-out, shallower)
- Leaves linked for efficient range scans
- All data at same depth (predictable I/O)
Range scans with leaf links
A range query such as WHERE key BETWEEN lo AND hi descends once, to the leaf where lo would be, and then walks right along the leaf links until it passes hi. Internal nodes are never revisited. Using the separator convention in the figure above (a key equal to a separator lives in the subtree to its right):
from bisect import bisect_left, bisect_right
class BPlusNode:
def __init__(self, is_leaf):
self.keys = []
self.children = [] # internal nodes only
self.values = [] # leaves only: values[j] belongs to keys[j]
self.next = None # leaves only: the leaf to the right
self.is_leaf = is_leaf
def find_leaf(root, key):
node = root
while not node.is_leaf:
node = node.children[bisect_right(node.keys, key)]
return node
def range_scan(root, lo, hi):
"""Yield (key, value) for every lo <= key <= hi, in key order."""
leaf = find_leaf(root, lo)
j = bisect_left(leaf.keys, lo)
while leaf is not None:
while j < len(leaf.keys):
if leaf.keys[j] > hi:
return
yield leaf.keys[j], leaf.values[j]
j += 1
leaf, j = leaf.next, 0
(bisect_right(keys, key) counts the separators ≤ key, which is the index of the child to follow. It is the binary-search version of the linear loop in btree_search.)
For example, in this B+ tree with up to 4 entries per leaf (built by bulk_load below from the keys 10, 20, …, 130):
[50 90 110]
/ / \ \
[10 20 30 40] → [50 60 70 80] → [90 100] → [110 120 130]
range_scan(root, 35, 85) reads the root, follows child 0 because 35 < 50, starts at 40 in the first leaf, takes all of the second leaf, and stops at 90 in the third: 4 node reads for 5 results.
Cost. If a leaf holds up to L entries and the query returns k of them, the scan reads h + 1 nodes to reach the first leaf and then about one more leaf per L results (up to twice that if leaves are only half full), so O(log_t n + k/L) node reads in the worst case. A plain B-tree can answer the same query by an in-order traversal, with a similar count of nodes, but the results are spread across all levels: the traversal keeps a stack of h nodes and keeps going back up into internal nodes between leaves. The B+ leaf chain needs only the current leaf in memory, lets a database cursor resume from where it stopped without descending again, and, when the leaves were written in key order (as bulk loading does), reads consecutive pages that the disk and the operating system can prefetch. Doubly linked leaves give the same for descending scans (ORDER BY key DESC).
Bulk loading
Building an index on an existing table by inserting n keys one at a time does O(n log_t n) node visits, rewrites each leaf many times, and in random key order touches pages in random order. It also leaves the tree loosely packed. With proactive splitting, ascending keys are the worst case: the rightmost leaf fills to 2t − 1 keys, splits into two halves of t − 1, and every later key goes to the right half, so the left half is never touched again. Inserting 100,000 ascending keys into the Section 10.5 tree with t = 50 produces 2,000 leaves holding 49.0 keys each on average, out of a possible 99. In random order the average is about 68, close to the ln 2 ≈ 69% that analysis of random insertion predicts.
Bulk loading builds the tree bottom-up instead:
- Sort the keys (with an external merge sort if they do not fit in memory).
- Fill leaves left to right, each as full as desired, and link each to the next.
- Build the level above from the list of leaves: each parent takes up to a full node’s worth of consecutive children, and its separators are the smallest keys of its second, third, … children. Repeat on the list of parents until a level has a single node, the root.
def pack(items, cap):
"""Cut items into runs of cap. If the last run is under half full,
share the last two runs evenly, so every run is at least half full."""
runs = [items[i:i + cap] for i in range(0, len(items), cap)]
if len(runs) >= 2 and len(runs[-1]) < cap // 2:
both = runs[-2] + runs[-1]
runs[-2:] = [both[:len(both) // 2], both[len(both) // 2:]]
return runs
def bulk_load(pairs, cap):
"""Build a B+ tree from (key, value) pairs already sorted by key.
Leaves hold up to cap entries; internal nodes have up to cap children."""
level = []
for run in pack(pairs, cap): # the leaf level
leaf = BPlusNode(is_leaf=True)
leaf.keys = [k for k, _ in run]
leaf.values = [v for _, v in run]
if level:
level[-1].next = leaf
level.append(leaf)
if not level:
return BPlusNode(is_leaf=True)
lows = [leaf.keys[0] for leaf in level] # smallest key under each node
while len(level) > 1: # one level up at a time
parents, parent_lows = [], []
for run in pack(list(zip(level, lows)), cap):
node = BPlusNode(is_leaf=False)
node.children = [child for child, _ in run]
node.keys = [low for _, low in run[1:]]
parents.append(node)
parent_lows.append(run[0][1])
level, lows = parents, parent_lows
return level[0]
pairs = [(k, "r%d" % k) for k in range(10, 140, 10)]
root = bulk_load(pairs, 4)
assert root.keys == [50, 90, 110]
assert [k for k, _ in range_scan(root, 35, 85)] == [40, 50, 60, 70, 80]
Every node except possibly the last one or two on each level is completely full, all leaves are at the same depth because every level is built whole, and pack keeps the last nodes at least half full so the result is a legal tree. After the sort, the work is O(n): every page is written exactly once, in order, which on disk means long sequential writes instead of n random read-modify-write cycles. The sort itself is O(n log n) comparisons but only a few sequential passes over the data. On a large table this makes index creation many times faster than repeated insertion, and the index comes out roughly half the size of one built from ascending inserts.
Completely full leaves have a cost: the first insert into any of them splits it. A table that will keep receiving inserts across its key range should be loaded with some free space in each leaf. PostgreSQL’s CREATE INDEX sorts the rows and builds the B-tree bottom-up exactly like this, leaving leaf pages 90% full by default (the index’s fillfactor). The same idea fixes the ascending-insert problem above: when PostgreSQL splits the rightmost page on a level, it leaves the left page fillfactor full instead of splitting it evenly, so a table keyed by an increasing sequence or timestamp still ends up with nearly full pages.
10.7 B* Trees
B* trees modify B-trees to keep nodes at least 2/3 full:
- Split only when two sibling nodes are full
- Redistribute between siblings before splitting
- More space-efficient than B-trees
10.8 2-3 Trees and 2-3-4 Trees
2-3 trees are B-trees of order 3:
- 2-node: 1 key, 2 children
- 3-node: 2 keys, 3 children
2-node: 3-node:
┌───┐ ┌───────┐
│ 5 │ │ 5 │ 8 │
└─┬─┘ └───┬─┘
│ /│\
These are conceptual foundations for understanding B-trees and for implementing in-memory balanced trees.
10.9 Real-World Applications
Database Systems:
- MySQL (InnoDB): B+ trees
- PostgreSQL: B+ trees (primary), other indexes
- Oracle: B+ trees, B* trees
- SQL Server: B+ trees
File Systems:
- NTFS (Windows): B+ trees
- HFS+ (macOS): B-trees
- ext4 (Linux): HTrees (generalized B+ trees)
- ReiserFS: B-trees
Key-Value Stores:
- LevelDB: Skip list + SSTable with B-tree-like index
- RocksDB: LSM trees (log-structured merge)
- Cassandra: LSM trees (memtable + SSTables), partitioned across nodes
10.10 Performance Characteristics
| Aspect | Binary Tree | B-Tree (m=100) | B+ Tree |
|---|---|---|---|
| Height (1M keys) | ~20 | ~3 | ~3 |
| Disk accesses | 20 | 3 | 3 |
| Node size | Small | Block size | Block size |
| Range scan | Inefficient | Efficient | Most efficient |
| Fan-out | 2 | ~50-200 | ~50-200 |
10.11 Variations and Extensions
B+-tree variants:
- B*-tree: Higher utilization
- B+-tree with bulk loading
- Prefix B-trees: Compress keys
LSM Trees (Log-Structured Merge):
- Write-optimized alternative
- Used in Cassandra, RocksDB, LevelDB
- Components: memtable (in-memory), SSTables (disk)
R-tree:
- Balanced like a B-tree, but nodes hold bounding rectangles instead of key ranges
- For multi-dimensional range queries
- Used in geographic databases
10.12 Historical Context
B-trees were introduced by Rudolf Bayer and Edward McCreight in 1970 at Boeing. The “B” stands for “balanced,” “broad,” or “Boeing” (depending on source).
The B+ tree variant was introduced shortly after, optimized for databases.
Donald Comer provided the comprehensive analysis in his 1979 paper “The Ubiquitous B-Tree,” showing how B-trees dominated database indexing.
The single-pass deletion of Section 10.4 is the formulation in Cormen, Leiserson and Rivest’s Introduction to Algorithms (1990), and later editions with Stein. Theodore Johnson and Dennis Shasha’s 1993 paper “B-Trees with Inserts and Deletes: Why Free-at-Empty Is Better Than Merge-at-Half” analysed the relaxed deletion that most database engines use instead.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
10.1 ★ Legal or not? In a B-tree of order 5 (Section 10.2), which of these are allowed? Name the rule that each illegal one breaks.
(a) A root with 1 key and 2 children. (b) A non-root internal node with 1 key and 2 children. (c) An internal node with 4 keys and 5 children. (d) A node with 3 keys and 3 children. (e) A tree with some leaves at depth 2 and others at depth 3.
Solution
(a) Legal. Rule 3 only requires the root to have at least 2 children.
(b) Illegal, rule 2. A non-root internal node needs at least ⌈5/2⌉ = 3 children (so at least 2 keys). This minimum is what keeps the height logarithmic.
(c) Legal. That is the maximum: 5 children (rule 1) and 5 − 1 = 4 keys (rule 4).
(d) Illegal, rule 4. A node with k children has exactly k − 1 keys; 3 keys need 4 children.
(e) Illegal, rule 5. All leaves must be at the same depth. B-trees grow and shrink only at the root (a root split adds a level everywhere at once), which is how this rule is maintained.
10.2 ★★ Insert by hand. Using btree_insert and _insert from Section 10.3 with MAX_KEYS = 3 (a B-tree of order 4, also called a 2-3-4 tree), insert 10, 20, 30, 40, 50, 60, 70 into an empty tree. A full node splits into its middle key, which moves up, and two nodes of one key each. Show the tree after every insertion that causes a split, and the final tree.
Hint
This code splits proactively: it splits a full node on the way down, before inserting, even if the new key would not have overflowed it yet.
Solution
-
10, 20, 30: all go into the root leaf:
[10 20 30], which is now full. -
40: the root is full, so
btree_insertsplits it first. 20 moves up into a new root; then 40 goes into the right leaf.[20] / \ [10] [30 40] -
50: goes into the right leaf:
[30 40 50], now full. No split yet, because splits happen on the way down and this leaf was not full when the descent reached it. -
60: the root
[20]is not full. Descending to child 1,[30 40 50]is full, sosplit_childmoves 40 up into the root. Since 60 > 40, descend to the new right child and insert.[20 40] / | \ [10] [30] [50 60] -
70: goes into
[50 60], giving[50 60 70]. No split.
Final tree:
[20 40]
/ | \
[10] [30] [50 60 70]
All leaves are at depth 1. The next insert larger than 40 will split [50 60 70] on its way down, before touching the leaf.
10.3 ★★ How tall can a B-tree get? Let t = ⌈m/2⌉ be the minimum number of children of a non-root internal node in a B-tree of order m, and assume (as is standard) that every non-root node holds at least t − 1 keys. (a) Show that a B-tree of height h (edges) holds at least 2t^h − 1 keys, so h ≤ log_t((n + 1)/2). (b) For m = 200 and n = 10⁹ keys, what is the maximum height, and how many node reads does a search need in the worst case? Compare with a balanced binary tree.
Hint
Count the minimum number of nodes at each depth: the root may have only 2 children, but every node below it has at least t.
Solution
(a) Take the thinnest possible tree. Depth 0 is the root with at least 1 key and 2 children. At depth 1 there are at least 2 nodes, at depth 2 at least 2t, and in general at least 2t^(d−1) nodes at depth d ≥ 1, each with at least t − 1 keys. So
n ≥ 1 + (t − 1) × Σ_{d=1}^{h} 2t^(d−1) = 1 + 2(t − 1) × (t^h − 1)/(t − 1) = 2t^h − 1.
Rearranging: t^h ≤ (n + 1)/2, so h ≤ log_t((n + 1)/2).
(b) m = 200 gives t = 100. log₁₀₀(5 × 10⁸) = log₁₀(5 × 10⁸) / 2 ≈ 8.70 / 2 = 4.35, so h ≤ 4: at most 5 levels, and a search reads at most 5 nodes. In the best case, with every node full (199 keys, 200 children), 3 levels hold only 200³ − 1 ≈ 8 × 10⁶ keys, so at least 4 levels are needed. A billion keys therefore sit in a tree of 4 or 5 levels. A balanced binary tree needs about log₂(10⁹) ≈ 30 levels. In practice the root and the second level (about 200 nodes) stay in memory, so the B-tree costs 2 or 3 disk reads per lookup.
10.4 ★★ Why B+ trees fan out further. Pages are 4096 bytes. Keys are 8 bytes, child pointers are 8 bytes, and each record (the value stored with a key) is 100 bytes. Ignore page headers. (a) What is the maximum fan-out of an internal node in a B-tree that stores records alongside keys in every node, and in a B+ tree whose internal nodes store only keys and pointers? (b) How many records fit in a B+ leaf? (c) With 10⁸ records and every node full, how many levels does each tree have?
Hint
A node with f children holds f − 1 keys. In the B-tree, each key carries its record with it.
Solution
(a) B-tree: f pointers plus f − 1 (key + record) entries: 8f + 108(f − 1) ≤ 4096, so 116f ≤ 4204 and f = 36. B+ tree: 8f + 8(f − 1) ≤ 4096, so 16f ≤ 4104 and f = 256.
(b) Each leaf entry is a key plus a record, 108 bytes: ⌊4096 / 108⌋ = 37 records per leaf. (Reserving 8 bytes for the next-leaf link still leaves room for 37.)
(c) B-tree: a full tree with L levels and fan-out 36 holds 36^L − 1 keys. 36⁵ − 1 ≈ 6.0 × 10⁷ is too few and 36⁶ − 1 ≈ 2.2 × 10⁹ is enough, so 6 levels.
B+ tree: 10⁸ / 37 ≈ 2.7 × 10⁶ leaves. Above them, internal levels with fan-out 256: 256² = 65,536 is too few to index them and 256³ ≈ 1.7 × 10⁷ is enough, so 3 internal levels plus the leaf level: 4 levels.
So the B+ tree does 4 page reads for every lookup, while the B-tree needs 6 for any key stored in a leaf, which is most of them (the occasional early hit in an internal node rarely helps). Moving records out of internal nodes is what lets each internal page route 256 ways instead of 36, which is the “higher fan-out, shallower” advantage in Section 10.6. The linked leaves add the second advantage: a range scan of 1,000 consecutive records reads 4 pages to find the start, then about 27 more leaves in order.
10.5 ★★ Find the bug. A colleague “simplifies” btree_search like this:
def btree_search(node, key):
i = 0
while i < len(node.keys) and key > node.keys[i]:
i += 1
if node.is_leaf:
if i < len(node.keys) and node.keys[i] == key:
return (node, i)
return None
return btree_search(node.children[i], key)
On the final tree from 10.2, which keys does it fail to find? Explain the bug, and say why the same shape of code would be close to correct for a B+ tree.
Solution
It only checks for a match at leaves. In a B-tree every key is stored exactly once, and keys that moved up during splits live only in internal nodes. On the tree from 10.2 it fails for 20 and 40: searching 20, the loop stops at i = 0 because 20 > 20 is false, the root is not a leaf, so it descends into children[0] = [10] and returns None. 40 likewise descends into [30]. The other five keys are found.
The fix is the original order in Section 10.3: check node.keys[i] == key at every node, before testing is_leaf.
In a B+ tree, internal keys are only routing copies and every key also appears in a leaf, so searching only at the leaves is the correct design. The descent rule must then match how separators were chosen. With the convention in Section 10.6’s figure, where the child to the right of separator s holds keys ≥ s, a key equal to a separator must go right, so the loop condition becomes key >= node.keys[i] for internal nodes.
10.6 ★★★ Implement the split. Section 10.3’s _insert calls split_child(node, i) and btree_insert calls split_root(root), but neither is shown there. (Section 10.5 lists them, so try this first.) Write them for nodes with fields keys, children and is_leaf, where MAX_KEYS = 2t − 1 for some t ≥ 2. Then explain why this top-down scheme needs MAX_KEYS to be odd: what goes wrong with order 5 (MAX_KEYS = 4) if you insert 1, 2, 3, 4, 0?
Hint
A full child has 2t − 1 keys. The middle one, at index t − 1, moves up into the parent at position i, and the right half becomes a new child at position i + 1. Internal nodes also have to split their children list.
Solution
class BNode:
def __init__(self, is_leaf):
self.keys = []
self.children = []
self.is_leaf = is_leaf
def split_child(parent, i):
"""Split the full child parent.children[i] around its median."""
full = parent.children[i]
mid = len(full.keys) // 2 # t - 1 when the node holds 2t - 1 keys
right = BNode(full.is_leaf)
right.keys = full.keys[mid + 1:]
if not full.is_leaf:
right.children = full.children[mid + 1:]
full.children = full.children[:mid + 1]
median = full.keys[mid]
full.keys = full.keys[:mid]
parent.keys.insert(i, median)
parent.children.insert(i + 1, right)
def split_root(root):
new_root = BNode(is_leaf=False)
new_root.children.append(root)
split_child(new_root, 0)
return new_root
A full node with 2t − 1 keys becomes two nodes of t − 1 keys each, with the median moving up. Both halves meet the minimum of t − 1 keys. The parent is guaranteed to have room for the median, because _insert never descends into a full node: it splits first. That invariant is what lets the insertion finish in a single pass down the tree, with no walking back up. Splitting the root is the only way the height grows, and it adds one level to every path at once, which keeps all leaves at the same depth.
Checks worth running: insert a few hundred random keys for t = 2, 3, 4, then assert that every non-root node holds between t − 1 and 2t − 1 keys, that internal nodes have one more child than keys, that keys are sorted within each node and between separators, and that all leaves are at the same depth.
Why MAX_KEYS must be odd. With order 5, a non-root node needs at least ⌈5/2⌉ − 1 = 2 keys, and a full node has 4. Splitting a 4-key node proactively, before inserting, leaves 2 keys on one side and 1 on the other. Insert 1, 2, 3, 4 (the root leaf is now full), then 0: btree_insert splits the root into [1 2], median 3, [4], and 0 goes left, giving
[3]
/ \
[0 1 2] [4]
The leaf [4] has only 1 key, below the order-5 minimum of 2. The top-down scheme only works when a full node splits into two legal halves, which requires 2t − 1 keys. Odd orders such as 5, which give an even MAX_KEYS, need the bottom-up approach instead: insert into the leaf first, and split only when it actually overflows to 5 keys, as in the figure in Section 10.3 (2 keys, median, 2 keys).
10.7 ★★ Delete by hand. With t = 2, inserting 1 to 15 in ascending order produces the tree below. Using the algorithm of Section 10.4, delete 1 and then 8. Name the case applied at each node, and show the tree after each deletion.
[4 8]
/ | \
[2] [6] [10 12]
/ \ / \ / | \
[1] [3] [5] [7] [9] [11] [13 14 15]
Hint
Deleting 1 starts with two fix-ups on the way down, one per level. Deleting 8 needs a predecessor, and the path to it ends at the last child of a node, which has no right sibling.
Solution
Delete 1. At the root [4 8], 1 belongs in child 0, [2], which is minimal. It has no left sibling and its right sibling [6] is minimal too, so merge (3b): [2], 4 and [6] become [2 4 6] with children [1] [3] [5] [7], and the root drops to [8]. Descend into [2 4 6]: 1 belongs in child 0, [1], again minimal with a minimal right sibling [3], so merge again: [1 2 3], and the node becomes [4 6]. Finally case 1 removes 1 from the leaf.
[8]
/ \
[4 6] [10 12]
/ | \ / | \
[2 3] [5] [7] [9] [11] [13 14 15]
A bottom-up algorithm reaches the same tree here, in the opposite order: [3] cannot lend a key, so it would merge at the leaf, leaving [2] empty, and then merge again one level up.
Delete 8. 8 is in the root, which is internal. Its left child [4 6] has 2 = t keys, so case 2a: the predecessor is the largest key in that subtree, 7. Overwrite 8 with 7 and delete 7 from [4 6]. There, 7 belongs in the last child [7], which is minimal. It has no right sibling and its left sibling [5] is minimal, so merge with the left sibling: [5], 6, [7] become [5 6 7] and the node becomes [4]. Case 1 removes 7.
[7]
/ \
[4] [10 12]
/ \ / | \
[2 3] [5 6] [9] [11] [13 14 15]
Both trees pass the invariant checks in Section 10.5: every non-root node has 1 to 3 keys and all leaves are at depth 2.
10.8 ★★ Sorted input. Section 10.6 says that inserting keys in ascending order with the proactive-splitting code of Section 10.5 leaves the leaves about half full. (a) Explain exactly why every leaf except the last ends up with t − 1 keys. (b) The table is now bulk loaded instead, with completely full leaves, and afterwards receives inserts of random keys. What happens to the first insert into each leaf, and what does the leaf fill settle to? (c) Why is a fill factor of 100% the right choice for a table that is only ever appended to in key order, such as a log keyed by timestamp?
Solution
(a) A new key larger than every existing key always goes to the rightmost leaf. When that leaf holds 2t − 1 keys, the next insertion splits it on the way down: t − 1 keys stay in the left half, the median moves up, and t − 1 go to the new right leaf, which receives the new key. No later key is smaller than anything in the left half, so it never gains another key. Every leaf except the rightmost is such a left half, with t − 1 of a possible 2t − 1 keys. The internal nodes fill the same way. With t = 50 that is 49 of 99 keys, which is what the measurement in Section 10.6 shows.
(b) Every leaf is full, so the first insert into each one splits it into two halves of t − 1 keys plus the new key: across the tree, utilization falls toward 50% as the inserts spread out, and then climbs back as the halves fill, settling around the ln 2 ≈ 69% of random insertion. The burst of splits right after loading is the reason for leaving free space, such as PostgreSQL’s default 90% leaf fill: a leaf can then absorb several inserts before its first split.
(c) If every new key is larger than all existing ones, no insert ever lands in an existing leaf except the rightmost. Free space left in the other leaves would never be used, so it is pure waste: more pages to store, cache and scan. Full leaves are optimal, and splitting the rightmost leaf unevenly (keeping the left page full and starting a nearly empty right page) keeps them full as the table grows.
Where this connects
- Chapter 16: External Memory and Cache-Oblivious Structures. The external-memory model that explains why B-trees exist
- Chapter 14: Probabilistic Data Structures. The Bloom filters that make LSM-tree reads viable
Volume II: Advanced Structures and Algorithms
Volume I organised data by position (arrays, lists) and by order (search trees, heaps). This volume adds three ideas that each change what is possible:
- Relationships with no fixed shape. A graph records only which things are connected. With the right auxiliary structure (a queue, a stack, a heap, a union-find) it answers questions about reachability, ordering, connectivity and distance.
- Lookup without order. A hash table gives up sorted order entirely and gets expected O(1) lookup in return. It is the most widely used structure in practice, and the fine print (hash quality, load factor, adversarial input) is where real systems succeed or fail.
- Structure inside the keys. When the keys are strings, their shared prefixes and suffixes can themselves be indexed. Tries, suffix arrays and Aho-Corasick turn text search from scanning into lookup.
Before you start. You need Volume I, especially Chapters 5 (stacks and queues), 7 (BSTs) and 9 (heaps); Chapter 11’s algorithms are those structures driven over a graph. Chapter 1’s notion of expected cost is used throughout Chapter 12.
| Chapter | After it you can |
|---|---|
| 11: Graphs: Modeling Relationships | Choose a graph representation, run BFS and DFS, detect cycles, order a DAG, find strongly connected components and MSTs, and pick the right shortest-path algorithm for the edge weights you have |
| 12: Hash Tables | Explain chaining versus open addressing, reason about load factor and resizing, choose a hash function, explain why Robin Hood hashing and Swiss tables are what modern hash maps use, defend against hash flooding, and build an LRU cache |
| 13: String Data Structures | Build tries and radix trees, explain suffix trees and suffix arrays, match patterns with KMP, the Z-array and rolling hashes, search for many patterns at once with Aho-Corasick, and choose between a gap buffer, rope and piece table for a text editor |
The three chapters are independent, so read them in any order. If you are preparing for interviews, Chapters 11 and 12 are the most frequently tested material in the whole book.
Chapter 11: Graphs—Modeling Relationships
Every structure in Volume I imposes a shape on its data: a line (arrays, lists), a hierarchy (trees), a partial order (heaps). A graph imposes nothing. It records only which things are related to which, and that generality is why it shows up everywhere: road networks, package dependencies, social networks, the call graph of a program, the links between web pages, the routers of the internet.
The price of generality is that there is no single “graph data structure”. There are several representations, each good at different questions, and a family of algorithms that are really just the right auxiliary structure (a queue, a stack, a heap, a union-find) driven over the graph. This chapter is as much about those pairings as about graphs themselves.
11.1 Graph Fundamentals
A graph G = (V, E) consists of:
- V: a set of vertices (also called nodes)
- E: a set of edges, each connecting a pair of vertices
Graph Example:
V = {A, B, C, D, E}
E = {(A,B), (A,C), (B,D), (C,D), (D,E)}
A
/ \
B C
\ /
D───E
We write n = |V| and m = |E|, or simply V and E inside O(…). The vocabulary you need:
- Adjacent: u and v are adjacent if (u, v) ∈ E. They are each other’s neighbours.
- Degree of v: the number of edges touching v. In a directed graph this splits into in-degree (edges arriving) and out-degree (edges leaving). In the example, deg(D) = 3.
- Path: a sequence of vertices where each consecutive pair is an edge. Its length is the number of edges.
- Cycle: a path of length at least 1 (at least 3 in a simple undirected graph) that starts and ends at the same vertex. A-B-D-C-A is a cycle of length 4.
- Connected: an undirected graph is connected if every vertex can reach every other. A directed graph is strongly connected if every vertex can reach every other following edge directions.
Two counting facts are worth memorising because they drive every complexity bound in this chapter:
- Handshake lemma. In an undirected graph, the degrees sum to 2E, because every edge contributes to the degree of both its endpoints. The example has degrees 2+2+2+3+1 = 10 = 2 × 5.
- Edge bound. A simple undirected graph has at most V(V-1)/2 edges, so E = O(V²) and log E = O(log V). A graph is sparse when E is close to V (road networks: most intersections have degree ≤ 4) and dense when E is close to V² (a complete graph of all-pairs distances).
11.2 Graph Types
Directed vs. undirected:
- Undirected: edges have no direction (relationships are symmetric: “is married to”)
- Directed: edges have direction, A → B does not imply B → A (“follows”, “depends on”, “links to”)
Weighted vs. unweighted:
- Weighted: edges carry a number (distance, cost, latency, capacity)
- Unweighted: every edge counts as 1
Simple vs. multigraph:
- Simple: no self-loops, at most one edge between any pair
- Multigraph: parallel edges allowed (two flights between the same cities at different prices)
Cyclic vs. acyclic:
- Cyclic: contains at least one cycle
- Acyclic: no cycles. A connected acyclic undirected graph is a tree (exactly V - 1 edges). A directed acyclic graph is a DAG.
Bipartite: the vertices split into two sides with every edge crossing between them (students and courses, users and products). A graph is bipartite exactly when it has no odd-length cycle.
11.3 Graph Representations
Throughout this chapter, Python examples use an adjacency list stored as a dict: graph[u] is a list of u’s neighbours, or a list of (neighbour, weight) pairs for weighted graphs. The example graph from 11.1 is:
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
'D': ['B', 'C', 'E'],
'E': ['D'],
}
Adjacency Matrix
A V×V matrix where adj[i][j] records whether (or with what weight) an edge i → j exists:
// For weighted graph
int adj[V][V];
// adj[i][j] = weight if edge exists, INF otherwise
Undirected Graph:
A B C D E
┌───────────────
A │ 0 1 1 0 0
B │ 1 0 0 1 0
C │ 1 0 0 1 0
D │ 0 1 1 0 1
E │ 0 0 0 1 0
Space: O(V²)
For an undirected graph the matrix is symmetric. Pros: O(1) “is there an edge u-v?”, trivial to implement, and matrix algebra applies (entry (i, j) of A^k counts walks of length k from i to j). Cons: O(V²) space and O(V) to list a vertex’s neighbours, even if it has only one. A road network of 10 million intersections would need 10^14 cells.
Adjacency List
Each vertex stores the list of its neighbours:
struct Node {
int vertex;
struct Node *next;
};
struct Graph {
int V;
struct Node **adj;
};
Adjacency List:
A → [B] → [C] → NULL
B → [A] → [D] → NULL
C → [A] → [D] → NULL
D → [B] → [C] → [E] → NULL
E → [D] → NULL
Space: O(V + E)
Pros: O(V + E) space, and iterating over a vertex’s neighbours costs O(degree), which is what traversals need. Cons: “is there an edge u-v?” costs O(deg(u)) unless you store neighbour sets (hash sets) instead of lists, which buys O(1) expected lookup at a constant-factor memory cost.
In practice, use dynamic arrays rather than linked lists for the neighbour lists. Chapter 3’s argument about cache locality applies directly: scanning a contiguous array of neighbour IDs is several times faster than chasing pointers.
Edge List
Just a list of (u, v) or (weight, u, v) tuples. Useless for traversal (finding a vertex’s neighbours means scanning everything), but it is the natural input for algorithms that look at edges in a global order: Kruskal’s MST sorts it, and Bellman-Ford sweeps it repeatedly.
Compressed Sparse Row (CSR)
When the graph is static, flatten the adjacency lists into two arrays: targets holds every neighbour list concatenated, and offsets[u] says where u’s list starts. The neighbours of u are targets[offsets[u] : offsets[u+1]].
Vertex index: A=0 B=1 C=2 D=3 E=4
offsets: [0, 2, 4, 6, 9, 10]
targets: [B, C, A, D, A, D, B, C, E, D]
└─A─┘ └─B─┘ └─C─┘ └──D───┘ └E┘
CSR uses exactly V + 1 + E integers with no per-node pointers, and every traversal is a sequential scan. It is the standard layout in graph analytics libraries, sparse matrix code (the matrix is the graph), and GPU graph processing. The cost is that adding an edge means rebuilding the arrays.
Choosing a representation
| Question | Matrix | Adjacency list | Edge list | CSR |
|---|---|---|---|---|
| Space | O(V²) | O(V + E) | O(E) | O(V + E) |
| Is (u, v) an edge? | O(1) | O(deg u), O(1) expected with sets | O(E) | O(deg u), O(log deg u) if sorted |
| List neighbours of u | O(V) | O(deg u) | O(E) | O(deg u) |
| Add an edge | O(1) | O(1) amortized | O(1) amortized | O(V + E) rebuild |
| Best for | dense graphs, Floyd-Warshall | general purpose, mutable graphs | Kruskal, Bellman-Ford | large static graphs |
11.4 Graph Traversal
Both basic traversals have the same skeleton: keep a set of discovered vertices and a container of vertices waiting to be processed. The container decides everything. A queue gives breadth-first search; a stack gives depth-first search.
Breadth-First Search (BFS)
BFS explores vertices in waves: first the source, then everything at distance 1, then everything at distance 2, and so on. Because a vertex is first discovered along a shortest path, recording who discovered it gives you shortest paths in an unweighted graph for free:
from collections import deque
def bfs(graph, source):
"""Return (dist, parent) for every vertex reachable from source."""
dist = {source: 0}
parent = {source: None}
queue = deque([source])
while queue:
u = queue.popleft()
for v in graph[u]:
if v not in dist: # first discovery is the shortest
dist[v] = dist[u] + 1
parent[v] = u
queue.append(v)
return dist, parent
def reconstruct_path(parent, target):
if target not in parent:
return None # unreachable
path = []
while target is not None:
path.append(target)
target = parent[target]
return path[::-1]
On the example graph, bfs(graph, 'A') gives distances A:0, B:1, C:1, D:2, E:3, and reconstruct_path(parent, 'E') returns ['A', 'B', 'D', 'E'].
Mark a vertex as discovered when you enqueue it, not when you dequeue it. Marking on dequeue lets the same vertex enter the queue many times (once per neighbour that sees it before it is processed), which is still correct but wastes up to O(E) queue space.
Properties:
- Uses a queue (FIFO), Chapter 5
- Finds shortest paths (fewest edges) in unweighted graphs
- Time: O(V + E). Each vertex is enqueued once and each adjacency list is scanned once; by the handshake lemma the scans total O(E).
- Space: O(V)
Depth-First Search (DFS)
DFS follows one path as deep as it can, then backtracks:
def dfs_recursive(graph, u, visited=None, order=None):
if visited is None:
visited, order = set(), []
visited.add(u)
order.append(u)
for v in graph[u]:
if v not in visited:
dfs_recursive(graph, v, visited, order)
return order
def dfs_iterative(graph, start):
visited, order = set(), []
stack = [start]
while stack:
u = stack.pop()
if u in visited:
continue # a vertex can be pushed more than once
visited.add(u)
order.append(u)
# push in reverse so neighbours are visited in listed order
for v in reversed(graph[u]):
if v not in visited:
stack.append(v)
return order
Both return ['A', 'B', 'D', 'C', 'E'] on the example graph. Two details in the iterative version matter. First, it checks visited when popping, unlike BFS, because a vertex may be pushed several times before it is reached, and only the last push reflects true depth-first order. Second, it pushes neighbours in reverse; without that, it still visits everything but in a different order from the recursive version, which surprises people when comparing outputs.
The recursive version is shorter, but its call stack is the DFS stack. Python’s default recursion limit is 1000, so a path-shaped graph of 10,000 vertices crashes it. Use the iterative form (or raise the limit with care) for large inputs.
Properties:
- Uses a stack (LIFO), explicit or the call stack
- Time: O(V + E); Space: O(V)
- Does not find shortest paths. Its value is the structure it reveals, which the next section uses.
To traverse a graph that is not connected, run the traversal from every vertex not yet visited. Each run discovers one connected component, so counting runs counts components.
11.5 What DFS Reveals: Cycles and Bipartiteness
Cycle detection in directed graphs
During a DFS, each vertex is in one of three states, traditionally coloured:
- White: not yet discovered
- Gray: discovered, still on the current recursion path (its descendants are being explored)
- Black: finished, all descendants explored
An edge u → v where v is gray points back to an ancestor of u on the current path. That is a back edge, and a directed graph has a cycle if and only if DFS finds a back edge.
WHITE, GRAY, BLACK = 0, 1, 2
def has_cycle(graph):
color = {u: WHITE for u in graph}
def visit(u):
color[u] = GRAY # on the current DFS path
for v in graph[u]:
if color[v] == GRAY: # back edge: v is an ancestor of u
return True
if color[v] == WHITE and visit(v):
return True
color[u] = BLACK # finished
return False
return any(color[u] == WHITE and visit(u) for u in graph)
Two colours are not enough. With only “visited / not visited”, an edge to a vertex finished in an earlier branch (a cross edge, harmless) looks the same as an edge to an ancestor (a back edge, a cycle). In the diamond A → B, A → C, B → D, C → D, the edge C → D reaches an already-visited D, but there is no cycle. D is black, not gray.
(For undirected graphs, it is simpler: any edge to an already-visited vertex other than your DFS parent closes a cycle. Or use union-find, 11.8.)
Bipartiteness
Two-colour the graph with BFS: give the source side 0, each newly discovered neighbour the opposite side of its discoverer. If you ever find an edge whose endpoints already have the same side, the graph has an odd cycle and is not bipartite.
def is_bipartite(graph):
side = {}
for s in graph: # handle every component
if s in side:
continue
side[s] = 0
queue = deque([s])
while queue:
u = queue.popleft()
for v in graph[u]:
if v not in side:
side[v] = 1 - side[u]
queue.append(v)
elif side[v] == side[u]:
return False # edge inside one side: odd cycle
return True
The example graph is bipartite: {A, D} on one side, {B, C, E} on the other. Adding the edge B-C creates the triangle A-B-C and breaks it.
11.6 Topological Sort
A topological order of a DAG lists the vertices so that every edge points forward: if u → v, then u comes before v. It answers “in what order can I do these tasks, given their dependencies?” A topological order exists exactly when the graph has no directed cycle.
Kahn’s algorithm repeatedly removes a vertex with no remaining incoming edges:
def topological_sort(graph):
"""Kahn's algorithm. Returns an order, or None if the graph has a cycle."""
in_degree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
in_degree[v] += 1
queue = deque(u for u in graph if in_degree[u] == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
return order if len(order) == len(graph) else None
The final check is the cycle detector. Vertices on a cycle never reach in-degree 0 (each waits on another), so they never get output. If the order is shorter than V, the leftover vertices contain a cycle. A version that omits this check silently returns a partial order for cyclic input, which is a real bug in build tools.
Time: O(V + E). Use deque.popleft(), not list.pop(0); the latter shifts the whole list and makes the loop O(V²) in the worst case.
The DFS method is a one-line consequence of 11.5: in a DAG, a vertex finishes (turns black) only after everything reachable from it has finished. So the reverse of finishing order is a topological order.
def topological_sort_dfs(graph):
"""Reverse postorder. Assumes the graph is a DAG."""
visited, postorder = set(), []
def visit(u):
visited.add(u)
for v in graph[u]:
if v not in visited:
visit(v)
postorder.append(u) # u finishes after everything it reaches
for u in graph:
if u not in visited:
visit(u)
return postorder[::-1]
Worked example (getting dressed):
dag = {
'socks': ['shoes'],
'pants': ['shoes', 'belt'],
'shirt': ['tie', 'belt'],
'tie': ['jacket'],
'belt': ['jacket'],
'shoes': [],
'jacket': [],
}
# Kahn: socks, pants, shirt, shoes, tie, belt, jacket
Topological orders are rarely unique. Any order that respects the edges is correct, which is why two correct implementations can disagree.
Applications: build systems (make, Bazel), package managers resolving install order, spreadsheet recalculation, course prerequisites, scheduling the layers of a neural network’s computation graph, and instruction scheduling in compilers.
11.7 Strongly Connected Components
In a directed graph, u and v are in the same strongly connected component (SCC) if each can reach the other. SCCs partition the vertices, and if you shrink each SCC to a single vertex, what remains (the condensation) is always a DAG. That makes SCCs the standard first step for problems on general directed graphs: collapse the cycles, then work on a DAG.
Kosaraju’s algorithm uses two DFS passes:
- Run DFS on G and record vertices in order of finishing time.
- Build the transpose Gᵀ (every edge reversed).
- Run DFS on Gᵀ, starting each new search from the unassigned vertex that finished latest in pass 1. Each search collects exactly one SCC.
def strongly_connected_components(graph):
# Pass 1: record finishing order on the original graph.
visited, finish = set(), []
def visit(u):
visited.add(u)
for v in graph[u]:
if v not in visited:
visit(v)
finish.append(u)
for u in graph:
if u not in visited:
visit(u)
# Build the transpose (every edge reversed).
transpose = {u: [] for u in graph}
for u in graph:
for v in graph[u]:
transpose[v].append(u)
# Pass 2: DFS on the transpose in decreasing finish time.
assigned, components = set(), []
def collect(u, comp):
assigned.add(u)
comp.append(u)
for v in transpose[u]:
if v not in assigned:
collect(v, comp)
for u in reversed(finish):
if u not in assigned:
comp = []
collect(u, comp)
components.append(comp)
return components
Why it works: the vertex that finishes last lies in a “source” SCC of the condensation (nothing outside it reaches in). Reversing the edges turns that source into a sink, so a DFS from it in Gᵀ cannot leak out of its own component. Removing that component exposes the next one, and so on.
Tarjan’s algorithm finds the same components in a single DFS by tracking, for each vertex, the lowest discovery time reachable through its subtree (its “low-link”). It avoids building the transpose and is usually faster in practice; Kosaraju is easier to remember and to prove. Both run in O(V + E).
Uses: finding dependency cycles in module graphs, solving 2-SAT (a formula is satisfiable iff no variable shares an SCC with its negation), and finding the “core” of a web or social graph.
11.8 Union-Find (Disjoint Set Union)
Union-find maintains a partition of {0, …, n-1} into disjoint sets under two operations: find(x) returns a representative of x’s set, and union(x, y) merges two sets. It answers “are x and y connected?” while edges are being added, which is exactly what Kruskal’s algorithm needs.
Each set is a tree of parent pointers; the root is the representative.
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) # path compression
return self.parent[x]
def union(self, x, y):
rx, ry = self.find(x), self.find(y)
if rx == ry:
return False # already in the same set
if self.rank[rx] < self.rank[ry]:
rx, ry = ry, rx
self.parent[ry] = rx # union by rank: shorter tree goes under
if self.rank[rx] == self.rank[ry]:
self.rank[rx] += 1
return True
Two independent optimisations make it fast:
- Union by rank attaches the shorter tree under the taller one, so trees stay O(log n) tall even without compression.
- Path compression makes every node on a
findpath point directly at the root, flattening the tree for future calls.
With both, any sequence of m operations takes O(m α(n)) time, where α is the inverse Ackermann function. α(n) ≤ 4 for any n that fits in the physical universe, so this is constant in practice, though not in theory: Fredman and Saks proved in 1989 that no union-find structure can do better. Either optimisation alone gives O(log n) amortized per operation.
What union-find cannot do is split sets. Deleting an edge requires a different structure (or, offline, the DSU-with-rollback technique from Chapter 23).
11.9 Minimum Spanning Trees
A spanning tree of a connected, undirected, weighted graph is a subset of V - 1 edges that connects every vertex without cycles. A minimum spanning tree (MST) is one with the least total weight: the cheapest way to wire up a set of buildings, cities or circuit pins.
Both classic algorithms are greedy, and both are justified by one fact:
Cut property. Split the vertices into any two non-empty groups. The lightest edge crossing between the groups belongs to some MST. (If edge weights are distinct, it belongs to the MST, which is then unique.)
Proof sketch: take an MST that does not contain that lightest crossing edge e. Adding e creates a cycle, and the cycle must cross the cut a second time through some edge f with weight ≥ weight(e). Swap f for e: still a spanning tree, no heavier. So some MST contains e.
Kruskal’s Algorithm
Sort all edges by weight; take each edge unless it would form a cycle. Union-find is the cycle detector: an edge (u, v) forms a cycle exactly when u and v are already in the same set.
def kruskal(n, edges):
"""n vertices numbered 0..n-1; edges is a list of (weight, u, v)."""
uf = UnionFind(n)
mst = []
for w, u, v in sorted(edges):
if uf.union(u, v): # False means u and v already connected
mst.append((u, v, w))
if len(mst) == n - 1:
break
return mst
Each accepted edge is the lightest edge leaving the component it joins, so the cut property applies. Time: O(E log E) for the sort, which is the same as O(E log V) since E ≤ V². The union-find work is nearly linear and never dominates. If the graph is disconnected, Kruskal returns a minimum spanning forest with fewer than n - 1 edges.
Prim’s Algorithm
Grow a single tree from a start vertex, always adding the cheapest edge that leaves it. A min-heap (Chapter 9) holds the candidate edges:
import heapq
def prim(graph, start):
"""graph[u] is a list of (v, weight) pairs, undirected."""
visited = {start}
mst = []
heap = [(w, start, v) for v, w in graph[start]]
heapq.heapify(heap)
while heap and len(visited) < len(graph):
w, u, v = heapq.heappop(heap)
if v in visited:
continue # stale entry: v was reached more cheaply
visited.add(v)
mst.append((u, v, w))
for x, wx in graph[v]:
if x not in visited:
heapq.heappush(heap, (wx, v, x))
return mst
The cut is “tree vertices vs. everything else”, and the heap’s minimum is the lightest crossing edge. Instead of decreasing keys, this version pushes duplicates and discards stale ones when popped (“lazy deletion”), which keeps the code simple and works with Python’s heapq, which has no decrease-key.
Time: O(E log V) with a binary heap. With a Fibonacci heap it is O(E + V log V), better on paper for dense graphs; see Chapter 19 for why that rarely wins in practice. For truly dense graphs stored as a matrix, the simple O(V²) array version of Prim (scan for the minimum each round, no heap) is the fastest option.
Which one? Kruskal is simplest when you already have an edge list, and it handles disconnected graphs naturally. Prim suits dense graphs and adjacency structures. Both give the same total weight.
11.10 Shortest Paths
The single-source problem: given a source s, find the minimum-weight path from s to every other vertex. Which algorithm you can use depends entirely on the edge weights.
Single-Source, Non-Negative Weights: Dijkstra’s Algorithm
Dijkstra’s algorithm is BFS with a priority queue in place of the FIFO queue: always expand the unfinished vertex with the smallest known distance.
import heapq
def dijkstra(graph, source):
"""graph[u] is a list of (v, weight) pairs with weight >= 0."""
dist = {u: float('inf') for u in graph}
parent = {source: None}
dist[source] = 0
pq = [(0, source)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue # stale entry (lazy deletion)
for v, w in graph[u]:
if d + w < dist[v]:
dist[v] = d + w
parent[v] = u
heapq.heappush(pq, (dist[v], v))
return dist, parent
The operation dist[v] = min(dist[v], dist[u] + w) is called relaxing the edge u → v. Every shortest-path algorithm in this section is a strategy for choosing which edges to relax, in which order.
Worked trace. Edges: S→A (4), S→B (1), B→A (2), A→C (1), B→C (5), C→D (3).
| Step | Pop | Relaxations | Heap afterwards |
|---|---|---|---|
| 1 | (0, S) | A: ∞→4, B: ∞→1 | (1,B) (4,A) |
| 2 | (1, B) | A: 4→3, C: ∞→6 | (3,A) (4,A) (6,C) |
| 3 | (3, A) | C: 6→4 | (4,A) (4,C) (6,C) |
| 4 | (4, A) | stale (4 > dist[A] = 3), skip | (4,C) (6,C) |
| 5 | (4, C) | D: ∞→7 | (6,C) (7,D) |
| 6 | (6, C) | stale, skip | (7,D) |
| 7 | (7, D) | none | empty |
Result: S:0, B:1, A:3, C:4, D:7, with path S → B → A → C → D. Note that A was first reached directly (cost 4) and improved via B; the direct edge was not the shortest route.
Why it is correct. When a vertex u is popped with its true distance, every vertex still in the heap has a distance at least as large. Any path to u through one of those vertices therefore costs at least as much, because edges cannot make a path cheaper. So u’s distance is final.
Why negative edges break it. That last sentence is the whole assumption. Take S→A (1), S→B (5), B→A (-10), A→C (1). Textbook Dijkstra finalises A at distance 1 when it pops it, then finalises C at 2. Only then does it pop B and discover that S → B → A costs -5. A was already declared done, so A and C end up wrong (the true distances are -5 and -4).
The lazy-deletion code above happens to recover in this example, because it re-pushes A when A improves and processes it again. That does not rescue it in general: with negative edges, a vertex can be reprocessed many times, and there are graphs that force exponentially many repetitions. If weights can be negative, use Bellman-Ford.
Time: O((V + E) log V) with a binary heap; O(E + V log V) with a Fibonacci heap.
A* search is Dijkstra with a priority of dist[v] + h(v), where h estimates the remaining distance to a single target (straight-line distance in a road map, for example). If h never overestimates the true remaining distance (straight-line distance never does), A* still finds the shortest path, but it explores far fewer vertices because it is pulled toward the goal. It is the standard algorithm for pathfinding in games and robotics.
Single-Source, Any Weights: Bellman-Ford
Bellman-Ford drops the cleverness and relaxes every edge, V - 1 times:
def bellman_ford(vertices, edges, source):
"""edges is a list of (u, v, weight). Returns dist, or None on a negative cycle."""
dist = {u: float('inf') for u in vertices}
dist[source] = 0
for _ in range(len(vertices) - 1):
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
break # converged early
for u, v, w in edges: # a V-th improvement means a negative cycle
if dist[u] + w < dist[v]:
return None
return dist
Why V - 1 rounds: a shortest path without cycles has at most V - 1 edges, and after round k, every vertex whose shortest path uses at most k edges has its correct distance (by induction: round k relaxes the k-th edge of that path). If anything still improves in round V, some path is getting cheaper without bound, so there is a negative cycle reachable from the source and “shortest path” is undefined.
Time: O(VE). That is much slower than Dijkstra, but it handles negative weights and detects negative cycles. It is also naturally distributed, since each relaxation only needs a neighbour’s current estimate. That is why distance-vector routing protocols such as RIP are Bellman-Ford running across routers (Chapter 28). A classic application of negative-cycle detection: currency arbitrage. With edge weights -log(rate), a negative cycle is a sequence of trades that ends with more money than it started.
All-Pairs: Floyd-Warshall
To get the distance between every pair of vertices, Floyd-Warshall uses dynamic programming over intermediate vertices. After processing k, dist[i][j] is the shortest path from i to j that uses only vertices 0..k as intermediate stops.
def floyd_warshall(n, edges):
"""n vertices numbered 0..n-1; edges is a list of (u, v, weight)."""
INF = float('inf')
dist = [[INF] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for u, v, w in edges:
dist[u][v] = min(dist[u][v], w) # keep the cheapest parallel edge
for k in range(n): # allow k as an intermediate vertex
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist # dist[i][i] < 0 for some i means a negative cycle
The loop order matters: k must be the outermost loop. Putting it innermost gives code that looks identical and returns wrong answers.
Time: O(V³), Space: O(V²). It handles negative edges (not negative cycles), and its three tight loops over a matrix are very cache-friendly, so for a few hundred vertices it often beats running Dijkstra V times despite the worse bound. For large sparse graphs, V runs of Dijkstra (O(VE log V)) win. With negative edges, Johnson’s algorithm runs Bellman-Ford once to reweight all edges to be non-negative, then runs Dijkstra from every vertex.
Choosing a shortest-path algorithm
| Situation | Algorithm | Time |
|---|---|---|
| Unweighted | BFS | O(V + E) |
| Weights only 0 or 1 | 0-1 BFS (deque: push 0-edges to the front, 1-edges to the back) | O(V + E) |
| DAG, any weights | Relax edges in topological order | O(V + E) |
| Non-negative weights | Dijkstra | O((V + E) log V) |
| Non-negative, single target, good heuristic | A* | Problem-dependent, usually far less than Dijkstra |
| Negative weights, single source | Bellman-Ford | O(VE) |
| All pairs, small or dense graph | Floyd-Warshall | O(V³) |
| All pairs, large sparse graph | V × Dijkstra (Johnson’s if negative edges) | O(VE log V) |
11.11 Applications
- Maps and navigation: road networks are sparse weighted graphs. Production routers use Dijkstra variants with heavy preprocessing (contraction hierarchies) to answer continent-scale queries in milliseconds.
- Internet routing: link-state protocols (OSPF, IS-IS) run Dijkstra on each router’s view of the topology; distance-vector protocols run distributed Bellman-Ford. Chapter 28 covers both.
- Build and package systems: dependency graphs are DAGs, scheduled by topological sort; cycle detection produces the “circular dependency” error.
- Social networks: BFS gives degrees of separation; friend suggestions start from vertices at distance 2.
- The web: crawlers are BFS over links; PageRank is a random walk on the link graph.
- Compilers: control-flow graphs, call graphs, and SCC detection for finding mutually recursive functions.
- Garbage collection: the mark phase of a tracing collector is a graph traversal from the roots; unreachable objects are garbage.
- Image processing: pixels are vertices of a grid graph; flood fill is BFS or DFS; Kruskal-style merging underlies some image segmentation.
- Finance: fraud detection on transaction graphs; arbitrage detection via negative cycles.
11.12 Historical Context
Graph theory starts with Leonhard Euler’s 1736 paper on the Seven Bridges of Königsberg, which proved that no walk crosses each bridge exactly once. The argument (a vertex in the middle of such a walk needs even degree) is the handshake lemma in disguise.
The algorithms in this chapter come mostly from the 1950s, when telephone networks, operations research and the first computers made them practical problems:
- BFS: Konrad Zuse described it in 1945 (in his unpublished PhD work); Edward Moore rediscovered it in 1959 for finding the shortest path out of a maze.
- DFS as a maze-solving method dates to Charles Pierre Trémaux in the 19th century. Its power as an algorithmic tool, through discovery and finishing times, was established by John Hopcroft and Robert Tarjan in the early 1970s; their work won the 1986 Turing Award.
- Kruskal’s algorithm: Joseph Kruskal, 1956. Prim’s algorithm: Robert Prim, 1957, though Vojtěch Jarník had published it in 1930, and Otakar Borůvka had solved the MST problem in 1926 to plan an electrical network in Moravia.
- Dijkstra’s algorithm: Edsger Dijkstra designed it in 1956, reportedly in about twenty minutes at a café in Amsterdam, and published it in 1959.
- Bellman-Ford: Lester Ford (1956) and Richard Bellman (1958), with Edward Moore independently.
- Floyd-Warshall: Robert Floyd and Stephen Warshall, both 1962 (Bernard Roy had published it in 1959).
- Topological sort: Arthur Kahn, 1962.
- SCCs: Tarjan’s algorithm, 1972; Kosaraju’s (unpublished, 1978) was published independently by Micha Sharir in 1981.
- Union-find: Bernard Galler and Michael Fischer, 1964. Tarjan’s 1975 analysis showed the inverse-Ackermann bound.
- A*: Peter Hart, Nils Nilsson and Bertram Raphael, 1968, for the Shakey robot at SRI.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
11.1 ★ Choosing a representation. For each graph, pick adjacency matrix, adjacency list or CSR, and justify it in one sentence: (a) a road network of 20 million intersections that is loaded once and queried millions of times; (b) a 300-city graph with a known distance between every pair; (c) a social network where users add and remove friends continuously.
Solution
(a) CSR. The graph is huge and sparse (average degree around 2 to 4) and never changes during queries, so the compact, cache-friendly layout pays off and the rebuild cost never matters. A matrix would need 4 × 10^14 cells.
(b) Adjacency matrix. The graph is complete, so E = V² anyway and the matrix wastes nothing. 90,000 cells is tiny, and O(1) edge lookup plus Floyd-Warshall’s matrix loops are a natural fit.
(c) Adjacency list, with hash sets for neighbours. It is sparse and constantly mutated; CSR would need rebuilding on every change, and sets give O(1) expected “are these two friends?” and O(1) expected removal.
11.2 ★ Trace BFS. Using the adjacency-list order given, run bfs from vertex 1 on this undirected graph and give the dist and parent of every vertex, then the path to 6.
g = {1: [2, 3], 2: [1, 4, 5], 3: [1, 5], 4: [2, 6], 5: [2, 3, 6], 6: [4, 5]}
Solution
Queue evolution: [1] → pop 1, discover 2, 3 → pop 2, discover 4, 5 → pop 3 (5 already discovered) → pop 4, discover 6 → pop 5, pop 6.
| Vertex | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| dist | 0 | 1 | 1 | 2 | 2 | 3 |
| parent | None | 1 | 1 | 2 | 2 | 4 |
Path to 6: 1 → 2 → 4 → 6. The path 1 → 2 → 5 → 6 has the same length; BFS returns the one through 4 because 4 was discovered first and so discovered 6 first.
11.3 ★★ Two colours are not enough. A student detects directed cycles with plain DFS and a single visited set, reporting a cycle whenever an edge reaches a visited vertex. Give the smallest graph you can on which this reports a cycle that does not exist, and explain what the three-colour version does differently.
Hint
The false alarm needs an edge into a vertex that was fully explored on an earlier branch.
Solution
Three vertices suffice: A → B, A → C, C → B. DFS from A visits B (finishes it), returns, visits C, then sees C → B with B already visited, and reports a cycle. There is none.
In the three-colour version, B is black (finished) by then, not gray. Only an edge to a gray vertex (an ancestor still on the recursion stack) is a back edge, and only back edges indicate cycles. C → B is a cross edge and is ignored.
11.4 ★★ Dijkstra by hand. Run Dijkstra from S on the undirected graph with edges S-A (7), S-B (2), B-A (3), B-C (8), A-C (1), C-D (2), A-D (6). List vertices in the order they are finalised with their distances, and give the shortest path to D.
Solution
| Finalised | Distance | Relaxations performed |
|---|---|---|
| S | 0 | A → 7, B → 2 |
| B | 2 | A: 7 → 5, C → 10 |
| A | 5 | C: 10 → 6, D → 11 |
| C | 6 | D: 11 → 8 |
| D | 8 | none |
Shortest path to D: S → B → A → C → D, cost 2 + 3 + 1 + 2 = 8. Neither the direct-looking A-D edge nor the S-A edge is used.
11.5 ★★ The k-loop. A programmer “optimises” Floyd-Warshall by moving the k loop to be innermost (for i: for j: for k:). Construct a small graph on which it returns a wrong distance, and explain why the original order is correct.
Hint
With k innermost, dist[i][j] is finalised using values dist[i][k] and dist[k][j] that may not have been computed yet.
Solution
Take four vertices with edges 0→1 (1), 1→3 (1), 3→2 (1), so the only path from 0 to 2 is 0 → 1 → 3 → 2 with cost 3.
With k innermost, row 0 is finished before row 1 is touched, and within row 0 the pair (0, 2) is finished before (0, 3). So when (0, 2) is computed, the two candidates that could lead to the answer are both still ∞: dist[0][1] + dist[1][2] needs dist[1][2] (row 1, not processed yet), and dist[0][3] + dist[3][2] needs dist[0][3] (column 3, processed later in this row). dist[0][2] is left at ∞ and never revisited, even though a path exists. The correct version returns 3.
The correct order maintains an invariant: after the k-th outer iteration, dist[i][j] is the shortest path using only intermediates from {0, …, k}. A shortest path that uses k as an intermediate splits into an i→k part and a k→j part, each using only intermediates below k, and those values were completed in earlier iterations. Moving k inward destroys that invariant.
11.6 ★★ Kruskal with union-find. Run Kruskal on vertices 0 to 5 with edges (weight, u, v): (4,0,1), (1,1,2), (3,0,2), (2,2,3), (5,1,3), (6,3,4), (2,4,5), (7,3,5). List each edge as accepted or rejected, and give the MST weight.
Solution
Sorted order (ties broken by u, then v, as Python’s tuple sort does):
| Edge | Decision | Sets afterwards |
|---|---|---|
| (1, 1, 2) | accept | {1,2} |
| (2, 2, 3) | accept | {1,2,3} |
| (2, 4, 5) | accept | {1,2,3} {4,5} |
| (3, 0, 2) | accept | {0,1,2,3} {4,5} |
| (4, 0, 1) | reject: 0 and 1 already connected | |
| (5, 1, 3) | reject | |
| (6, 3, 4) | accept, 5 edges = n - 1, stop | {0,…,5} |
MST weight: 1 + 2 + 2 + 3 + 6 = 14. The edge (7, 3, 5) is never examined because the loop stops at n - 1 edges.
11.7 ★★ Shortest paths in a DAG. Write dag_shortest_paths(graph, source) that runs in O(V + E) on a weighted DAG, including one with negative edge weights. Explain why negative weights are safe here but not in Dijkstra.
Hint
If you process vertices in topological order, by the time you reach u, every edge into u has already been relaxed.
Solution
def dag_shortest_paths(graph, source):
"""graph[u] is a list of (v, weight); the graph must be a DAG."""
# Topological order by reverse DFS postorder (11.6).
visited, postorder = set(), []
def visit(u):
visited.add(u)
for v, _ in graph[u]:
if v not in visited:
visit(v)
postorder.append(u)
for u in graph:
if u not in visited:
visit(u)
dist = {u: float('inf') for u in graph}
dist[source] = 0
for u in reversed(postorder):
if dist[u] == float('inf'):
continue # not reachable from source
for v, w in graph[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist
Every path into u consists of edges from vertices that come before u in topological order. All of those were processed, and their edges relaxed, before u, so dist[u] is final when u is processed, regardless of sign. There is no “greedy” step that assumes later edges can’t help, which is exactly the assumption negative weights break in Dijkstra. Each vertex and edge is touched a constant number of times, so it is O(V + E).
Replacing each weight with its negation and running this gives the longest path in a DAG, which is the critical-path computation in project scheduling. (Longest path in a general graph is NP-hard.)
11.8 ★★★ Word ladder. Given a start word, a target word and a dictionary of equal-length words, find the minimum number of single-letter changes to turn start into target, where every intermediate word is in the dictionary (for example, COLD → CORD → CARD → WARD → WARM). The dictionary has N words of length L. Design an algorithm, state its complexity, and explain why building the graph explicitly by comparing all pairs is a poor idea.
Hint
The words are vertices, but you do not need the edges up front. Think about what all neighbours of “COLD” have in common.
Solution
It is BFS on an implicit graph whose vertices are words, with an edge between words differing in one position. BFS is right because edges are unweighted and we want the fewest steps.
Comparing all pairs to build the edges costs O(N² L): for N = 100,000 words that is 10^10 letter comparisons before the search even starts. Instead, bucket words by wildcard patterns: COLD belongs to the buckets *OLD, C*LD, CO*D, COL*. Two words are neighbours exactly when they share a bucket.
from collections import defaultdict, deque
def ladder_length(start, target, words):
buckets = defaultdict(list)
for w in set(words) | {start}:
for i in range(len(w)):
buckets[w[:i] + '*' + w[i + 1:]].append(w)
dist = {start: 0}
queue = deque([start])
while queue:
w = queue.popleft()
if w == target:
return dist[w]
for i in range(len(w)):
key = w[:i] + '*' + w[i + 1:]
for nxt in buckets[key]:
if nxt not in dist:
dist[nxt] = dist[w] + 1
queue.append(nxt)
buckets[key] = [] # each bucket only needs expanding once
return None
Building the buckets costs O(N L²) (N words × L patterns × O(L) to build each pattern string). Clearing a bucket after its first expansion means each bucket’s contents are scanned once in total, so the BFS is also O(N L²) overall. For the COLD → WARM example, it returns 4.
A further constant-factor improvement is bidirectional BFS: search from both ends and stop when the frontiers meet. If each word has about b neighbours and the answer is d steps, this explores roughly 2 b^(d/2) words instead of b^d.
Where this connects
- Chapter 5: Stacks and Queues. The two containers that turn into DFS and BFS
- Chapter 9: Heaps and Priority Queues. The structure inside Dijkstra and Prim, and why decrease-key matters
- Chapter 21: Algorithm Design Using Data Structures. The greedy and DP paradigms behind these algorithms
- Chapter 23: Advanced Competitive Programming Data Structures. Heavy-light decomposition, link-cut trees and DSU with rollback, for graphs that change or are queried along paths
- Chapter 28: Network Topology and Routing Data Structures. The same graph structures applied to network routing
Chapter 12: Hash Tables
12.1 The Hash Table Idea
Hash tables provide O(1) average-case lookup by computing an index from a key via a hash function.
Key: "apple"
Hash function: h(key) → 3
Index 3 → Value stored
Direct addressing would need 26 slots for letters.
Hash table needs fewer slots with good hash function.
The idea is best understood as a compromise between two extremes. Direct addressing (one array slot per possible key) gives genuine O(1) access but needs an array the size of the key space, which for 64-bit integers or arbitrary strings is impossible. A sorted array needs only n slots but costs O(log n) per lookup.
A hash table takes the array indexing of the first and the space of the second, and pays for it with collisions: squeezing a large key space into m slots guarantees that different keys sometimes land on the same one. Everything difficult about hash tables follows from that single consequence.
Worth being precise about the guarantee, since “O(1) lookup” is repeated so often it stops being examined. It is O(1) average case, under the assumption that keys distribute uniformly. The worst case is O(n) (every key colliding), and that worst case is reachable by an adversary who knows your hash function. This is not hypothetical: collision-flooding denial of service against PHP, Java, Python, and Ruby web frameworks was demonstrated in 2011 and forced all of them to change their hashing or limit their input (Section 12.2).
12.2 Hash Functions
A hash function maps keys to array indices.
Requirements
- Deterministic: Same key always maps to same index
- Uniform: Keys distribute evenly across indices
- Fast: O(1) computation
A fourth requirement belongs on that list for anything handling untrusted input: unpredictable. An attacker who can compute your hash function offline can generate thousands of keys that all collide, turning every operation into a linear scan. Uniformity over random input is not the same as uniformity over chosen input.
There is also a subtle correctness requirement that causes real bugs: equal keys must hash equally. In languages where you can override both equality and hashing, overriding one without the other produces a container that loses entries. The key is there, but the lookup goes to the wrong bucket. This is the single most common hash-table bug in application code.
Common Methods
Division Method:
h(k) = k mod m
Choose m as a prime not near a power of 2.
The reason for the prime matters. If m is a power of two, k mod m keeps only the low bits of k and discards everything else, so keys differing only in their high bits all collide. Pointers and aligned addresses have predictable low bits, which is exactly the case where this fails badly. A prime m mixes all the bits of k into the result.
Implementations that do want a power-of-two table size (because masking is faster than division) must therefore mix the bits first: Java’s HashMap XORs the high 16 bits into the low 16 before masking, precisely for this reason.
Multiplication Method:
h(k) = floor(m × (k × A mod 1))
Knuth’s A = (√5 - 1)/2 ≈ 0.618
The value of A is the reciprocal of the golden ratio, and it is chosen because it is the irrational number hardest to approximate with a fraction, which means successive multiples spread across the interval as evenly as possible rather than clustering. Unlike the division method, this works with any m, including powers of two.
Universal Hashing:
h(k) = ((a × k + b) mod p) mod m
Random a, b from large prime field.
This is the principled defense against adversarial input, and the guarantee is stronger than it looks: for any two distinct keys, the probability of collision over a random choice of (a, b) is at most 1/m. No fixed input is bad, because the function is not fixed until runtime. Carter and Wegman’s 1979 result is the reason modern languages seed their hash functions randomly at process start.
String Hashing:
/* Signed overflow is undefined behaviour in C, and a negative
intermediate makes `% m` negative, an out-of-bounds index.
Use unsigned, and mask or mod only at the end. */
unsigned long hash_string(const char *s, unsigned long m) {
unsigned long h = 5381;
while (*s) {
h = h * 33 + (unsigned char)*s; /* djb2; wraps harmlessly */
s++;
}
return h % m;
}
The original version of this function used int and applied % m inside the loop. Both are bugs: signed overflow is undefined behaviour, and a negative h yields a negative index in C. Hash arithmetic should always be done in unsigned types.
What production code actually uses. The classic multiply-and-add hashes (djb2, FNV, the h*31 in Java’s String.hashCode) are fine for well-behaved keys and weak against chosen ones. Modern defaults:
| Hash | Used by | Property |
|---|---|---|
| SipHash-1-3 | Rust, Python, Perl | Keyed, resists collision attacks |
| xxHash / wyhash | Databases, caches | Very fast, not attack-resistant |
| MurmurHash3 | Cassandra, Elasticsearch | Good distribution, fast, not keyed |
| CityHash / FarmHash | Fast on long keys |
Choose by threat model: keyed hashes for anything reachable by user input, fast unkeyed hashes for internal maps with trusted keys. Rust makes this explicit. The default HashMap uses SipHash, and swapping in FxHashMap for internal use is often a 2× speedup.
Hash Flooding
A web framework parses every POST request into a hash table of form fields before application code runs. If the attacker can choose field names that all have the same hash, n fields cost Θ(n²) comparisons to insert, and the server burns CPU on a request that took milliseconds to send. Crosby and Wallach described these algorithmic complexity attacks in 2003. At the 28th Chaos Communication Congress (28C3) in December 2011, Alexander Klink and Julian Wälde showed that the default hash tables in PHP, ASP.NET, Java, Python, Ruby and JavaScript platforms were all exploitable this way.
Building the colliding keys is easy when the hash is a fixed polynomial. Java’s String.hashCode computes s₀·31ⁿ⁻¹ + … + sₙ₋₁, and the two-character strings "Aa" and "BB" have the same hash (65 · 31 + 97 = 66 · 31 + 66 = 2112). Because the hash of a concatenation depends only on the hashes and lengths of its parts, any string made of k such blocks collides with all 2ᵏ of them:
from itertools import product
def java_string_hash(s):
"""Java's String.hashCode, reduced to 32 bits."""
h = 0
for ch in s:
h = (31 * h + ord(ch)) & 0xFFFFFFFF
return h
assert java_string_hash("Aa") == java_string_hash("BB") == 2112
keys = ["".join(blocks) for blocks in product(["Aa", "BB"], repeat=16)]
assert len(keys) == 65536
assert len({java_string_hash(k) for k in keys}) == 1 # one hash value
The full hash values are equal, so these keys collide for every table size, and resizing does not help. Inserting all 65,536 into a chained table makes about 65,536² / 2 ≈ 2 × 10⁹ key comparisons.
The responses came in layers:
- Limit the input. PHP added
max_input_vars(default 1,000 fields) in December 2011. This caps the damage for one entry point and fixes nothing else. - Randomize the seed. Python made a per-process random hash seed the default in 3.3. A random seed alone is not enough if the function has collisions that do not depend on the seed: at 29C3 (2012), Aumasson, Bernstein and Boßlet built seed-independent multicollisions for MurmurHash2, MurmurHash3 and CityHash64, the functions Ruby and others had just adopted as their randomized fix.
- Use a keyed pseudorandom function. SipHash (Aumasson and Bernstein, 2012) takes a secret 128-bit key chosen at startup. It is a pseudorandom function: without the key its outputs are unpredictable, so an attacker cannot compute colliding inputs offline, and it is still fast on the short keys hash tables see. Ruby switched to it in 2012, Python in 3.4 (PEP 456), and Rust and Perl use it too.
- Bound the worst case structurally. Java 8’s tree bins (Section 12.3) turn a flooded chain into a red-black tree, so even a successful attack costs O(log n) per operation instead of O(n).
The defences compose: Rust uses SipHash with randomly generated keys, and Java uses a predictable hash but caps the damage with trees.
12.3 Collision Resolution
When two keys hash to the same index, we need a strategy.
Chaining
Store colliding elements in a linked list:
Index ┌──────────────────────────────────┐
0 │ NULL │
1 │ [John:555] → [Mary:123] → NULL │
2 │ NULL │
3 │ [Alice:456] → NULL │
4 │ NULL │
5 │ [Bob:789] → NULL │
└──────────────────────────────────┘
Load factor α = n/m (elements per bucket)
- Search: O(1 + α)
- Insert: O(1)
- Delete: O(1 + α)
Because chains can grow without bound, α may exceed 1. A chained table never “fills up”, it just degrades. Deletion is straightforward, which is chaining’s main advantage over the alternative.
Java’s HashMap adds a refinement worth knowing: once a chain exceeds 8 entries it converts to a red-black tree, capping the worst case at O(log n) instead of O(n). That single change neutralises collision-flooding attacks without requiring a keyed hash.
Open Addressing
Find another empty slot in the array.
Linear Probing:
h(k), h(k)+1, h(k)+2, ... (mod m)
Problem: Primary clustering
Quadratic Probing:
h(k), h(k)+1², h(k)+2², h(k)+3², ... (mod m)
Problem: Secondary clustering
Double Hashing:
h(k), h(k)+h₂(k), h(k)+2×h₂(k), ... (mod m)
Best clustering behavior.
The clustering problems are worth distinguishing. Primary clustering is the serious one: with linear probing, any run of occupied slots grows at both ends, and longer runs are more likely to be extended, so clusters feed on themselves and probe sequences lengthen non-linearly. Secondary clustering is milder: keys with the same initial hash follow identical probe sequences, but keys with different hashes do not interfere.
Despite the theory favouring double hashing, linear probing usually wins in practice below about 70% load, because its probe sequence is sequential memory access. The next slot is almost always in the same cache line already fetched. Double hashing jumps randomly through the table and misses cache on nearly every probe. This is Chapter 16’s lesson applied: an algorithm with more operations can be faster if the operations are cheaper.
Two constraints specific to open addressing. Load factor must stay below 1, and performance collapses as it approaches: at α = 0.9 linear probing averages about 50 probes per unsuccessful search, versus about 2.5 at α = 0.5. Resize at 0.7 or below.
And deletion requires tombstones. Simply clearing a slot breaks the probe chain for any key that probed past it, making entries unreachable. The slot must be marked “deleted but occupied” instead, and tombstones accumulate, eventually requiring a rehash to clear.
12.4 Hash Table Operations
A complete open-addressing table, with the resize and tombstone handling that the sketch version omits:
_EMPTY = object() # never written
_DELETED = object() # tombstone: probe past it, but reuse on insert
class HashTable:
def __init__(self, capacity=16):
self._keys = [_EMPTY] * capacity
self._values = [None] * capacity
self._count = 0 # live entries
self._used = 0 # live entries + tombstones
def _probe(self, key):
"""Yield indices in probe order. Linear probing: cache-friendly."""
i = hash(key) % len(self._keys)
for _ in range(len(self._keys)):
yield i
i = (i + 1) % len(self._keys)
def __setitem__(self, key, value):
first_tombstone = None
for i in self._probe(key):
k = self._keys[i]
if k is _EMPTY:
# Reuse an earlier tombstone if we passed one.
slot = first_tombstone if first_tombstone is not None else i
if first_tombstone is None:
self._used += 1
self._keys[slot], self._values[slot] = key, value
self._count += 1
break
if k is _DELETED:
if first_tombstone is None:
first_tombstone = i
elif k == key:
self._values[i] = value # overwrite, no count change
return
# Resize on *used*, not count, since tombstones lengthen probes too.
if self._used > len(self._keys) * 0.7:
self._resize(len(self._keys) * 2)
def __getitem__(self, key):
for i in self._probe(key):
k = self._keys[i]
if k is _EMPTY:
raise KeyError(key) # probe chain ended
if k is not _DELETED and k == key:
return self._values[i]
raise KeyError(key)
def __delitem__(self, key):
for i in self._probe(key):
k = self._keys[i]
if k is _EMPTY:
raise KeyError(key)
if k is not _DELETED and k == key:
self._keys[i] = _DELETED # tombstone, not _EMPTY
self._values[i] = None
self._count -= 1
return
raise KeyError(key)
def _resize(self, new_capacity):
"""Every key must be rehashed; indices depend on table size."""
old = [(k, v) for k, v in zip(self._keys, self._values)
if k is not _EMPTY and k is not _DELETED]
self._keys = [_EMPTY] * new_capacity
self._values = [None] * new_capacity
self._count = self._used = 0
for k, v in old:
self[k] = v # tombstones dropped here
Four details in that code are the ones people get wrong:
_EMPTYterminates a probe chain;_DELETEDdoes not. Confusing the two makes entries unreachable after a deletion.- Resize triggers on
_used, not_count. A table churning through insertions and deletions can be mostly tombstones with few live entries; if you only watch the live count, probe sequences grow without ever triggering a rehash. - Insertion reuses the first tombstone it passed, rather than the empty slot at the end. Otherwise the table fills with tombstones even when entries are being replaced.
- Resizing rehashes everything. Indices are computed modulo the table size, so nothing carries over. This makes a single insertion O(n) occasionally, which is why the bound is amortized O(1): the same argument as the dynamic array in Chapter 3.
That last point has a consequence for latency-sensitive systems: a hash table’s average insert is O(1), but one insert in every n takes O(n). If tail latency matters, either pre-size the table or use an incremental-resize scheme that migrates a few entries per operation, as Redis does.
12.5 Modern Open Addressing
The table in Section 12.4 is linear probing much as it was implemented in 1954, and it has three weaknesses that show up in production. Probe lengths have a long tail: the average is small but a few unlucky keys sit dozens of slots from home. Unsuccessful searches scan all the way to an empty slot. And every probe compares a full key, which for strings means a memory access and a comparison loop per slot. The two designs that dominate modern libraries attack these directly. Robin Hood hashing fixes the tail and the deletion problem; Swiss tables make each probe so cheap that the tail barely matters.
Robin Hood Hashing
For an entry stored at slot i whose home slot is h = hash(k) mod m, its probe-sequence length (PSL) is (i − h) mod m: how many slots past home it sits. A lookup that finds the entry costs PSL + 1 probes. Plain linear probing gives each slot to whichever key arrives first, so a key’s PSL depends on luck.
Robin Hood hashing (Celis, 1985) changes one rule. Insertion walks forward from home, tracking the PSL d the new entry would have at the current slot. If the occupant’s PSL is smaller than d, the occupant is “richer” (closer to home), so the new entry takes the slot and the evicted occupant continues the walk with its own PSL. The rich give to the poor.
This maintains an invariant: moving from one occupied slot to the next, PSL rises by at most one. Equivalently, within a run of occupied slots, entries are sorted by home slot. Two consequences follow.
- Unsuccessful lookups stop early. Suppose a search for k reaches slot i at distance d and the occupant’s PSL is less than d. If k were stored further on, at slot j, its PSL there would be d + (j − i), so PSL would have to rise by more than j − i over j − i steps, which the invariant forbids. So the search can stop without reaching an empty slot. (An empty slot can be treated as PSL −1, which makes it the same test.)
- Deletion needs no tombstones. Remove the entry, then shift each following entry back one slot, reducing its PSL by one, until reaching an empty slot or an entry with PSL 0 (already at home, so it cannot move closer). This is backward-shift deletion. The run stays sorted and the table never accumulates tombstones.
The code keeps the conventions of HashTable above, with a third array holding each slot’s PSL:
class RobinHoodTable:
"""Linear probing where the entry farther from home keeps the slot."""
def __init__(self, capacity=16):
self._keys = [None] * capacity
self._values = [None] * capacity
self._dist = [-1] * capacity # probe-sequence length; -1 marks empty
self._count = 0
def __len__(self):
return self._count
def _home(self, key):
return hash(key) % len(self._keys)
def _find(self, key):
"""Slot holding key, or None. Stops early at an empty or richer slot."""
m = len(self._keys)
i, d = self._home(key), 0
while self._dist[i] >= d: # empty (-1) is < d too, so it also stops
if self._dist[i] == d and self._keys[i] == key:
return i
i, d = (i + 1) % m, d + 1
return None
def __getitem__(self, key):
i = self._find(key)
if i is None:
raise KeyError(key)
return self._values[i]
def __setitem__(self, key, value):
i = self._find(key)
if i is not None:
self._values[i] = value # overwrite in place
return
if self._count + 1 > len(self._keys) * 0.9:
self._resize(len(self._keys) * 2)
m = len(self._keys)
i, d = self._home(key), 0
while self._dist[i] != -1:
if self._dist[i] < d: # occupant is closer to home: rob it
key, self._keys[i] = self._keys[i], key
value, self._values[i] = self._values[i], value
d, self._dist[i] = self._dist[i], d
i, d = (i + 1) % m, d + 1
self._keys[i], self._values[i], self._dist[i] = key, value, d
self._count += 1
def __delitem__(self, key):
i = self._find(key)
if i is None:
raise KeyError(key)
m = len(self._keys)
j = (i + 1) % m
while self._dist[j] > 0: # backward shift: pull the run left
self._keys[i], self._values[i] = self._keys[j], self._values[j]
self._dist[i] = self._dist[j] - 1
i, j = j, (j + 1) % m
self._keys[i], self._values[i], self._dist[i] = None, None, -1
self._count -= 1
def _resize(self, new_capacity):
old = [(k, v) for k, v, d in zip(self._keys, self._values, self._dist)
if d != -1]
self.__init__(new_capacity)
for k, v in old:
self[k] = v
Two details. _find compares the stored PSL before the key: an entry with a different PSL at this slot has a different home, so it cannot be k, and the expensive key comparison is skipped. Production tables store part of the hash per slot for the same reason. And __setitem__ searches for an existing key first, so the displacement walk never needs to compare keys: every entry it carries is known to be unique.
A trace. Take m = 8 and h(k) = k mod 8 (small integers hash to themselves in CPython), and insert 2, 3, 8, 16, 24. The first four go to slots 2, 3, 0, 1 with no conflict. Key 24 has home 0:
| Slot | Occupant (PSL) | 24’s distance | Action |
|---|---|---|---|
| 0 | 8 (0) | 0 | 0 is not < 0, move on |
| 1 | 16 (1) | 1 | 1 is not < 1, move on |
| 2 | 2 (0) | 2 | 0 < 2: 24 takes slot 2, carry 2 at distance 0 |
| 3 | 3 (0) | 1 | 0 < 1: 2 takes slot 3, carry 3 at distance 0 |
| 4 | empty | 1 | 3 settles here with PSL 1 |
Compare the two layouts:
slot: 0 1 2 3 4 5 6 7
linear probing: 8 16 2 3 24 . . . PSLs 0 1 0 0 4
Robin Hood: 8 16 24 2 3 . . . PSLs 0 1 2 1 1
Both PSL lists sum to 5, so the average successful lookup costs the same, but the worst entry dropped from 4 to 2. An unsuccessful search for 32 (home 0) scans slots 0 to 5 under linear probing, 6 probes. Under Robin Hood it stops at slot 3, where it is at distance 3 but the occupant has PSL 1: 4 probes. Deleting 16 from the Robin Hood table shifts 24, 2 and 3 back one slot each, giving 8 24 2 3 . . . . with PSLs 0 1 0 0, which is exactly the table you would get if 16 had never been inserted.
Why it works: the mean is fixed, the variance is not. The equal sums in the trace are not a coincidence. Under linear probing, Robin Hood never changes the total PSL of a set of keys, only who pays it (Exercise 12.9). What it changes is the spread. Measured on one table of m = 65,536 slots filled with random hash values:
| α | Mean PSL (both) | PSL variance, LP / RH | Max PSL, LP / RH | Probes per miss, LP / RH |
|---|---|---|---|---|
| 0.50 | 0.50 | 1.6 / 0.7 | 29 / 7 | 2.5 / 1.7 |
| 0.75 | 1.5 | 18.6 / 3.9 | 115 / 24 | 8.2 / 2.9 |
| 0.90 | 4.3 | 234 / 19 | 467 / 36 | 44.5 / 5.7 |
At α = 0.9 the longest probe drops by a factor of 13 and misses get 8 times cheaper, which is what lets Robin Hood tables run at a load factor of 0.9 where plain linear probing has collapsed. All operations remain O(1) expected time for a fixed α < 1, O(n) worst case, with insertion O(1) amortized across resizes. The costs are an extra field per slot (a byte is enough for the PSL in practice), more writes per insertion because of the swaps, and deletions that may shift a whole run.
Robin Hood hashing was the design of Rust’s standard HashMap until Rust 1.36 (2019), and it is used by C++ libraries such as tsl::robin_map, which combines it with backward-shift deletion.
Swiss Tables
Robin Hood still compares keys slot by slot. A Swiss table, the design behind Google’s Abseil flat_hash_map, moves the search out of the key array altogether.
Layout. Alongside the array of slots (each holding a key and value) sits a separate array of control bytes, one per slot. A control byte says what the slot holds:
| Control byte | Meaning |
|---|---|
0b1000_0000 (0x80) | empty |
0b1111_1110 (0xFE) | deleted (tombstone) |
0b0xxx_xxxx | full; the low 7 bits are H2 of the key’s hash |
These are Abseil’s values (Abseil also has a sentinel, 0xFF, marking the end of the array for iteration). The essential rule is that special states have the top bit set and full slots have it clear, so “is this slot free?” is a single bit test.
Splitting the hash. A 64-bit hash is split into two parts. H1, 57 bits, chooses where in the table the probe starts. H2, the other 7 bits, is stored in the control byte. (The original design took H2 from the low 7 bits; current Abseil and Rust’s hashbrown take the top 7. Either works if the hash is well mixed.)
Probing a group at once. Slots are examined in groups of 16. To look up k, start at the group H1 selects, load its 16 control bytes into one 128-bit SSE2 register, and compare all 16 against H2 in a single instruction (_mm_cmpeq_epi8, after broadcasting H2 to all 16 lanes). A second instruction (_mm_movemask_epi8) packs the result into a 16-bit mask with one bit per matching slot. Only those slots’ keys are compared. If the group also contains an empty byte, the key is absent; otherwise move to the next group. For example, with H2 = 0x15:
slot j: 0 1 2 3 4 5 6 7 ... 15
control: 0x15 0x80 0x3A 0x15 0xFE 0x61 0x80 0x0C ...
== H2? 1 0 0 1 0 0 0 0
match mask: 0b...1001 -> compare keys in slots 0 and 3 only
empty mask: 0b...0100_0010 (nonzero) -> if neither matches, k is absent
A full slot holding a different key matches a random 7-bit H2 with probability 1/128, so wasted key comparisons are rare. In the model below, filled to the maximum load of 7/8, a successful lookup inspected 1.1 groups and made 0.07 failed key comparisons on average, and an unsuccessful one inspected 2.1 groups and made 0.23.
Why it wins on cache behaviour. A probe step reads 16 bytes of contiguous metadata, a quarter of a 64-byte cache line, instead of 16 keys and values spread over several lines. A typical lookup touches one line of control bytes and then the one slot that matches: about two cache misses whatever the key type, and the key comparison, which for strings is the expensive part, almost always succeeds the first time it runs. Because one step covers 16 slots, clusters cost little, and the table runs comfortably at 7/8 load with only one byte of overhead per slot. No PSLs are stored, and nothing moves on insert.
Groups are visited in triangular order (offsets of 0, 1, 3, 6, 10, … groups), which visits every group exactly once when the number of groups is a power of two. Deletion writes a tombstone, with one refinement: if the deleted slot’s group still contains an empty byte, then that group has never been full, so no insertion ever probed past it, and the slot can be marked empty instead. Tombstones consume the growth budget like full slots, so a delete-heavy table eventually rehashes, often in place at the same size.
The following Python models that logic. It has no SIMD: _match loops over 16 bytes where the real code runs about three instructions. It also simplifies one thing: here groups are aligned blocks of 16, while Abseil and hashbrown load 16 bytes starting at any slot, copying the first group’s control bytes to the end of the array so a load can wrap around. With unaligned groups, the never-full test for deletion has to look at the control bytes on both sides of the slot.
GROUP = 16 # slots per group: one 16-byte SSE2 register
EMPTY, DELETED = 0x80, 0xFE # Abseil's values; a full slot holds 0x00-0x7F
MASK64 = (1 << 64) - 1
def _mix(h):
"""Scramble Python's hash: small ints hash to themselves, and both
H1 and H2 need well-mixed bits."""
h = (h * 0x9E3779B97F4A7C15) & MASK64
return h ^ (h >> 29)
class SwissTable:
def __init__(self, groups=1): # groups must be a power of 2
n = groups * GROUP
self._ctrl = bytearray([EMPTY]) * n
self._keys = [None] * n
self._values = [None] * n
self._count = 0
self._growth_left = n * 7 // 8 # max load factor 7/8
def __len__(self):
return self._count
@staticmethod
def _split(key):
h = _mix(hash(key))
return h >> 7, h & 0x7F # H1: where to start, H2: 7-bit tag
def _match(self, g, pred):
"""Bitmask of slots j in group g with pred(ctrl byte). Models one SIMD
compare plus movemask: 16 bytes tested at once in hardware."""
base, mask = g * GROUP, 0
for j in range(GROUP):
if pred(self._ctrl[base + j]):
mask |= 1 << j
return mask
def _probe(self, h1):
"""Groups in triangular order g, g+1, g+3, g+6, ...: with a power-of-2
number of groups this visits every group exactly once."""
ngroups = len(self._ctrl) // GROUP
g = h1 & (ngroups - 1)
for i in range(ngroups):
yield g
g = (g + i + 1) & (ngroups - 1)
def _find(self, key):
h1, h2 = self._split(key)
for g in self._probe(h1):
m = self._match(g, lambda c: c == h2)
while m: # usually 0 or 1 candidates
i = g * GROUP + (m & -m).bit_length() - 1
if self._keys[i] == key:
return i
m &= m - 1 # clear lowest set bit
if self._match(g, lambda c: c == EMPTY):
return None # nothing ever probed past here
return None
def __getitem__(self, key):
i = self._find(key)
if i is None:
raise KeyError(key)
return self._values[i]
def __setitem__(self, key, value):
i = self._find(key)
if i is not None:
self._values[i] = value
return
if self._growth_left == 0: # full of entries or tombstones
ngroups = len(self._ctrl) // GROUP
grow = self._count >= len(self._ctrl) * 7 // 16
self._rehash(2 * ngroups if grow else ngroups)
h1, h2 = self._split(key)
for g in self._probe(h1):
m = self._match(g, lambda c: c & 0x80) # EMPTY or DELETED: top bit set
if m:
i = g * GROUP + (m & -m).bit_length() - 1
if self._ctrl[i] == EMPTY:
self._growth_left -= 1 # reusing a tombstone costs nothing
self._ctrl[i] = h2
self._keys[i], self._values[i] = key, value
self._count += 1
return
def __delitem__(self, key):
i = self._find(key)
if i is None:
raise KeyError(key)
if self._match(i // GROUP, lambda c: c == EMPTY):
self._ctrl[i] = EMPTY # group was never full: no probe went past it
self._growth_left += 1
else:
self._ctrl[i] = DELETED # some key may have probed past: tombstone
self._keys[i] = self._values[i] = None
self._count -= 1
def _rehash(self, groups):
old = [(k, v) for c, k, v in zip(self._ctrl, self._keys, self._values)
if not c & 0x80]
self.__init__(groups)
for k, v in old:
self[k] = v
The _mix step is not decoration. With Python’s identity hash for integers, the top bits of every small key would be zero and every key would share the same H2, turning each probe into a full scan of the group. Swiss tables need a hash whose every bit is well mixed, which is why Abseil and hashbrown ship their own hash functions rather than trusting the key type’s. Complexity is the same as for any open-addressing table: O(1) expected per operation at bounded load, O(n) worst case, insertion O(1) amortized.
Who uses what. It is worth being precise, because “hash table” names a different structure in every language:
- C++: Abseil’s
flat_hash_mapandflat_hash_setare Swiss tables.std::unordered_mapuses chaining, because the standard requires that references to elements survive a rehash and exposes a bucket interface, which together rule out open addressing. - Rust:
std::collections::HashMaphas been a Swiss table since Rust 1.36 (2019), when the standard library adopted thehashbrowncrate. It uses 16-slot groups with SSE2 on x86 and 8-slot groups on other 64-bit targets. Its byte values differ from Abseil’s (empty is 0xFF, deleted is 0x80), but the top-bit rule is the same. - Go: the built-in
mapswitched to a Swiss table in Go 1.24 (February 2025). It uses groups of 8 slots with a 64-bit control word, SIMD instructions on amd64 and portable bit arithmetic elsewhere (Exercise 12.10), and the same 7/8 load factor. Each map is a set of tables of at most 1,024 slots, with upper hash bits choosing the table, so growing the map splits one small table at a time and no single insertion pays for rehashing the whole map. - Python:
dictis neither linear probing nor a Swiss table. It probes with the recurrence i ← (5i + 1 + perturb) mod 2ᵏ, shiftingperturb(initially the full hash) right by 5 bits each step, so the high bits of the hash influence the probe sequence; this matters because small integers hash to themselves. Since CPython 3.6 the table is also compact: the hashed array holds only small integer indices (1 byte each for small tables), pointing into a dense array of (hash, key, value) entries kept in insertion order. An empty slot then costs 1 byte instead of a 24-byte entry, and the dense array is why dicts iterate in insertion order, a guarantee of the language since 3.7. The index array is kept at most 2/3 full. - Java:
HashMapuses chaining with tree bins (Section 12.3).
Choosing a Scheme
| Chaining | Linear probing (12.4) | Robin Hood | Swiss table | |
|---|---|---|---|---|
| Memory per entry | Node per entry (next pointer plus allocator overhead) and a bucket pointer per slot | Key and value only, but 1 − α of the slots are empty and full-sized | As linear probing, plus a PSL or stored hash per slot | Key and value plus 1 control byte per slot |
| Probe behaviour | One dependent pointer load per chain node, each a likely cache miss | Sequential and cache-friendly; primary clustering gives long tails; misses scan to an empty slot | Sequential with low variance; misses stop at the first richer occupant | 16 (or 8) control bytes tested per step; keys compared only on a 7-bit tag match |
| Deletion | Unlink the node; no tombstones | Tombstones, cleared only by rehashing | Backward shift; no tombstones | Tombstone, or empty if the group was never full |
| Max useful α | Above 1 still works; Java uses 0.75, C++ unordered_map 1.0 | About 0.7 | About 0.9 | 7/8 |
| Used by | Java HashMap, C++ std::unordered_map | Java IdentityHashMap, many hand-written tables | Rust before 1.36, tsl::robin_map | Abseil, Rust HashMap, Go 1.24+ |
All four are O(1) expected and O(n) worst case per operation; the differences are constant factors, memory, and tail behaviour. For open addressing, memory per stored entry is the slot size divided by α: at 7/8 load a Swiss table spends 8/7 of a slot per entry, at 0.7 linear probing spends 10/7. Chaining remains the right choice when elements must never move (other code holds pointers to them) or are large, since open addressing copies entries on every resize. When keys and values are small and lookups are hot, which is the common case, the Swiss table is the current default for good reason.
12.6 Perfect Hashing
If all keys are known in advance, we can construct a hash table with no collisions.
Two-level scheme:
- First level: Hash to buckets
- Second level: Hash each bucket with no collisions (requires more slots)
The FKS scheme (Fredman, Komlós, Szemerédi, 1984) makes this concrete and gives the surprising result: O(1) worst-case lookup in O(n) total space. The trick is the second level. A bucket holding bᵢ keys gets a table of size bᵢ², where a randomly chosen hash function is collision-free with probability above ½, so a few retries always find one. Squaring sounds wasteful, but the expected sum of bᵢ² across all buckets is O(n) when the first level is chosen well.
Minimal perfect hashing goes further, mapping n keys to exactly n slots with no gaps. Modern constructions (CHD, BBHash, PTHash) achieve about 2–3 bits of overhead per key. These are used where a key set is fixed and lookups are hot: compiler keyword recognition, gperf-generated parsers, static routing tables, and the term dictionaries in search indexes.
12.7 Applications
Dictionaries/Maps:
- Python dict, Java HashMap, C++ unordered_map
Sets:
- Python set, Java HashSet
Caches:
- LRU cache with hash table + linked list
Database indexing:
- Hash indexes (for equality queries)
Symbol tables:
- Compiler symbol tables
Counting/frequency:
- Word frequency in text
The LRU cache is worth expanding, because it is the canonical example of composing two structures to get properties neither has alone. A hash table gives O(1) lookup but no notion of recency; a doubly linked list gives O(1) reordering but no lookup. Combine them (hash key → list node, list ordered by recency), and every operation is O(1): find the node by hash, unlink it, move it to the head. Python’s functools.lru_cache and every production cache are built this way.
Where hash tables are the wrong choice, which is easy to forget given how good the average case is: any workload needing ordered iteration, range queries, nearest-key lookups, or prefix matching. Those need a tree or a trie. The failure mode is insidious because a hash table works fine until the day someone asks for “all records between these two dates”.
12.8 Historical Context
Hash tables were invented independently by multiple researchers in the 1950s-1960s. The term “hash” comes from the idea of “hashing” (mixing up) the keys.
The first published description is Arnold Dumey’s in 1956, though Hans Peter Luhn had described chaining in an internal IBM memorandum in 1953, and Gene Amdahl, Elaine McGraw, and Arthur Samuel had implemented linear probing for the IBM 701 assembler in 1954: making it one of the few fundamental data structures whose invention is documented in code before it appeared in a paper.
Donald Knuth’s analysis in The Art of Computer Programming Volume 3 (1973) established the mathematics of both methods and remains the standard reference. Carter and Wegman introduced universal hashing in 1979, which turned adversarial resistance from a hope into a theorem, and Fredman, Komlós, and Szemerédi gave the first O(1) worst-case scheme in 1984. Pagh and Rodler’s cuckoo hashing (2001) achieved the same worst-case guarantee with a far simpler structure.
Robin Hood hashing comes from Pedro Celis’s work with Per-Åke Larson and Ian Munro at Waterloo, published at FOCS in 1985 and in Celis’s 1986 PhD thesis. Crosby and Wallach described algorithmic complexity attacks on hash tables in 2003; Klink and Wälde’s 28C3 talk in December 2011 showed how widely web platforms were exposed, and Aumasson and Bernstein’s SipHash (2012) became the standard response. Swiss tables were designed at Google by Sam Benzaquen, Alkis Evlogimenos, Matt Kulukundis and Roman Perepelitsa, presented by Kulukundis at CppCon 2017, and open-sourced in Abseil in 2018. Rust adopted the design through hashbrown in 2019 and Go in 2025.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
12.1 ★ Trace linear probing. A table has m = 11 slots, h(k) = k mod 11, and uses linear probing. Insert the keys 22, 1, 13, 11, 24, 33 in that order. Show the final table and the number of probes each insertion took. Then count the probes for an unsuccessful search for 44. For comparison, how many key comparisons would the same search cost in a chained table with the same hash function?
Solution
| Key | h(k) | Slots probed | Lands in | Probes |
|---|---|---|---|---|
| 22 | 0 | 0 | 0 | 1 |
| 1 | 1 | 1 | 1 | 1 |
| 13 | 2 | 2 | 2 | 1 |
| 11 | 0 | 0, 1, 2, 3 | 3 | 4 |
| 24 | 2 | 2, 3, 4 | 4 | 3 |
| 33 | 0 | 0, 1, 2, 3, 4, 5 | 5 | 6 |
Final table: [22, 1, 13, 11, 24, 33, _, _, _, _, _].
Searching for 44 starts at 44 mod 11 = 0 and must walk the whole run 0..5 before reaching the empty slot 6: 7 probes, to learn that the key is absent.
With chaining, bucket 0 holds only the keys that hash to 0 (22, 11, 33), so the search costs 3 comparisons. The difference is primary clustering: keys hashing to 0, 1 and 2 merged into a single run, and every search that lands anywhere in that run pays for all of it. Only 6 of 11 slots are full (α ≈ 0.55), yet this search already costs 7 probes.
12.2 ★ Why not a power of two? The keys are 16 aligned addresses: 4096, 4160, 4224, …, 4096 + 64 × 15 (consecutive multiples of 64). (a) How many distinct buckets does h(k) = k mod 16 use? (b) How many does h(k) = k mod 17 use? (c) Java’s HashMap computes h ^ (h >>> 16) before masking to a power-of-two size. Does that rescue these keys in a 16-slot table?
Hint
Write 64 in binary. For (b), ask whether 64 mod 17 shares a factor with 17.
Solution
(a) One. Every key is a multiple of 64, so its low 6 bits are zero, and k mod 16 reads only the low 4 bits. All 16 keys land in bucket 0, and every operation is a scan of one 16-long chain.
(b) Sixteen, all different. The keys are 4096 + 64i. Modulo 17, the step 64 is 13, and since 17 is prime, multiples of 13 cycle through every residue before repeating. Sixteen consecutive steps therefore hit sixteen distinct buckets (in fact every residue except 3).
(c) No. The spreader XORs the high 16 bits into the low 16, but every key here is below 2¹⁶, so h >>> 16 is 0 and the XOR changes nothing. The keys still differ only in bits 6 to 9, and a 16-slot mask reads bits 0 to 3. The spreader helps keys that differ in their high half; it does nothing for keys that differ only in middle bits. (Java’s fallback for this case is the one described in Section 12.3: the overlong chain becomes a red-black tree.)
12.3 ★★ Tombstones by hand. Using the HashTable from Section 12.4 with capacity 8 and integer keys (in CPython, hash(k) == k for small non-negative integers), run:
t = HashTable(8)
t[3] = "a"
t[11] = "b"
t[19] = "c"
del t[11]
t[27] = "d"
(a) Show the key array after the three inserts. (b) Show it after the delete, and what t[19] would do if __delitem__ wrote _EMPTY instead of _DELETED. (c) Where does 27 go, and what are _count and _used at the end?
Hint
3, 11, 19 and 27 all hash to slot 3. Follow first_tombstone through __setitem__.
Solution
(a) All three keys hash to 3 mod 8 = 3, so linear probing places them in slots 3, 4, 5:
slot: 0 1 2 3 4 5 6 7
keys: E E E 3 11 19 E E E = _EMPTY
(b) Deleting 11 writes a tombstone into slot 4:
slot: 0 1 2 3 4 5 6 7
keys: E E E 3 T 19 E E T = _DELETED
t[19] probes 3 (key 3, not a match), 4 (tombstone, keep going), 5 (match). If the delete had written _EMPTY, the probe would stop at slot 4 and raise KeyError(19) even though 19 is sitting in slot 5. That is the bug the tombstone exists to prevent.
(c) Inserting 27 probes slot 3 (key 3, no match), slot 4 (tombstone: first_tombstone = 4), slot 5 (key 19, no match), slot 6 (_EMPTY). It stops there because it has now proven 27 is not already present, then writes 27 into the remembered tombstone at slot 4, not into slot 6:
slot: 0 1 2 3 4 5 6 7
keys: E E E 3 27 19 E E
_count is 3 (live keys 3, 27, 19). _used is also 3: it went to 3 after the inserts, stayed at 3 on the delete (the tombstone still occupies a slot), and stayed at 3 on the final insert because it reused a slot that was already counted.
12.4 ★★ Find the bug. This class is meant to make usernames case-insensitive. What does the snippet print, and why? Fix it.
class Username:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name.lower() == other.name.lower()
def __hash__(self):
return hash(self.name)
users = {Username("Alice"): 1}
print(Username("alice") in users)
Solution
It prints False, even though Username("Alice") == Username("alice") is True.
This is the “equal keys must hash equally” rule from Section 12.2. __hash__ uses the raw name, so "Alice" and "alice" get unrelated hashes and the lookup goes to a different slot from the one the entry was stored in. The dictionary never gets as far as calling __eq__. (CPython also compares stored full hash values before calling __eq__, so even an accidental slot collision would not save it.)
The fix is to hash exactly what equality compares:
class Username:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name.lower() == other.name.lower()
def __hash__(self):
return hash(self.name.lower())
The general rule: __hash__ may use less information than __eq__ (that only adds collisions), but never information that __eq__ ignores. Python partly enforces this by setting __hash__ = None when a class defines __eq__ alone, which makes instances unhashable rather than silently wrong; overriding both, as here, bypasses that safety net.
12.5 ★★ Clusters feed on themselves. A linear-probing table has m = 10 slots, of which slots 2, 3, 4, 5 and 8 are occupied. The next key’s hash is uniform over 0..9. For each empty slot, what is the probability that the new key ends up there? What does this say about the claim that “longer runs are more likely to be extended”?
Hint
A key lands in the first empty slot at or after its hash position. Which hash values lead to slot 6?
Solution
A key with hash h goes to the first empty slot at or after h (wrapping around).
| Empty slot | Hash values that land there | Probability |
|---|---|---|
| 0 | 0 | 1/10 |
| 1 | 1 | 1/10 |
| 6 | 2, 3, 4, 5, 6 | 5/10 |
| 7 | 7 | 1/10 |
| 9 | 8, 9 | 2/10 |
The probabilities sum to 1. The slot just past the run of length 4 catches half of all insertions, because every key that hashes anywhere into the run slides to its end. In general, the empty slot after a run of length L is hit with probability (L + 1)/m. Once slot 6 fills, the run becomes 2..6 and slot 7 catches 6/10 of the next insertions, so the run’s capture probability grows with every key it absorbs. That positive feedback is primary clustering, and it is why probe counts rise non-linearly as α grows.
12.6 ★★ Build the LRU cache. Section 12.7 describes an LRU cache as a hash table pointing into a doubly linked list. Implement LRUCache(capacity) with get(key) (return the value or None, and mark the key most recently used) and put(key, value) (insert or update, evicting the least recently used key when full). Both must be O(1). Do not use OrderedDict.
Hint
Sentinel head and tail nodes remove every special case for an empty list. When you evict the tail node you must also delete it from the dictionary, so the node has to remember its key.
Solution
class _Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key=None, value=None):
self.key, self.value = key, value
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.map = {} # key -> _Node
self.head = _Node() # sentinel: most recent side
self.tail = _Node() # sentinel: least recent side
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, node):
node.prev.next, node.next.prev = node.next, node.prev
def _push_front(self, node):
node.prev, node.next = self.head, self.head.next
self.head.next.prev = node
self.head.next = node
def get(self, key):
node = self.map.get(key)
if node is None:
return None
self._unlink(node) # O(1): the hash gave us the node
self._push_front(node)
return node.value
def put(self, key, value):
node = self.map.get(key)
if node is not None:
node.value = value
self._unlink(node)
self._push_front(node)
return
if len(self.map) == self.capacity:
lru = self.tail.prev # least recently used
self._unlink(lru)
del self.map[lru.key] # why the node stores its key
node = _Node(key, value)
self.map[key] = node
self._push_front(node)
c = LRUCache(2)
c.put("a", 1)
c.put("b", 2)
assert c.get("a") == 1 # order now: a, b
c.put("c", 3) # evicts b
assert c.get("b") is None
assert c.get("a") == 1 and c.get("c") == 3
Every operation is one dictionary operation (O(1) average) plus a constant number of pointer updates. Neither structure alone could do this: the dictionary cannot find the oldest entry without a scan, and the list cannot find a key without a scan. The list must be doubly linked because _unlink needs the predecessor, and the only handle we have is the node itself.
12.7 ★★★ Why FKS fits in O(n) space. Assume a universal family: for any two distinct keys, a randomly chosen function into m slots makes them collide with probability at most 1/m. (a) Show that hashing a bucket’s b keys into a table of size b² is collision-free with probability greater than ½. (b) The first level hashes all n keys into m = n buckets, giving bucket sizes b₁, …, bₙ. Show that E[Σ bᵢ²] < 2n, and explain how this yields O(n) total space with an expected constant number of retries.
Hint
Count colliding pairs and use Markov’s inequality, Pr[X ≥ t] ≤ E[X]/t for non-negative X. For (b), note that b² = b + 2 · C(b, 2).
Solution
(a) Let X be the number of pairs of keys that collide. There are C(b, 2) = b(b − 1)/2 pairs, each colliding with probability at most 1/b², so
E[X] ≤ b(b − 1) / (2b²) = (b − 1) / (2b) < ½.
X is a non-negative integer, so by Markov, Pr[X ≥ 1] ≤ E[X] < ½. The table is collision-free with probability greater than ½, and the expected number of random functions tried before finding a good one is less than 2.
(b) For each bucket, bᵢ² = bᵢ + 2 · C(bᵢ, 2), and C(bᵢ, 2) counts the pairs that collided into bucket i. Summing over buckets:
Σ bᵢ² = n + 2C, where C is the total number of colliding pairs at the first level.
There are C(n, 2) pairs, each colliding with probability at most 1/n, so E[C] ≤ (n − 1)/2 and
E[Σ bᵢ²] ≤ n + (n − 1) < 2n.
By Markov again, Pr[Σ bᵢ² ≥ 4n] < ½. So the construction picks a first-level function, checks whether Σ bᵢ² < 4n, and retries if not (expected fewer than 2 attempts); then builds each second-level table (expected fewer than 2 attempts each). Total space is n first-level slots plus Σ bᵢ² < 4n second-level slots, which is O(n), and a lookup is exactly two hash evaluations, which is O(1) worst case. Squaring each bucket’s size looks extravagant, but the squares are small because large buckets are rare.
12.8 ★★ Robin Hood by hand. Use the RobinHoodTable from Section 12.5 with capacity 8, so h(k) = k mod 8. (a) Insert 5, 6, 13, 14, 21 in that order and show the keys and PSLs after each insertion. (b) How many probes does an unsuccessful search for 29 take, and how many would it take in the plain linear-probing table holding the same keys? (c) Delete 13 and show the result.
Hint
21’s walk wraps from slot 7 to slot 0, and the entry it evicts keeps walking.
Solution
(a) Writing each slot as key(PSL):
| Insert | Home | Result (slots 0 to 7) | What happened |
|---|---|---|---|
| 5 | 5 | . . . . . 5(0) . . | empty home slot |
| 6 | 6 | . . . . . 5(0) 6(0) . | empty home slot |
| 13 | 5 | . . . . . 5(0) 13(1) 6(1) | at slot 6, 13 has distance 1 and 6 has PSL 0, so 13 takes it; 6 moves to slot 7 |
| 14 | 6 | 14(2) . . . . 5(0) 13(1) 6(1) | slots 6 and 7 hold PSL 1 against 14’s 0 and 1; wraps to slot 0 |
| 21 | 5 | 14(2) 6(3) . . . 5(0) 13(1) 21(2) | at slot 7, 21 has distance 2 and 6 has PSL 1: swap. 6 continues at distance 2, cannot take slot 0 (14 has PSL 2), lands in slot 1 |
(b) 29 has home 5. It sees 5(0) at distance 0, 13(1) at distance 1, 21(2) at distance 2, then 14(2) at slot 0 at distance 3. Since 2 < 3, the search stops: 4 probes. Plain linear probing puts the same keys at 14 21 . . . 5 6 13, and the search scans slots 5, 6, 7, 0, 1 and stops at the empty slot 2: 6 probes.
(c) 13 is in slot 6. Backward shift moves 21 to slot 6 (PSL 1), 14 to slot 7 (PSL 1) and 6 to slot 0 (PSL 2), then stops at the empty slot 2 and clears slot 1:
slot: 0 1 2 3 4 5 6 7
6(2) . . . . 5(0) 21(1) 14(1)
No tombstone was written, and every entry that moved is now one slot closer to home.
12.9 ★★★ Robin Hood cannot change the average. Insert the same keys in the same order into a plain linear-probing table and a Robin Hood table of the same size, with no deletions or resizes. Prove that the sum of all PSLs is the same in both, so the average successful lookup costs the same. What does Robin Hood change, then?
Hint
First show both tables have the same set of occupied slots. Then, during a Robin Hood insertion, track the quantity T = (sum of PSLs of the entries in the table) + (current distance of the entry being carried).
Solution
Same occupied slots. By induction on insertions. Suppose both tables have the same occupied set and a key with home h arrives. Linear probing puts it in e, the first empty slot at or after h. Robin Hood’s walk also starts at h and moves forward one slot at a time; swaps exchange which entry occupies a slot but never empty or fill one, so the walk ends by filling the same slot e. The occupied sets stay equal.
Same total. Linear probing adds one entry with PSL (e − h) mod m, so the total grows by (e − h) mod m. For Robin Hood, track T as in the hint. At the start of the walk T is the old total plus 0. A step to the next slot adds 1 to the carried entry’s distance, so T grows by 1. A swap puts the carried entry, with distance d, into the slot and picks up the occupant with its PSL d′: the table’s sum changes by d − d′ and the carried distance by d′ − d, so T is unchanged. The walk takes (e − h) mod m steps, and when it ends the carried entry is placed at e, so the new total is the old total plus (e − h) mod m, exactly as for linear probing.
(Without wraparound there is a one-line version: the total PSL is Σ(position − home) = Σ positions − Σ homes. The first sum depends only on the occupied set and the second only on the keys.)
So the mean PSL, and the average successful-search cost of 1 + mean PSL, is identical. Robin Hood only redistributes the total: it takes slots from entries near home and gives them to entries far from home, which shrinks the variance and the maximum, as the table in Section 12.5 shows. Separately, its invariant lets unsuccessful searches stop early, so those do get cheaper on average.
12.10 ★★★ Matching without SIMD. Go’s map on architectures other than amd64, and hashbrown on targets without SSE2, use groups of 8 control bytes packed into one 64-bit integer and find matches with ordinary arithmetic. With LSB = 0x0101010101010101 and MSB = 0x8080808080808080, the match is:
x = word XOR (h2 × LSB)
match = (x − LSB) AND (NOT x) AND MSB
(a) Implement it in Python (byte j of the group is bits 8j to 8j + 7) and run it on the group 0x15 0x80 0x3A 0x15 0xFE 0x61 0x80 0x0C with H2 = 0x15. (b) Show that a byte equal to h2 is always flagged, and that an empty or deleted byte (top bit set) never is. (c) The test can flag a byte that does not equal h2. Find an example, say exactly when it happens, and explain why it is harmless.
Hint
XOR turns matching bytes into 0x00. Think about what subtracting 0x01 does to a 0x00 byte, and what the resulting borrow does to the byte above it.
Solution
(a)
LSB = 0x0101010101010101 # 0x01 in every byte
MSB = 0x8080808080808080 # 0x80 in every byte
MASK64 = (1 << 64) - 1
def match_h2(word, h2):
"""0x80 in every byte of word that (probably) equals h2."""
x = word ^ (h2 * LSB) # bytes equal to h2 become 0x00
return (x - LSB) & ~x & MSB & MASK64
group = bytes([0x15, 0x80, 0x3A, 0x15, 0xFE, 0x61, 0x80, 0x0C])
word = int.from_bytes(group, "little")
assert match_h2(word, 0x15) == 0x80000080 # bytes 0 and 3
fp = int.from_bytes(bytes([0x15, 0x14] + [0x80] * 6), "little")
assert match_h2(fp, 0x15) == 0x8080 # byte 1 is a false positive
(b) Take one byte b of x, ignoring borrows for now. If b = 0x00 (the control byte equals h2), then b − 1 = 0xFF with the top bit set, and NOT b = 0xFF also has it set, so the byte is flagged. A borrow coming in from below only makes b − 1 smaller, and 0x00 minus 1 or 2 still has the top bit set, so a true match is never missed. If the control byte is empty or deleted, its top bit is 1 and h2’s is 0, so b has its top bit set and NOT b has it clear: the AND with NOT x removes it whatever the subtraction produced. Special bytes are never reported.
(c) The subtraction borrows across bytes. A matching byte (b = 0x00) borrows from the byte above it, which therefore has 2 subtracted instead of 1. If that byte is b = 0x01, then 0x01 − 2 = 0xFF (top bit set) and NOT 0x01 = 0xFE (top bit set), so it is flagged. That happens exactly when a full control byte equals h2 XOR 0x01 and sits directly above a true match (or above another such byte in a chain). In the example, byte 1 holds 0x14 = 0x15 XOR 0x01 just above the 0x15 in byte 0. It is harmless because every flagged slot has its key compared before anything is returned: a false positive costs one extra comparison and never a wrong answer, and by (b) it can never be an empty or deleted slot. Implementations accept it because the exact version needs more instructions on every probe.
Where this connects
- Chapter 14: Probabilistic Data Structures. Trading exactness for a 10-100x memory reduction
- Chapter 18: Concurrent Data Structures. What it takes to make a hash table concurrent
Chapter 13: String Data Structures
Strings break the assumptions the rest of this book runs on. A comparison is no longer O(1). Comparing two strings costs up to their length. And the queries people actually want are different in kind: not “is this key present” but “which keys start with this”, “where does this pattern occur”, “what is the longest repeated section”. Hash tables answer none of those, because hashing destroys exactly the structure the questions are about.
The structures here exploit the one property strings have that opaque keys don’t: shared prefixes. The first half of the chapter is about ways of storing a set of strings so that common prefixes are stored once. The rest covers the other side of string work: finding one pattern in a text that streams past (Section 13.5), many patterns at once (Section 13.6), and holding a string that is being edited (Section 13.7).
13.1 Tries (Prefix Trees)
A trie stores strings by their prefixes. Each edge carries a character, and a string is a path from the root:
Trie for {"cat", "car", "card", "do", "dog", "done"}:
root
│
├── c
│ └── a
│ ├── t ● "cat"
│ └── r ● "car"
│ └── d ● "card"
│
└── d
└── o ● "do"
├── g ● "dog"
└── n
└── e ● "done"
● marks a node where a stored word ends.
The end-of-word marks matter more than they look. car and card both terminate, and car’s marker sits on an internal node, so “is this node a leaf” is not the same question as “does a word end here”. A trie that conflates the two cannot store a word that is a prefix of another word, which is a common bug.
class TrieNode:
__slots__ = ("children", "is_word")
def __init__(self):
self.children = {} # char -> TrieNode
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word): # O(L)
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_word = True
def search(self, word): # O(L)
node = self._walk(word)
return node is not None and node.is_word
def starts_with(self, prefix): # O(P)
return self._walk(prefix) is not None
def with_prefix(self, prefix): # O(P + output)
"""Every stored word beginning with `prefix`. The autocomplete query."""
node = self._walk(prefix)
if node is None:
return
stack = [(node, prefix)]
while stack:
n, s = stack.pop()
if n.is_word:
yield s
for ch, child in n.children.items():
stack.append((child, s + ch))
def _walk(self, s):
node = self.root
for ch in s:
node = node.children.get(ch)
if node is None:
return None
return node
The complexity is the selling point. Lookup is O(L) in the length of the query, completely independent of how many strings are stored. A trie holding ten strings and a trie holding ten million answer a 12-character lookup in the same time. No hash table can promise that, because hashing the key is already O(L) and then collisions depend on n.
| Operation | Trie | Hash set | Balanced BST |
|---|---|---|---|
| Insert | O(L) | O(L) average | O(L log n) |
| Search | O(L) | O(L) average | O(L log n) |
| Prefix query | O(P + output) | Impossible | O(L log n + output) |
| Sorted iteration | O(total chars) | Impossible | O(n) |
| Worst-case lookup | O(L) guaranteed | O(nL) | O(L log n) |
Note the BST column: string comparison is O(L), so a BST of strings is O(L log n), not O(log n). A detail that reference tables routinely get wrong.
Space is the problem. A node with a 256-entry array per character costs 2KB per node before storing anything. For a dictionary of English words that is wildly wasteful, since most nodes have one or two children. The mitigations, in increasing order of sophistication: a hash map per node (what the code above does. Flexible, one indirection), a sorted array of children (compact, binary search), a 256-bit bitmap plus a packed child array (succinct, the approach in Chapter 24), or compressing the paths outright, which is the next section.
13.2 Radix Trees (Compressed Tries)
Compress any chain of single-child nodes into one edge holding a whole substring:
Radix tree, same words:
root
│
├── "ca"
│ ├── "t" ● "cat"
│ └── "r" ● "car"
│ └── "d" ● "card"
│
└── "do" ● "do"
├── "g" ● "dog"
└── "ne" ● "done"
The chain c→a became one edge "ca".
The guarantee this buys: every internal node either ends a word or has at least two children, so a radix tree over n strings has at most n−1 branching nodes regardless of how long the strings are. Space becomes proportional to the number of strings, not the number of characters. For sparse key sets (long keys with little overlap, like URLs or file paths) the saving is enormous.
PATRICIA tries take it further by storing, at each node, only the bit position that distinguishes the subtrees, skipping the intervening bits entirely. A lookup descends on those bit tests alone and performs exactly one full key comparison at the end. This makes them ideal for fixed-width binary keys, which is why they index IP routing tables. An IP lookup is a longest-prefix match over 32 or 128 bits, and the Linux kernel’s routing table (fib_trie) is a PATRICIA variant.
Adaptive Radix Trees (ART) are the modern refinement: node size adapts to the number of children (4, 16, 48, or 256 slots), so sparse and dense regions each get an appropriate layout. ART is competitive with hash tables on lookups while preserving ordering, and is used in HyPer, DuckDB, and several key-value stores.
13.3 Suffix Trees
The structures so far index a set of strings. A suffix tree indexes one string, by all of its suffixes, which is what makes arbitrary substring search possible, because every substring is a prefix of some suffix.
The terminal $ (a character not otherwise in the alphabet) guarantees no suffix is a prefix of another, so every suffix ends at a leaf:
Suffix tree for "banana$": a compressed trie of all 7 suffixes.
Leaf labels are the starting positions of each suffix.
root
├── "$" → 6
├── "a"
│ ├── "$" → 5
│ └── "na"
│ ├── "$" → 3
│ └── "na$" → 1
├── "banana$" → 0
└── "na"
├── "$" → 4
└── "na$" → 2
Read a path from the root and you have a substring of “banana”. The node reached by “ana” has two leaves below it (3 and 1), which says immediately that “ana” occurs twice, at positions 3 and 1. That is the general pattern: internal nodes correspond to repeated substrings, and the number of leaves below a node is the number of occurrences.
This is why so many string problems collapse to tree traversals:
| Problem | Solution on a suffix tree | Time |
|---|---|---|
| Does pattern P occur? | Walk P from the root | O(m) |
| How many times? | Count leaves below that node | O(m + occ) |
| Longest repeated substring | Deepest internal node | O(n) |
| Longest common substring of A and B | Build over A#B$; deepest node with leaves from both | O(n) |
| Longest palindromic substring | Suffix tree of A#reverse(A)$ + LCA queries | O(n) |
Ukkonen’s 1995 algorithm builds the tree in O(n) for a constant alphabet: online, one character at a time. It is genuinely difficult to implement correctly; the suffix links and the “active point” bookkeeping are notorious.
That difficulty, plus the memory cost, is why suffix trees are less used than their power suggests. A suffix tree needs roughly 20 bytes per character in a practical implementation. Indexing a 3-billion-character genome would take 60GB. The next section is the response to that.
13.4 Suffix Arrays
A suffix array is just the sorted list of suffix starting positions: the same information as a suffix tree’s leaf order, in a flat integer array:
String: "banana$"
Suffixes: 0:"banana$" 1:"anana$" 2:"nana$" 3:"ana$"
4:"na$" 5:"a$" 6:"$"
Sorted lexicographically:
rank 0: "$" → position 6
rank 1: "a$" → position 5
rank 2: "ana$" → position 3
rank 3: "anana$" → position 1
rank 4: "banana$" → position 0
rank 5: "na$" → position 4
rank 6: "nana$" → position 2
Suffix array: [6, 5, 3, 1, 0, 4, 2]
Four bytes per character instead of twenty. Same queries, far better cache behavior, because a binary search over a contiguous integer array is about as friendly to hardware as a search gets.
The LCP array stores the longest common prefix between each suffix and the one before it in sorted order, with LCP[0] = 0 by convention:
rank: 0 1 2 3 4 5 6
suffix "$" "a$" "ana$" "anana$" "banana$" "na$" "nana$"
LCP: 0 0 1 3 0 0 2
↑ ↑ ↑ ↑
"$" vs "a$" vs "ana$" vs "na$" vs
"a$" "ana$" "anana$" "nana$"
share share share "ana" share "na"
nothing "a"
Kasai’s algorithm computes the LCP array in O(n) once the suffix array is known. Together, the suffix array and LCP array carry all the information in a suffix tree: the LCP array encodes the tree’s internal node structure implicitly, so any suffix-tree algorithm can be rewritten to use them.
Construction is a solved problem: SA-IS (Nong, Zhang, Chan, 2009) builds a suffix array in O(n) worst case, is straightforward compared to Ukkonen’s algorithm, and is fast in practice. The simpler O(n log n) doubling approach (sort by first character, then by first 2, then 4, then 8) is what most people implement in contests and is usually fast enough.
Searching with a plain suffix array is O(m log n): binary search, comparing up to m characters at each of log n steps. With the LCP array and a little extra bookkeeping this drops to O(m + log n).
Suffix arrays are the practical default. The FM-index goes one step further, compressing the suffix array to the text’s own entropy while keeping it searchable, which is how BWA and Bowtie fit a human genome index in a few gigabytes.
13.5 Single-Pattern Matching: Prefix Function, Z-Array, Rolling Hash
Sections 13.3 and 13.4 index the text. The opposite case is just as common: one pattern P of length m, one text T of length n that is read once (a log line, a network packet, a file being scanned), and no index worth building. The naive method tries every alignment and compares up to m characters at each, which is O(nm) in the worst case. P = aaaab against T = aaaa…a reads four as at every one of the n alignments before failing.
The three structures below are built from the pattern (or from P and T together) in linear time and remove that worst case. Each is an array of integers, or a single number, that summarizes how the string overlaps itself.
The prefix function (KMP’s failure function)
A border of a string is a proper prefix that is also a suffix: abab has the borders ab and the empty string. The prefix function stores, for every prefix of P, the length of its longest border:
π[i] = length of the longest proper prefix of P[0..i] that is also a suffix of P[0..i]
P = a b a b a c a
i = 0 1 2 3 4 5 6
π = 0 0 1 2 3 0 1
π[4] = 3 because ababa begins and ends with aba. π[5] = 0 because no prefix of ababac ends in c.
Why this is the right thing to store: suppose the last k characters of the text match P[0..k), and the next text character c is not P[k]. The alignment that just failed is dead, but a later alignment can only still succeed if the part of it already read is both a suffix of the matched text P[0..k) and a prefix of P. That is a border of P[0..k). The longest one has length π[k−1]; if c does not extend that either, the next candidate is the longest border of the border, π[π[k−1]−1], and so on. A border of a border is itself a border, and this chain visits every border of P[0..k) from longest to shortest, so no possible alignment is skipped. The text pointer never moves backwards. Computing π is the same procedure run on P against itself:
def prefix_function(p):
"""pi[i] = length of the longest proper prefix of p[:i+1] that is also its suffix."""
pi = [0] * len(p)
k = 0 # length of the current border
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1] # fall back to the next shorter border
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def kmp_search(text, pattern):
"""Start positions of every occurrence of pattern in text. O(n + m) worst case."""
pi = prefix_function(pattern)
m, k, hits = len(pattern), 0, []
for i, ch in enumerate(text):
while k > 0 and ch != pattern[k]:
k = pi[k - 1]
if ch == pattern[k]:
k += 1
if k == m:
hits.append(i - m + 1)
k = pi[k - 1] # keep going: occurrences may overlap
return hits
assert prefix_function("ababaca") == [0, 0, 1, 2, 3, 0, 1]
assert kmp_search("abababacab", "ababaca") == [2]
assert kmp_search("aaaa", "aa") == [0, 1, 2]
A trace of that search, with k the number of pattern characters currently matched:
| i | text[i] | k before | Fallbacks | k after |
|---|---|---|---|---|
| 0–4 | a b a b a | 0 → 5 | 5 | |
| 5 | b | 5 | needs c; k = π[4] = 3, and P[3] = b matches | 4 |
| 6 | a | 4 | 5 | |
| 7 | c | 5 | 6 | |
| 8 | a | 6 | 7 = m: match at 2, then k = π[6] = 1 | |
| 9 | b | 1 | 2 |
At i = 5 the naive method would restart at alignment 1 and re-read four characters. KMP keeps the three it knows are right (aba, the longest border of ababa) and continues.
Complexity. Building π is O(m) and searching is O(n), both worst case. The argument is amortized over the run: k grows by at most 1 per character, each fallback shrinks it by at least 1, and it never goes below 0, so the total number of fallbacks is at most the total number of increments, n. The bound is on the total, not per character: with P = aaaab and text aaaac, the single c triggers four fallbacks (k = 4, 3, 2, 1, 0). That matters only for hard real-time stream processing, and Knuth’s refinement of the failure function, which skips borders followed by the same character that just failed, cuts the per-character delay to O(log m). Memory is m integers, and the text is consumed one character at a time, so KMP works on a stream that is never stored.
A side result used constantly: the smallest period of P (the least p with P[i] = P[i + p] for every valid i) is m − π[m−1]. For abababab, π[7] = 6, so the period is 2.
The connection to Aho–Corasick. Build the Aho–Corasick automaton of Section 13.6 from a single pattern. The trie is a path of m + 1 nodes, and the failure link of the node at depth q points to the node at depth π[q−1]. The construction is the same loop, too: Aho–Corasick computes failure links in breadth-first order by following the parent’s failure link until it reaches a node with an outgoing edge labelled c, which is while k > 0 and p[i] != p[k]: k = pi[k - 1] with “has a child labelled c” in place of p[k] == c. Aho–Corasick is the prefix function computed over a trie instead of a string.
The Z-array
The Z-array measures self-overlap from the other direction: Z[i] is the length of the longest common prefix of S and S[i:], with Z[0] = n by convention.
S = a a b x a a b
i = 0 1 2 3 4 5 6
Z = 7 1 0 0 3 1 0
Z[4] = 3 because S[4:] = aab matches the first three characters of S, and the string ends there.
Computing every Z[i] by direct comparison is O(n²). The linear algorithm keeps the Z-box [l, r): among the matches found so far, the one reaching furthest right, so S[l:r] = S[0:r−l]. For i inside the box, S[i:r] is a copy of S[i−l : r−l], whose Z value is already known, so Z[i] ≥ min(r − i, Z[i − l]) without looking at a character. Only characters at or beyond r are compared, and each successful comparison moves r right.
def z_array(s):
"""z[i] = length of the longest common prefix of s and s[i:]; z[0] = len(s)."""
n = len(s)
z = [0] * n
if n:
z[0] = n
l = r = 0 # s[l:r] matches s[0:r-l], r maximal so far
for i in range(1, n):
if i < r:
z[i] = min(r - i, z[i - l]) # reuse what the box already tells us
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1 # extend by direct comparison
if i + z[i] > r:
l, r = i, i + z[i]
return z
def z_search(text, pattern, sep="\0"):
"""sep must occur in neither string. O(n + m) worst case."""
m = len(pattern)
z = z_array(pattern + sep + text)
return [i - m - 1 for i in range(m + 1, len(z)) if z[i] >= m]
assert z_array("aabxaab") == [7, 1, 0, 0, 3, 1, 0]
assert z_search("abababacab", "ababaca") == [2]
r only increases and never exceeds n, so the comparisons that extend a match total at most n, and each i adds at most one failed comparison: O(n) worst case. To search, compute Z over P + separator + T; the separator caps every value at m, and the occurrences are exactly the positions in the T part where Z reaches m.
The prefix function and the Z-array carry the same information (each can be converted to the other in O(n)), and both give O(n + m) matching. The practical differences: KMP is online with O(m) memory, while the Z approach as written holds all of P + T. Z values are often easier to reason with, though, because each one directly answers “how far does the text at i agree with the pattern”. Matching with at most one mismatch, for example, is two Z computations: one forward over P + sep + T, one over the reversed strings, and an alignment qualifies when the forward and backward agreements together cover at least m − 1 characters.
Rolling hashes and Rabin–Karp
The third approach turns each length-m window of the text into a number and compares numbers. The polynomial hash of a string s of length m, for a prime p and a base b in [0, p), is
H(s) = (s[0]·b^(m-1) + s[1]·b^(m-2) + ... + s[m-1]) mod p
What makes it useful is that the next window’s hash follows from the current one in O(1): remove the leading character’s term, shift everything by one power of b, add the new character.
H(T[i+1 .. i+m]) = ((H(T[i .. i+m-1]) - T[i]·b^(m-1))·b + T[i+m]) mod p
With small numbers (digits as their own values, b = 10, p = 13), searching for P = 14 in T = 3141592: H(P) = 14 mod 13 = 1. The windows hash to 31 → 5, then (5 − 3·10)·10 + 4 = −246 ≡ 1, then 2, 2, 7, and for 92, (7 − 5·10)·10 + 2 = −428 ≡ 1. Two windows hash to 1: 14 at position 1 is a real match, and 92 at position 5 is a spurious hit, two different strings with the same hash. Rabin–Karp therefore checks the characters whenever the hashes agree:
import random
MOD = (1 << 61) - 1 # a Mersenne prime, about 2.3 * 10**18
def rabin_karp(text, pattern, base=None):
"""Start positions of pattern in text. Expected O(n + m) when matches are few."""
n, m = len(text), len(pattern)
if m == 0 or m > n:
return []
if base is None:
base = random.randrange(256, MOD - 1) # drawn after the input is fixed
high = pow(base, m - 1, MOD) # weight of the character leaving the window
hp = ht = 0
for i in range(m):
hp = (hp * base + ord(pattern[i])) % MOD
ht = (ht * base + ord(text[i])) % MOD
hits = []
for i in range(n - m + 1):
if ht == hp and text[i:i + m] == pattern: # verify, so never a false match
hits.append(i)
if i + m < n: # roll: drop text[i], append text[i+m]
ht = ((ht - ord(text[i]) * high) * base + ord(text[i + m])) % MOD
return hits
assert rabin_karp("abababacab", "ababaca") == [2]
assert rabin_karp("3141592", "14") == [1]
All three functions in this section were checked against a brute-force search on thousands of random texts over small alphabets, where overlaps and near-misses are most frequent.
How likely is a collision? Fix two different strings x and y of length m before the base is chosen. H(x) − H(y) = Σ (x[i] − y[i])·b^(m−1−i) mod p is a nonzero polynomial in b of degree at most m − 1. Over the integers mod a prime, which form a field, such a polynomial has at most m − 1 roots. So for b drawn uniformly at random, Pr[H(x) = H(y)] ≤ (m − 1)/p. Summed over the n − m + 1 windows, the expected number of spurious hits is at most about nm/p. With p = 2⁶¹ − 1, n = 10⁹ and m = 1,000, that is about 4 × 10⁻⁷ for the entire scan. With a 30-bit prime such as 10⁹ + 7, the same scan expects about 1,000 spurious hits, each costing an m-character check.
There are two ways to use the hash:
- Las Vegas (the code above): verify every hash hit. Never wrong, expected O(n + m + m·occ) time. Its worst case is a text full of real matches,
aⁿ againstaᵐ, where verification costs O(nm). KMP reports the same matches in O(n). - Monte Carlo: trust the hash and skip verification. O(n + m) worst case, wrong with probability at most about nm/p.
Why the base must be random. The bound above is a probability over the choice of b, for inputs fixed before b is drawn. With b and p hard-coded, nothing is random: two given strings either collide or they don’t, and anyone who can read the code can pick inputs that do. This is the hash-flooding problem from Section 12.1 in another form. The most common way to get this wrong is to drop the modulus and let 64-bit arithmetic overflow, which computes the hash mod 2⁶⁴. 2⁶⁴ is not prime, the root-counting argument no longer applies, and there are strings of length 1,024 that collide for every odd base (Exercise 13.9). An even base is worse: b⁶⁴ ≡ 0 mod 2⁶⁴, so only the last 64 characters affect the hash at all.
Double hashing runs two hashes with independently drawn bases (and usually two different primes p₁, p₂) and treats a hit as real only when both agree. For a fixed pair of strings the collision probability becomes at most (m/p₁)·(m/p₂), so two primes near 10⁹ behave like one modulus near 10¹⁸. This is the standard technique in languages without cheap 128-bit multiplication. (It is unrelated to double hashing as an open-addressing probe sequence in Section 12.3.)
Beyond one pattern. A rolling hash turns any substring into a number in O(1): with prefix hashes h[i] = H(S[0..i)), the hash of S[l..r) is h[r] − h[l]·b^(r−l) mod p, so after O(n) preprocessing any two substrings can be compared for equality in O(1) with small error probability. That one primitive gives longest repeated substring by binary search on the length, matching many patterns of the same length through a hash set of their hashes, and two-dimensional matching. In shipped systems, rsync finds moved blocks with a rolling checksum (a sum-based cousin of the polynomial hash) backed by a strong hash; LBFS and backup tools such as restic cut files into content-defined chunks at positions chosen by a rolling Rabin fingerprint (polynomial hashing over GF(2) rather than mod a prime), so an insertion only changes nearby chunks; and MOSS detects plagiarism by “winnowing” the hashes of every k-gram.
| Prefix function (KMP) | Z-array | Rolling hash (Rabin–Karp) | |
|---|---|---|---|
| Extra space | m integers | n + m integers | O(1) plus the current window |
| Matching time | O(n + m) worst case | O(n + m) worst case | O(n + m) expected with few matches (Las Vegas); O(n + m) worst case if unverified (Monte Carlo) |
| Can report a false match | No | No | Only if unverified, probability ≤ about nm/p |
| Reads the text as a stream | Yes | Not as written | Yes |
| Generalizes to | Many patterns (Aho–Corasick) | Matching with one mismatch | O(1) substring equality, many equal-length patterns, 2D |
13.6 Aho–Corasick: Searching for Many Patterns at Once
Everything so far searches for one pattern. The common real problem is the opposite: given ten thousand patterns (a spam word list, a malware signature set, a set of banned URLs) find every occurrence of any of them in one pass over the text.
Running a single-pattern search once per pattern is O(k·n) for k patterns. Aho–Corasick does it in O(n + total pattern length + occurrences), independent of k.
The construction is a trie of all patterns, augmented with failure links. A failure link from a node points to the node representing the longest proper suffix of the current match that is also a prefix of some pattern: exactly the generalization of the KMP failure function (the prefix function of Section 13.5) to a set of patterns.
Patterns: {"he", "she", "his", "hers"}
root
/ \
h s
/ \ \
e● i h
| \ \
r s● e● ● = a pattern ends here
|
s●
Failure link: the node for "she" fails to the node for "he",
because "he" is the longest suffix of "she" that is also a prefix
of a pattern. So on matching "she" you also report "he" for free.
When a character doesn’t match, follow the failure link instead of restarting. The automaton never re-reads a character of the text, which is where the linear bound comes from. This is the algorithm behind grep -F, most intrusion detection systems, and content filters.
13.7 Text Editor Buffers: Gap Buffer, Rope, Piece Table
Everything so far treats the string as fixed. A text editor holds one string that changes constantly: a stream of small insertions and deletions, interleaved with reads by position (drawing the screen), by line number (“go to line 50,000”), and undo. Files can be hundreds of megabytes (logs, generated JSON). The obvious representation, one contiguous array of characters, costs O(n − i) to insert at position i because everything after i shifts. Typing near the top of a 100 MB file would move 100 MB per keystroke.
Three access patterns decide which structure fits: edits at the cursor (ordinary typing, with strong locality), edits at scattered positions (multiple cursors, search-and-replace, a formatter, a collaborator’s edits arriving over the network), and reads by offset or by line.
The gap buffer
Keep one array, but leave the free space in the middle, at the cursor, instead of at the end. The text is everything outside the gap: buf[:gap_start] + buf[gap_end:], and the cursor is gap_start. Typing writes into the gap; moving the cursor moves the gap by copying the characters it passes over to the other side.
GapBuffer("hello world"): capacity 22, cursor at the end, _ marks the gap
h e l l o ␣ w o r l d _ _ _ _ _ _ _ _ _ _ _ gap = [11, 22)
move_to(5): the 6 characters " world" are copied to the far end of the array
h e l l o _ _ _ _ _ _ _ _ _ _ _ ␣ w o r l d gap = [5, 16)
insert(","): one write into the gap, nothing shifts
h e l l o , _ _ _ _ _ _ _ _ _ _ ␣ w o r l d gap = [6, 16)
class GapBuffer:
"""Text = buf[:gap_start] + buf[gap_end:]. The cursor sits at gap_start."""
def __init__(self, text="", capacity=16):
cap = max(capacity, 2 * len(text))
self.buf = list(text) + [None] * (cap - len(text))
self.gap_start, self.gap_end = len(text), cap
def __len__(self):
return len(self.buf) - (self.gap_end - self.gap_start)
def __getitem__(self, i): # O(1)
if not 0 <= i < len(self):
raise IndexError(i)
if i < self.gap_start:
return self.buf[i]
return self.buf[i + self.gap_end - self.gap_start]
def move_to(self, pos): # O(|pos - cursor|)
if not 0 <= pos <= len(self):
raise IndexError(pos)
while self.gap_start > pos: # carry characters left of the gap to its right
self.gap_start -= 1
self.gap_end -= 1
self.buf[self.gap_end] = self.buf[self.gap_start]
while self.gap_start < pos: # carry characters right of the gap to its left
self.buf[self.gap_start] = self.buf[self.gap_end]
self.gap_start += 1
self.gap_end += 1
def insert(self, s): # O(len(s)) amortized, at the cursor
for ch in s:
if self.gap_start == self.gap_end:
self._grow()
self.buf[self.gap_start] = ch
self.gap_start += 1
def delete(self, k=1): # O(1): backspace k characters
self.gap_start = max(0, self.gap_start - k)
def _grow(self): # double the array: O(n), rare
old_cap = len(self.buf)
tail = self.buf[self.gap_end:]
self.buf = self.buf[:self.gap_start] + [None] * old_cap + tail
self.gap_end = self.gap_start + old_cap
def __str__(self):
return "".join(self.buf[:self.gap_start] + self.buf[self.gap_end:])
g = GapBuffer("hello world")
g.move_to(5)
g.insert(",")
assert str(g) == "hello, world" and (g.gap_start, g.gap_end) == (6, 16)
g.delete(1)
assert str(g) == "hello world" and g[6] == "w"
Costs. Insertion at the cursor is O(1) amortized (the gap is refilled by doubling, the same argument as the dynamic array in Section 3.4); backspace is O(1), just widening the gap; indexing is O(1), one comparison and one array read. An edit at an arbitrary position first moves the gap there, O(distance), so O(n) worst case. That is the whole tradeoff: typing produces long runs of edits in one place, so gap moves are rare and short, and the gap buffer has the best constant factors of anything here, because the text is one contiguous array. It degrades when edits alternate between distant positions, which is exactly what multiple cursors and some search-and-replace orders do (Exercise 13.10). Nothing in it helps find line k (you scan for newlines or keep a separate index), and it has no undo of its own: overwritten gap contents are gone, so editors keep a separate log of (position, text inserted or deleted) records. Emacs is the best-known gap-buffer editor; its buffer text is a gap buffer (GPT and GAP_SIZE in its C source), and its undo log is the Lisp-visible buffer-undo-list.
The rope
A rope (Boehm, Atkinson and Plass, 1995) is a balanced binary tree whose leaves hold short strings. The text is the left-to-right concatenation of the leaves, and each internal node stores its weight, the length of its left subtree:
[9] weight = length of the left subtree
/ \
[4] [6]
/ \ / \
"the " "quick" " brown" " fox" text: "the quick brown fox"
index(12): 12 >= 9, go right with 12 - 9 = 3; 3 < 6, go left;
" brown"[3] = 'o'.
The operations are built from two primitives. Concat makes a new root over two ropes: O(1), plus O(log n) to rebalance. Split at position i walks down to i, cuts the leaf there in two, and separates the tree along that root-to-leaf path: O(log n). Insert is split, then two concats; delete is two splits and one concat. On a balanced rope every one of these is O(log n) worst case wherever the edit lands: the cursor gives no advantage, and scattered edits cost no more. Indexing is O(log n) instead of O(1), and sequential reads use an iterator that walks leaves rather than descending from the root per character.
Two extensions make ropes the structure of choice for modern editors:
- Augmented counts. Each node can store, besides the character count, the number of newlines in its subtree. “Offset of line k” and “line containing offset i” then descend the tree in O(log n), the same subtree-summary trick as the weights.
- Persistence. If nodes are never modified in place, an edit creates only the O(log n) nodes on the split paths and shares everything else with the previous version, which is path copying from Chapter 17. An old root is a complete old version, so undo is “keep the root”, and a background thread (syntax highlighting, saving, a language server) can read a consistent snapshot while the user keeps typing.
Production ropes put chunks of tens to about a thousand bytes in each leaf and use a B-tree rather than a binary tree, so the tree is shallow and the per-character work is a copy within one small array. xi-editor’s xi-rope is a B-tree rope, Helix uses the Ropey library, and Zed’s rope is a B+ tree of chunks (its SumTree) whose nodes carry summaries including line counts and UTF-16 lengths; Zed takes a snapshot of a buffer for a background thread by copying the root and incrementing reference counts. The cost is constant factors: more memory per character than an array, and pointer chasing on every access.
The piece table
A piece table never moves or overwrites text. It keeps two buffers: the original buffer, the file exactly as loaded and never modified, and the add buffer, to which every typed character is appended. The document is a sequence of pieces, each a (buffer, start, length) triple naming a span of one buffer; the text is the concatenation of the spans in piece order.
Load the fox jumped, insert quick brown at offset 4, delete the final ed, then type s:
start: [(orig, 0, 14)] "the fox jumped"
insert(4, "quick brown "): split the piece at 4, add a piece for the new text
[(orig, 0, 4), (add, 0, 12), (orig, 4, 10)] "the quick brown fox jumped"
delete(24, 2): split at 24, drop the piece covering "ed"
[(orig, 0, 4), (add, 0, 12), (orig, 4, 8)] "the quick brown fox jump"
insert(24, "s"): [(orig, 0, 4), (add, 0, 12), (orig, 4, 8), (add, 12, 1)]
"the quick brown fox jumps"
class PieceTable:
"""Text = concatenation of pieces; each piece is (buffer, start, length)."""
ORIGINAL, ADD = 0, 1
def __init__(self, text=""):
self.buffers = (text, []) # original is read-only, add is append-only
self.pieces = [(self.ORIGINAL, 0, len(text))] if text else []
self.history = [] # earlier piece lists, for undo
def _split(self, pos):
"""Make pos fall on a piece boundary; return the index of the piece starting there."""
offset = 0
for i, (buf, start, length) in enumerate(self.pieces):
if pos == offset:
return i
if pos < offset + length: # pos is inside this piece: cut it in two
k = pos - offset
self.pieces[i:i + 1] = [(buf, start, k), (buf, start + k, length - k)]
return i + 1
offset += length
if pos == offset:
return len(self.pieces)
raise IndexError(pos)
def insert(self, pos, s): # O(number of pieces)
if not s:
return
self.history.append(list(self.pieces))
add = self.buffers[self.ADD]
i = self._split(pos)
prev = self.pieces[i - 1] if i > 0 else None
if prev and prev[0] == self.ADD and prev[1] + prev[2] == len(add):
self.pieces[i - 1] = (self.ADD, prev[1], prev[2] + len(s)) # typing: extend
else:
self.pieces.insert(i, (self.ADD, len(add), len(s)))
add.extend(s) # text is only ever appended
def delete(self, pos, length): # O(number of pieces)
if length <= 0:
return
self.history.append(list(self.pieces))
i = self._split(pos)
j = self._split(pos + length)
del self.pieces[i:j] # the characters stay in their buffers
def undo(self):
if self.history:
self.pieces = self.history.pop()
def __getitem__(self, i): # O(number of pieces)
for buf, start, length in self.pieces:
if i < length:
return self.buffers[buf][start + i]
i -= length
raise IndexError(i)
def __len__(self):
return sum(length for _, _, length in self.pieces)
def __str__(self):
return "".join("".join(self.buffers[b][s:s + n]) for b, s, n in self.pieces)
pt = PieceTable("the fox jumped")
pt.insert(4, "quick brown ")
pt.delete(24, 2)
pt.insert(24, "s")
assert str(pt) == "the quick brown fox jumps"
assert pt.pieces == [(0, 0, 4), (1, 0, 12), (0, 4, 8), (1, 12, 1)]
pt.undo()
assert str(pt) == "the quick brown fox jump"
pt.undo()
assert str(pt) == "the quick brown fox jumped"
Both classes were tested against a plain Python string on thousands of random edit sequences, including undo for the piece table.
Costs. With k pieces in a list, finding the piece that contains an offset is O(k), and so are insert, delete and indexing. k grows with the number of separate edits, not with the number of characters: each insert adds at most two pieces and each delete at most one net, so k ≤ 2e + 1 after e edits. Ordinary typing adds none, because the prev check extends the piece that ends at the end of the add buffer; editors also cache the cursor’s piece, so typing is O(1) amortized. Loading is O(1) beyond reading the file: the original buffer is the file’s bytes, never copied or split into lines, and can be memory-mapped. Memory is the original file plus every character ever typed (deleted text is never reclaimed while undo can reach it) plus the pieces.
Undo comes free. The buffers only ever grow, so every past version of the document is still fully described by its piece list. Undo restores an earlier list, and the code above simply snapshots the list (O(k) per edit). Real implementations record the few piece-level changes each edit made and invert them, but the principle is the same: no text is ever copied to support undo.
The piece tree. Replacing the list with a balanced search tree of pieces, each node caching the total length (and newline count) of its left subtree, makes locating an offset or a line O(log k). VS Code switched to exactly this in 2018 (release 1.21): a piece table whose pieces live in a red-black tree, with each node storing its left subtree’s length and line-feed count. The old representation, an array of line objects, cost roughly 40 to 60 bytes per line; a 35 MB file of 13.7 million lines took about 600 MB, while the piece tree’s memory after loading is close to the file size.
Comparing the three
n is the document length and k the number of pieces.
| Gap buffer | Rope (balanced) | Piece table (list) | Piece tree | |
|---|---|---|---|---|
| Insert/delete at the cursor | O(1) amortized | O(log n) worst case | O(1) amortized with a cached cursor piece | O(log k) worst case |
| Insert/delete elsewhere | O(n) worst case (gap move) | O(log n) worst case | O(k) | O(log k) worst case |
| Character at offset i | O(1) | O(log n) | O(k) | O(log k) |
| Offset of line j | O(n) scan, unless indexed separately | O(log n) with newline counts | O(n) scan | O(log k) with line-feed counts |
| Undo | Separate edit log | Keep old roots (persistent) | Restore old piece lists; text never destroyed | Same as piece table |
| Memory beyond the text | The gap | Node per chunk | All deleted text, plus pieces | Same, plus tree nodes |
| Used by | Emacs | xi-editor, Zed, Helix (Ropey) | Bravo; Word’s “fast save” format | VS Code |
For one person typing into a file of a few megabytes, all three are instantaneous and the gap buffer is the simplest. The differences appear with large files (load time and memory favour the piece table), with edits scattered across the document (the gap buffer loses), and with concurrency (a persistent rope or piece tree lets other threads read snapshots without locking out the user).
13.8 Choosing a String Structure
| Need | Use | Why |
|---|---|---|
| Autocomplete, prefix queries | Trie or radix tree | O(P) prefix descent |
| Dictionary with tight memory | Radix tree, or succinct trie | Nodes proportional to strings, not characters |
| IP longest-prefix match | PATRICIA / ART | Bit-level tests, ordered |
| Substring search in one fixed text | Suffix array + LCP | Suffix-tree power at 4 bytes per character |
| Same, with minimal memory | FM-index | Compressed to text entropy, still searchable |
| Many patterns, one text | Aho–Corasick | O(n) regardless of pattern count |
| One pattern, one pass, no preprocessing of text | KMP or Boyer–Moore | O(n + m), no index to build |
| Many substring-equality checks on one string | Rolling hash with prefix hashes | O(1) per comparison after O(n) setup, random base |
| A string being edited (an editor buffer) | Gap buffer, rope, or piece table | Section 13.7: by locality of edits, file size, and need for snapshots |
| Exact set membership only, no prefix queries | Hash set | Simpler and faster when you don’t need order |
The decisive question is which side you preprocess. Index the text (suffix array, FM-index) when the text is fixed and queries are many: a genome, a codebase, a document corpus. Index the pattern (KMP, Aho–Corasick) when the text streams past once and the patterns are fixed: a log pipeline, a packet filter.
13.9 Applications
Autocomplete: Trie prefix matching Spell checking: Dictionary lookup IP routing: Longest prefix match DNA sequencing: Pattern matching Search engines: Inverted indexes
In shipped systems: Elasticsearch and Lucene store their term dictionaries as finite-state transducers, a compressed-trie variant that shares suffixes as well as prefixes; the Linux kernel routes packets through fib_trie, a PATRICIA variant; BWA and Bowtie align sequencing reads against an FM-index of the reference genome; grep -F and Snort use Aho–Corasick; Redis implements its stream IDs and cluster key routing over radix trees; and DuckDB and HyPer index with ART. Editors split three ways: Emacs keeps text in a gap buffer, VS Code in a piece tree, and Zed, xi-editor and Helix in ropes; rsync and content-defined chunking in backup tools rest on rolling hashes.
13.10 Historical Context
Tries were described by Axel Thue in 1912 in a paper on repetition-free strings, long before computers existed to store them. René de la Briandais rediscovered them for file searching in 1959, and Edward Fredkin named them in 1960. From retrieval, which is why the original pronunciation is “tree” and why nobody agrees about it.
Donald Morrison published PATRICIA in 1968 (“Practical Algorithm To Retrieve Information Coded In Alphanumeric”), one of the better backronyms in computing.
Peter Weiner gave the first linear-time suffix tree construction in 1973, in a paper Knuth reportedly called “the algorithm of the year.” McCreight simplified it in 1976, and Ukkonen produced the online version in 1995 that most implementations follow.
Udi Manber and Gene Myers introduced suffix arrays in 1990 explicitly as the space-efficient answer to suffix trees, and were candid that they were trading a little query time for a large memory saving: a trade that looks better every year as datasets grow faster than RAM.
Alfred Aho and Margaret Corasick published their multi-pattern algorithm in 1975 while at Bell Labs, where it went straight into fgrep.
James Morris and Vaughan Pratt found the linear-time single-pattern algorithm in 1970, and Donald Knuth found it independently; the three published it together in 1977 as the Knuth–Morris–Pratt algorithm. Richard Karp and Michael Rabin published randomized fingerprint matching in 1987. The Z-algorithm reached most students through Dan Gusfield’s 1997 textbook Algorithms on Strings, Trees, and Sequences, which builds linear-time matching on it.
Editor buffers have their own lineage. Bravo (Butler Lampson and Charles Simonyi, Xerox PARC, 1974) used a piece table, and Simonyi went on to lead Microsoft Word. Hans Boehm, Russ Atkinson and Michael Plass described ropes in 1995, drawing on the Cedar environment at PARC, where ropes had been the standard string representation almost from the start. Charles Crowley’s 1998 survey Data Structures for Text Sequences compared gap buffers, piece tables and their relatives and argued for the piece table, and VS Code’s 2018 rewrite to a piece tree brought the idea back into the mainstream.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
13.1 ★ Trie versus radix tree. Insert the words test, team, toast, to into the Trie from Section 13.1. (a) Draw the trie and count its nodes, excluding the root. (b) Draw the radix tree for the same words and count its nodes. (c) Which node is the reason is_word cannot be replaced by “is a leaf”?
Solution
(a) The trie has 10 nodes:
root
└── t
├── e
│ ├── s
│ │ └── t ● "test"
│ └── a
│ └── m ● "team"
└── o ● "to"
└── a
└── s
└── t ● "toast"
(b) Compressing every chain of single-child nodes that do not end a word gives 6 nodes:
root
└── "t"
├── "e"
│ ├── "st" ● "test"
│ └── "am" ● "team"
└── "o" ● "to"
└── "ast" ● "toast"
The chains s→t, a→m and a→s→t each collapse to one edge. Note that "o" cannot be merged with "ast" even though it has a single child: it ends a word, and merging would lose that fact. That is the radix-tree invariant from Section 13.2 (every internal node ends a word or has at least two children). Here the branching nodes are "t" and "e": 2, within the bound of n − 1 = 3.
(c) The o node. It ends to but is internal, because toast continues below it. A trie that treats “leaf” as “end of word” would report to as absent.
13.2 ★ The hidden cost of comparing strings. A colleague stores 1,000,000 URLs (about 80 characters each, most beginning with https://www.) in a balanced BST and argues: “a lookup is about 20 comparisons, a trie lookup is 80 steps, so the BST is four times faster.” What is wrong with the argument, and what is the fair comparison?
Solution
A string comparison is not O(1). Each of the ~20 comparisons (log₂ 10⁶ ≈ 20) scans characters until the first difference, and URLs share long prefixes, so many comparisons read well past the common https://www. before deciding. Near the bottom of the tree, the keys being compared against are the query’s sorted neighbours, which share the longest prefixes of all. The honest bound is the one in the Section 13.1 table: O(L log n), up to 20 × 80 = 1,600 character comparisons, against the trie’s O(L) = 80 node steps.
The fair comparison also cuts the other way, which is worth saying plainly: the BST’s character comparisons are sequential memcmp-style scans over contiguous bytes, while each trie step is a pointer hop to a node that is probably not in cache. Which wins on real hardware depends on how long the shared prefixes are and on memory layout, which is why radix trees and ART (fewer, fatter nodes) are the practical answer rather than a plain trie.
13.3 ★★ Suffix array and LCP by hand. Build the suffix array and LCP array for mississippi$ ($ sorts before every letter). Then use the LCP array to find the longest repeated substring, and say where it occurs.
Hint
Group the suffixes by first letter first: one $, four starting with i, one m, two p, four s. Sort within each group.
Solution
rank pos suffix LCP with previous
0 11 $ 0
1 10 i$ 0
2 7 ippi$ 1 ("i")
3 4 issippi$ 1 ("i")
4 1 ississippi$ 4 ("issi")
5 0 mississippi$ 0
6 9 pi$ 0
7 8 ppi$ 1 ("p")
8 6 sippi$ 0
9 3 sissippi$ 2 ("si")
10 5 ssippi$ 1 ("s")
11 2 ssissippi$ 3 ("ssi")
Suffix array: [11, 10, 7, 4, 1, 0, 9, 8, 6, 3, 5, 2].
LCP array: [0, 0, 1, 1, 4, 0, 0, 1, 0, 2, 1, 3].
A substring repeats exactly when two suffixes share it as a prefix, and the longest common prefix of any two suffixes is achieved by some adjacent pair in sorted order. So the longest repeated substring has length max(LCP) = 4, at rank 4: suffixes 4 and 1 share issi, which occurs at positions 1 and 4 (mississippi[1:5] and mississippi[4:8]; the two occurrences overlap in the i at position 4). This is the suffix-array version of “deepest internal node” from the Section 13.3 table.
13.4 ★★ Count occurrences with a suffix array. Write count_occurrences(text, sa, pattern) that returns how many times pattern occurs in text, using two binary searches over the suffix array. What is its running time?
Hint
All suffixes that start with the pattern are contiguous in the suffix array. Find the first rank whose suffix (cut to m characters) is ≥ the pattern, and the first whose suffix is > it.
Solution
def count_occurrences(text, sa, pattern):
"""Number of times `pattern` occurs in `text`. O(m log n)."""
m = len(pattern)
def first_at_least(target):
# First rank whose suffix, cut to m characters, is >= target.
lo, hi = 0, len(sa)
while lo < hi:
mid = (lo + hi) // 2
if text[sa[mid]:sa[mid] + m] < target:
lo = mid + 1
else:
hi = mid
return lo
def first_greater(target):
# First rank whose suffix, cut to m characters, is > target.
lo, hi = 0, len(sa)
while lo < hi:
mid = (lo + hi) // 2
if text[sa[mid]:sa[mid] + m] <= target:
lo = mid + 1
else:
hi = mid
return lo
return first_greater(pattern) - first_at_least(pattern)
text = "banana$"
sa = [6, 5, 3, 1, 0, 4, 2]
assert count_occurrences(text, sa, "ana") == 2
assert count_occurrences(text, sa, "a") == 3
assert count_occurrences(text, sa, "nab") == 0
Cutting each suffix to m characters is what makes the matches contiguous: every suffix that starts with the pattern compares equal to it, so they form one block, and the two searches find its ends. The ranks in that block are the occurrences, so sa[lo:hi] lists their positions if you need them.
Each binary search takes O(log n) steps, each comparing up to m characters, so the total is O(m log n), independent of how many occurrences there are. (With the LCP array this improves to O(m + log n), as Section 13.4 notes.)
13.5 ★★ Aho–Corasick failure links. For the patterns {"he", "she", "his", "hers"} from Section 13.6, give the failure link of every trie node. Then run the automaton over the text ushers and list every match it reports, with the position where each match starts.
Hint
The failure link of a node spelling s goes to the node for the longest proper suffix of s that is also a path from the root. For each node, try the suffixes from longest to shortest.
Solution
| Node | Proper suffixes tried | Failure link |
|---|---|---|
| h | (empty) | root |
| he | e | root |
| hi | i | root |
| his | is, s | s |
| her | er, r | root |
| hers | ers, rs, s | s |
| s | (empty) | root |
| sh | h | h |
| she | he | he |
Because she fails to he, which ends a pattern, the output set of she is {she, he}.
Running over ushers, following the goto edge when it exists and the failure link otherwise:
| i | char | State after | Reported |
|---|---|---|---|
| 0 | u | root (no edge) | |
| 1 | s | s | |
| 2 | h | sh | |
| 3 | e | she | she at 1, he at 2 |
| 4 | r | she has no r edge; fail to he, take r: her | |
| 5 | s | hers | hers at 2 |
Three matches: she at 1, he at 2, hers at 2. Note step 4: the automaton never moved backwards in the text. It moved from she to her by following one failure link, which is why the total work is linear.
13.6 ★★ Find the bug. This delete for the Section 13.1 Trie is meant to unmark a word and prune nodes that no longer lead to any word. Starting from the chapter’s trie of {"cat", "car", "card", "do", "dog", "done"}, what does the trie contain after delete("car")? After delete("do") (on a fresh copy)? Fix it.
def delete(self, word):
path = [self.root]
for ch in word:
nxt = path[-1].children.get(ch)
if nxt is None:
return False
path.append(nxt)
if not path[-1].is_word:
return False
path[-1].is_word = False
# Prune nodes that no longer lead anywhere.
for i in range(len(word) - 1, -1, -1):
node = path[i + 1]
if node.is_word:
break
del path[i].children[word[i]]
return True
Solution
The pruning loop stops only at a node that ends a word. It never checks whether the node still has children, so it cuts away live subtrees.
delete("car"): thernode is no longer a word, so it is cut, takingcardwith it. Thenais cut (it is not a word), which also removescat. Thencis cut. The trie now holds onlydo,dog,done.delete("do"): theonode is cut along withdoganddonebelow it, thend. The trie holds onlycat,car,card.
The loop happens to work for delete("card"), which is why a quick test can miss the bug.
The fix: a node may be pruned only if it ends no word and has no children.
def delete(self, word):
path = [self.root]
for ch in word:
nxt = path[-1].children.get(ch)
if nxt is None:
return False
path.append(nxt)
if not path[-1].is_word:
return False
path[-1].is_word = False
for i in range(len(word) - 1, -1, -1):
node = path[i + 1]
if node.is_word or node.children:
break
del path[i].children[word[i]]
return True
Once one node survives, every ancestor has at least that child, so stopping (rather than continuing) is correct. With the fix, delete("car") only clears the mark on r, since r still has the child d.
13.7 ★★★ Longest common substring. The Section 13.3 table says the longest common substring of A and B comes from a suffix structure over A#B$. Implement longest_common_substring(a, b) with a suffix array and Kasai’s LCP algorithm. You may build the suffix array naively with sorted. Explain why it is enough to look only at adjacent suffixes, and why Kasai’s algorithm runs in O(n).
Hint
A common substring is a common prefix of a suffix starting in A and a suffix starting in B. For Kasai: if suffix i shares h characters with its sorted predecessor, suffix i + 1 shares at least h − 1 with its own.
Solution
def suffix_array(s):
# Simple O(n^2 log n) construction; fine for an exercise.
return sorted(range(len(s)), key=lambda i: s[i:])
def lcp_kasai(s, sa):
"""LCP[r] = common prefix length of suffixes at ranks r-1 and r. O(n)."""
n = len(s)
rank = [0] * n
for r, i in enumerate(sa):
rank[i] = r
lcp = [0] * n
h = 0
for i in range(n): # suffixes in text order, not rank order
r = rank[i]
if r == 0:
h = 0
continue
j = sa[r - 1] # the suffix just before i in sorted order
while i + h < n and j + h < n and s[i + h] == s[j + h]:
h += 1
lcp[r] = h
if h > 0:
h -= 1 # the next suffix keeps at least h-1
return lcp
def longest_common_substring(a, b):
s = a + "#" + b + "$" # '#' and '$' occur in neither string
sa = suffix_array(s)
lcp = lcp_kasai(s, sa)
boundary = len(a) # position of '#'
best_len, best_pos = 0, 0
for r in range(1, len(s)):
i, j = sa[r - 1], sa[r]
if (i < boundary) != (j < boundary) and lcp[r] > best_len:
best_len, best_pos = lcp[r], sa[r]
return s[best_pos:best_pos + best_len]
assert lcp_kasai("banana$", suffix_array("banana$")) == [0, 0, 1, 3, 0, 0, 2]
assert longest_common_substring("xabcdy", "zzbcdq") == "bcd"
assert longest_common_substring("banana", "ananas") == "anana"
assert longest_common_substring("abc", "xyz") == ""
Why the separators. # occurs once, so no common prefix of two suffixes can run across it; a match found between an A-suffix and a B-suffix lies entirely inside A and inside B.
Why adjacent pairs suffice. The LCP of the suffixes at ranks p < q is the minimum of lcp[p+1..q]. Take the best pair (one from A, one from B) with value L. Walking from rank p to rank q, the side (A or B) must switch at some adjacent pair, and every adjacent LCP in that range is at least L. So some adjacent cross-side pair also achieves L, and scanning adjacent pairs finds it.
Why Kasai is O(n). It visits suffixes in text order. If suffix i matches its predecessor for h characters, then dropping the first character gives suffix i + 1 a string (the predecessor minus its first character) that sorts before it and shares h − 1 characters, so lcp[rank[i+1]] ≥ h − 1. The algorithm therefore starts each comparison at h − 1 instead of 0. h decreases by at most 1 per step, never exceeds n, and so increases at most 2n times in total: the inner while loop does O(n) work over the whole run.
13.8 ★★ Prefix function, Z-array and periods. (a) Compute the prefix function π and the Z-array for aabaaab. (b) Use π to find the smallest period of abcabcab. (c) Explain why m − π[m−1] is always the smallest period of a string of length m.
Solution
(a)
S = a a b a a a b
i = 0 1 2 3 4 5 6
π = 0 1 0 1 2 2 3
Z = 7 1 0 2 3 1 0
Two entries worth checking by hand. π[5] = 2: the prefix aabaaa ends in aa, which is also its start, but aab ≠ aaa, so 2 is the longest border. Computing it, the algorithm had k = 2 (border aa of aabaa), tried to extend with S[5] = a against S[2] = b, fell back to k = π[1] = 1, and extended a to aa. Z[3] = 2: S[3:] = aaab agrees with S = aab… for two characters, then a ≠ b.
(b) π for abcabcab is [0, 0, 0, 1, 2, 3, 4, 5], so the period is 8 − 5 = 3: the string is abc repeated and cut off.
(c) P has period p exactly when P[i] = P[i + p] for every valid i, which says the prefix of length m − p equals the suffix of length m − p, that is, P has a border of length m − p. So periods and borders correspond one to one (p ↔ m − p), and the smallest period corresponds to the longest border, whose length is π[m−1].
def smallest_period(p):
return len(p) - prefix_function(p)[-1]
assert prefix_function("aabaaab") == [0, 1, 0, 1, 2, 2, 3]
assert z_array("aabaaab") == [7, 1, 0, 2, 3, 1, 0]
assert smallest_period("abcabcab") == 3
assert smallest_period("abcd") == 4
(This block uses prefix_function and z_array from Section 13.5.)
13.9 ★★★ Breaking a 64-bit rolling hash. A library computes polynomial hashes with 64-bit unsigned integers and lets them overflow, so all arithmetic is mod 2⁶⁴. The base is random but always odd. Let t₀ = 0, u₀ = 1, and t_{k+1} = t_k u_k, u_{k+1} = u_k t_k (concatenation), so t₁₀ and u₁₀ are 1,024 characters long (t is the Thue–Morse sequence, u its complement). Show that H(t₁₀) = H(u₁₀) for every odd base. Why does the collision bound of Section 13.5 not protect against this?
Hint
Let D_k = H(t_k) − H(u_k), computed over the integers. Write H(t_{k+1}) and H(u_{k+1}) in terms of H(t_k), H(u_k) and b^(2^k), and find a recurrence for D_k. Then count factors of 2.
Solution
For strings x and y with |y| = L, H(xy) = H(x)·b^L + H(y). With L = 2^k:
H(t_{k+1}) = H(t_k)·b^L + H(u_k)
H(u_{k+1}) = H(u_k)·b^L + H(t_k)
D_{k+1} = D_k·b^L − D_k = D_k·(b^(2^k) − 1)
D₀ = 0 − 1 = −1, so D₁₀ = −(b − 1)(b² − 1)(b⁴ − 1)···(b^512 − 1).
Now count factors of 2 for odd b. b − 1 is even: at least 1. b² − 1 = (b − 1)(b + 1) is a product of two consecutive even numbers, so it is divisible by 8: at least 3. Each further factor is b^(2^(i+1)) − 1 = (b^(2^i) − 1)(b^(2^i) + 1), and the second factor is even, so the count grows by at least 1 each time: b^(2^i) − 1 has at least i + 2 factors of 2 for i ≥ 1. The total for i = 0 to 9 is at least 1 + (3 + 4 + ··· + 11) = 1 + 63 = 64. So 2⁶⁴ divides D₁₀, and the two strings collide mod 2⁶⁴ whatever the odd base. (For k = 9 the count is only 1 + 52 = 53, so 512 characters are not enough; that agrees with experiment.)
import random
def h64(s, b):
h = 0
for c in s:
h = (h * b + c) & ((1 << 64) - 1) # what overflowing uint64 arithmetic computes
return h
t, u = [0], [1]
for _ in range(10):
t, u = t + u, u + t
assert len(t) == 1024 and t != u
for _ in range(1000):
b = random.randrange(1, 1 << 64) | 1 # any odd base
assert h64(t, b) == h64(u, b)
The Section 13.5 bound relies on the modulus being prime: over a field, a nonzero polynomial of degree m − 1 has at most m − 1 roots, so few bases are bad. The integers mod 2⁶⁴ are not a field, and a polynomial there can vanish at every odd input. Here D₁₀, viewed as a polynomial in b, is zero for all 2⁶³ odd bases. Choosing the base at random does not help when the modulus admits a polynomial that kills every base. Use a prime modulus such as 2⁶¹ − 1 (and still draw the base at random).
13.10 ★★ Two cursors. A 10 MB file is open in an editor. The user places two cursors, at offsets 1,000 and 9,000,000, and types 20 characters; each keystroke inserts one character at each cursor. Estimate the work for (a) a gap buffer, (b) a piece table using the Section 13.7 code (how many pieces are there at the end?), and (c) a balanced rope.
Solution
(a) Each keystroke inserts at the first cursor, then at the second, and the next keystroke returns to the first. Every visit moves the gap about 9 × 10⁶ characters, twice per keystroke: roughly 20 × 2 × 9 × 10⁶ ≈ 3.6 × 10⁸ character copies for 40 characters typed. With one cursor the same 20 keystrokes cost 20 writes. This is why multi-cursor editing is the gap buffer’s weak spot.
(b) The first insertion splits the original piece at offset 1,000 and adds a piece; the second splits at the far cursor and adds another: 5 pieces. After that, every insertion lands right after an add-buffer piece, but that piece no longer ends at the end of the add buffer, because the other cursor’s character was appended in between. The “extend” shortcut fails, and each insertion adds one piece: 5 + 19 × 2 = 43 pieces. Each operation scans that list, so the work is trivial (a few thousand piece visits), and nothing proportional to the 10 MB file is ever touched. The interleaving shows up in the piece count, not in copying.
pt = PieceTable("x" * 100)
c1, c2 = 10, 90
for _ in range(20):
pt.insert(c1, "a"); c1 += 1; c2 += 1
pt.insert(c2, "b"); c2 += 1
assert len(pt.pieces) == 43
(c) Each insertion is a split and two concatenations, O(log n): with leaves of about 1 KB, a 10 MB rope has about 10⁴ leaves and depth around 14 for a binary tree. 40 insertions cost a few hundred node visits plus copying within small leaves. Like the piece table, the rope does not care how far apart the cursors are.
Where this connects
- Chapter 24: Research-Grade Data Structures. The compressed, succinct versions of these indexes
- Chapter 23: Advanced Competitive Programming Data Structures. Suffix automata and palindromic trees for contests
Volume III: Specialized and Modern Structures
The structures in Volumes I and II assume a single machine, a single thread, exact answers and data that fits in memory. Real systems break every one of those assumptions, and each chapter in this volume relaxes one of them:
| Assumption dropped | Chapter | The idea |
|---|---|---|
| Answers must be exact | 14: Probabilistic Data Structures | Bloom filters, cuckoo filters, HyperLogLog and Count-Min trade a controlled error rate for huge savings in memory |
| Keys are one-dimensional | 15: Spatial and Geometric Data Structures | KD-trees, quadtrees, R-trees and geohashes answer “what is near this point?” |
| Memory access is uniform | 16: External Memory and Cache-Oblivious Structures | Count block transfers instead of operations, and design layouts that are fast at every level of the memory hierarchy |
| Updates destroy the old version | 17: Persistent Data Structures | Path copying, fat nodes and structural sharing keep every version alive cheaply; persistent vectors, queues and finger trees; the basis of functional languages, Git and MVCC |
| One thread at a time | 18: Concurrent Data Structures | Locks, compare-and-swap, the ABA problem, and when lock-free is worth its complexity |
| The textbook is the state of the art | 19: Emerging and Specialized Structures | Succinct structures, learned indexes, vector search, and why some theoretical winners lose in practice |
The last three chapters step back from individual structures to how they are built and used:
| Chapter | The idea |
|---|---|
| 20: Data Structure Design Patterns | Wrappers, iterators, adapters and builders: the recurring ways structures are composed and exposed |
| 21: Algorithm Design Using Data Structures | Divide and conquer, dynamic programming, greedy, backtracking and randomization, and the structure each paradigm leans on |
| 22: Practical Considerations | Choosing structures under real constraints, what your language’s standard library really gives you, profiling, and debugging structural bugs |
Before you start. Volume I is required. Chapter 14 uses hashing from Chapter 12, Chapter 16 builds on B-trees from Chapter 10, and Chapter 17 builds on BSTs from Chapter 7. Otherwise the chapters are independent and can be read in any order; pick the assumption that matters most to your work.
Chapter 14: Probabilistic Data Structures
14.1 The Probabilistic Approach
Sometimes we don’t need exact answers, we need fast, space-efficient approximate answers. Probabilistic data structures trade accuracy for speed and space.
That trade is worth stating precisely, because the amount of accuracy given up is small and the amount of space saved is not. Tracking the unique visitors to a website exactly means storing every visitor ID: 100 million IDs at 16 bytes each is 1.6GB. A HyperLogLog answers the same question with a standard error under 1% using 12 kilobytes: a factor of 130,000. For a dashboard, an error of a percent or two is invisible and 1.6GB is not.
The general shape of every structure in this chapter:
- Hash the input. A good hash turns arbitrary data into uniformly distributed bits, and uniformity is what makes the statistics work.
- Keep a lossy summary of the hashes rather than the data itself. Bits set, maximum leading-zero counts, counter minima.
- Accept a bounded, quantifiable error in exchange for space that grows far more slowly than n, often not at all.
The critical design question for any of them is which direction the error goes, because a one-sided error is usually safe to build on and a two-sided one usually isn’t:
| Structure | Answers | Error direction | Space |
|---|---|---|---|
| Bloom filter | Is x in the set? | False positives only | ~10 bits/element at 1% |
| Counting Bloom | Same, with deletion | False positives only | 4× a Bloom filter |
| Cuckoo filter | Same, with deletion | False positives only | ~20% less than Bloom |
| HyperLogLog | How many distinct? | ±2% both directions | ~12KB, fixed |
| Count-Min Sketch | How often is x? | Overestimates only | O((1/ε)·log(1/δ)) |
| MinHash | How similar are two sets? | ±ε both directions | k hashes per set |
| t-digest | What is the 99th percentile? | Accurate at the tails | ~kilobytes |
“False positives only” is what makes a Bloom filter safe as a cache filter: a false positive costs one wasted lookup, while a false negative would mean losing data. Match the error direction to what a mistake costs you.
14.2 Bloom Filters
A Bloom filter tells you if an element is “probably in the set” or “definitely not.”
Structure:
- m-bit array, all initially 0
- k hash functions
- Insert: Set bits at h₁(x), h₂(x), …, hₖ(x)
- Query: Check if all bits at h₁(x), h₂(x), …, hₖ(x) are 1
Bloom filter with m=12, k=3:
After inserting "apple", "banana":
bits: [1] [0] [1] [0] [0] [1] [0] [1] [0] [1] [0] [1]
0 1 2 3 4 5 6 7 8 9 10 11
Query "grape": bits 2,5,9 all 1 → "Probably present" (false positive!)
Query "mango": bit 3 is 0 → "Definitely not present"
The asymmetry is structural, not a limitation to be engineered away. Insertion only ever sets bits to 1 and never clears them, so a bit that is 0 proves that nothing which hashes there was inserted, “definitely not present” is a proof. A bit that is 1 only proves something set it, which may have been a different element. Hence: no false negatives, ever; false positives at a rate you choose.
class BloomFilter:
def __init__(self, expected_items, false_positive_rate=0.01):
# These two formulas are the whole design.
self.m = math.ceil(-expected_items * math.log(false_positive_rate)
/ (math.log(2) ** 2))
self.k = max(1, round(self.m / expected_items * math.log(2)))
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item):
# Kirsch-Mitzenmacher: two real hashes simulate k of them
# with no loss in the false-positive bound.
h1, h2 = mmh3.hash64(item)
for i in range(self.k):
yield (h1 + i * h2) % self.m
def add(self, item):
for pos in self._positions(item):
self.bits[pos // 8] |= 1 << (pos % 8)
def __contains__(self, item):
return all(self.bits[pos // 8] >> (pos % 8) & 1
for pos in self._positions(item))
False positive probability:
p ≈ (1 - e^(-kn/m))^k
Optimal k = (m/n) × ln 2
The optimal k balances two opposing pressures: more hash functions means more bits must coincidentally align for a false positive, but also more bits set per insertion, filling the array faster. The optimum falls where the array is exactly half full, which is a pleasing result. A Bloom filter operating at its design capacity has half its bits set.
What the formula implies in practice, which is the part worth memorising:
| Target false-positive rate | Bits per element | Hash functions |
|---|---|---|
| 10% | 4.8 | 3 |
| 1% | 9.6 | 7 |
| 0.1% | 14.4 | 10 |
| 0.01% | 19.2 | 13 |
Bits per element is independent of element size. Ten bits per element whether the elements are 8-byte integers or 2KB URLs. That property is why Bloom filters appear wherever the exact set would not fit in memory.
The Kirsch-Mitzenmacher trick in the code above matters for performance: computing seven independent hash functions is expensive, and it turns out two are enough. h1 + i*h2 gives the same asymptotic false-positive rate. Every production implementation does this.
Properties:
- False positives possible
- False negatives impossible
- Cannot delete (Counting Bloom Filter needed)
- Space: ~1.44 × log₂(1/p) bits per element
Two further constraints that catch people. You must size it in advance. A Bloom filter cannot grow, and exceeding the expected count degrades the false-positive rate quickly rather than gracefully. (Scalable Bloom filters chain progressively larger filters to work around this.) And you cannot enumerate the contents: a Bloom filter can answer questions about membership but cannot tell you what it holds.
14.3 Counting Bloom Filters
Store counters instead of bits to enable deletion:
Standard Bloom: [1] [0] [1] [0]
Counting Bloom: [3] [0] [2] [0]
After deleting one "apple" (counters decrement):
Counting Bloom: [2] [0] [1] [0]
Deleting from a standard Bloom filter is impossible because clearing a bit might erase evidence of a different element that happens to share it. Counters fix this by recording how many elements set each position.
The cost is 4× the space, since 4 bits per counter is the usual choice. Four bits caps a counter at 15, and counter overflow is the failure mode to know about: if a counter saturates it must stop incrementing, and thereafter decrements can take it below its true value, which reintroduces false negatives, the one guarantee the structure was supposed to keep. With good hashing, overflow at 4 bits is vanishingly rare, but the analysis assumes it never happens.
Delete only elements you actually inserted. Deleting an element that was never added decrements counters that belong to other elements and silently corrupts the filter.
14.4 Cuckoo Filters
Modern alternative to Bloom filters:
- Better space efficiency
- Supports deletion
- O(1) expected operations
- Uses cuckoo hashing internally
A cuckoo filter stores a short fingerprint of each element (typically 8 to 12 bits) in a cuckoo hash table with two candidate buckets per item. A query checks both buckets for the fingerprint.
The trick that makes it work is partial-key cuckoo hashing. Standard cuckoo hashing needs the original key to relocate an item, and a filter has thrown the key away. Cuckoo filters compute the second bucket as:
bucket2 = bucket1 XOR hash(fingerprint)
Because XOR is its own inverse, either bucket yields the other from the fingerprint alone, so items can be relocated without ever storing the key.
Versus a Bloom filter: about 20% less space at false-positive rates below 3%, genuine deletion support, and better cache behavior (two bucket probes instead of k scattered bit tests). Against: insertion can fail when eviction chains grow too long, so the table must stay below about 95% load, and like counting Bloom filters, deleting something never inserted corrupts it.
Use a cuckoo filter when you need deletion or the lowest false-positive rate per bit. Use a Bloom filter when you need guaranteed insertion and maximum simplicity.
14.5 HyperLogLog
Estimates the number of distinct elements with about 0.81% standard error using 12 KB (derived below):
Idea: Hash each element
If hash starts with k zeros, it's a rare event
The maximum number of leading zeros seen estimates n ≈ 2^R
Register-based improvement:
Split hash into:
- r bits → register index (2^r registers)
- (64-r) bits → count leading zeros
The intuition is worth dwelling on because it is genuinely clever. If hashes are uniformly random bit strings, then roughly half start with 0, a quarter with 00, an eighth with 000. So seeing a hash with 10 leading zeros suggests you have probably looked at around 2¹⁰ distinct values. The rarest event you have observed tells you how many trials you have run.
Using only the single maximum is very noisy: one unlucky hash with 20 leading zeros would suggest a million elements when there were ten. The fix is stochastic averaging: use the first r bits of the hash to pick one of 2^r registers, track the maximum leading-zero count separately in each, and combine them. The registers partition the input, so their estimates are independent, and averaging 16,384 independent estimates cuts the error by √16384 = 128.
The combination uses a harmonic mean, not an arithmetic one, because the harmonic mean suppresses the influence of a single large outlier: precisely the failure mode being defended against:
E = α_m · m² / Σᵢ 2^(−M[i])
m = number of registers, M[i] = max leading zeros in register i
α_m ≈ 0.7213 / (1 + 1.079/m) bias correction constant
Standard error is 1.04/√m. With m = 16,384 registers at 6 bits each (12KB), that is 0.81% error, for a set of any cardinality up to about 2⁶⁴.
The mergeability is the underrated property. The union of two HyperLogLogs is the element-wise maximum of their registers. That means cardinality across a hundred servers can be computed by each server keeping its own sketch and sending 12KB to a coordinator. No coordination, no shuffling of raw data, and the merge is exact. Merging sketches of A and B gives precisely the sketch you’d get from counting A ∪ B directly. This is why every distributed analytics system uses it.
Intersections, however, are not supported. Inclusion-exclusion (|A∩B| = |A| + |B| − |A∪B|) compounds the error of three estimates and produces garbage when the sets differ greatly in size.
14.6 Count-Min Sketch
Estimates frequency of items:
Structure: d rows, w columns
Each row has its own hash function
Add x: increment position h_i(x) in row i
Estimate count of x: min over all rows of count at h_i(x)
Always overestimates (never underestimates)
Where a Bloom filter answers “is x present”, a Count-Min Sketch answers “how many times have I seen x”: in fixed space, for a stream of unbounded length.
d=3 rows, w=6 columns. Adding "apple" three times:
row 0 (h₀): [0] [3] [0] [0] [0] [0] h₀(apple) = 1
row 1 (h₁): [0] [0] [0] [3] [0] [0] h₁(apple) = 3
row 2 (h₂): [0] [0] [3] [0] [0] [0] h₂(apple) = 2
Now add "banana" twice, and suppose h₀(banana) = 1 too:
row 0: [0] [5] [0] [0] [0] [0] ← collision inflates this cell
row 1: [0] [0] [2] [3] [0] [0]
row 2: [0] [0] [3] [2] [0] [0]
estimate("apple") = min(5, 3, 3) = 3 ✓ the collision is discarded
Why the minimum works: every cell for x contains x’s true count plus whatever collided there. Collisions only ever add, so every row gives an overestimate, and the smallest is the least-contaminated. With d rows the chance that every row collided badly falls exponentially.
The error bound is additive relative to the total stream volume: with w = ⌈e/ε⌉ and d = ⌈ln(1/δ)⌉, the estimate exceeds the truth by more than ε·N with probability at most δ, where N is the total count of all items. The practical implication is that heavy hitters are estimated accurately and rare items are not. An item appearing 0.001% of the time may be swamped by noise. That is usually the right bias, since heavy hitters are what these are deployed to find.
Count-Min sketches are linear: adding two sketches element-wise gives the sketch of the combined stream. Same distributed benefit as HyperLogLog.
14.7 Two More Worth Knowing
MinHash estimates the Jaccard similarity of two sets (|A∩B|/|A∪B|)without comparing them. Hash every element of a set and keep the minimum hash. The probability that two sets share the same minimum is exactly their Jaccard similarity, so keeping k independent minima estimates it to within about 1/√k. Combined with locality-sensitive hashing, this is how near-duplicate detection works at web scale: Google used it for deduplicating crawled pages, and it remains standard for plagiarism detection and clustering.
t-digest estimates quantiles (medians, p95, p99) over a stream in a few kilobytes, with the crucial property that accuracy is highest at the extremes. Ordinary sampling gives uniform accuracy, which is backwards for latency monitoring: nobody cares about a precise median, and everyone cares about p99. t-digest is what Prometheus-adjacent tooling, Elasticsearch percentile aggregations, and most latency dashboards use.
14.8 Applications
Bloom Filters:
- Web caching (Akamai, Google Chrome)
- Database optimization (Google Bigtable)
- Bitcoin SPV nodes
- Spell checkers
HyperLogLog:
- Google BigQuery
- Redis (PFADD, PFCOUNT)
- Analytics dashboards
Count-Min Sketch:
- Network traffic analysis
- Database query optimization
The single highest-leverage deployment is in LSM-tree storage engines. A read in an LSM tree may need to check several sorted runs on disk, and most of them will not contain the key. A Bloom filter per run answers “definitely not here” from memory, skipping the disk read entirely. Cassandra, RocksDB, LevelDB, HBase, and Bigtable all do this, and it is the difference between an LSM read being one disk seek and being ten: see Chapter 16.
Also worth noting: Chrome’s Safe Browsing originally shipped a Bloom filter of malicious URLs so the browser could check locally and only consult Google’s servers on a hit, privacy and latency from the same structure. Medium uses them to avoid re-recommending read articles; Ethereum puts one in every block header so light clients can skip blocks with no relevant logs.
14.9 Historical Context
Burton Bloom published his filter in 1970 in a two-page CACM paper about hyphenation dictionaries. The problem was that a full dictionary would not fit in the memory of the machines of the day. The structure sat quietly for two decades until networking and databases at scale made it indispensable.
Philippe Flajolet spent much of his career on this family. Probabilistic counting came in 1985 with Nigel Martin, LogLog in 2003, and HyperLogLog in 2007 with Fusy, Gandouet, and Meunier. Flajolet’s approach: analytic combinatorics, using complex analysis to derive exact constants like that 0.7213. Is why these structures come with precise error bounds rather than empirical rules of thumb. He died in 2011; HyperLogLog now runs in essentially every large-scale analytics system.
Graham Cormode and S. Muthukrishnan introduced the Count-Min Sketch in 2005, and Andrei Broder developed MinHash at AltaVista in 1997 for exactly the problem the web had just created: too many near-identical pages.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
14.1 ★ Size a Bloom filter, then overfill it. You expect 1,000,000 items and want a 1% false-positive rate. (a) Using the formulas in the BloomFilter constructor, compute m (bits) and k. How much memory is that? (b) The estimate was wrong and 2,000,000 items arrive. What is the false-positive rate now? And at 3,000,000?
Solution
(a) m = ⌈−n ln p / (ln 2)²⌉ = ⌈1,000,000 × 4.6052 / 0.48045⌉ = 9,585,059 bits, about 1.2 MB (9.6 bits per item, matching the table). k = round((m/n) ln 2) = round(6.64) = 7.
(b) Plug into p ≈ (1 − e^(−kn/m))^k with m and k fixed:
| Items inserted | kn/m | Fraction of bits set | False-positive rate |
|---|---|---|---|
| 1,000,000 | 0.730 | 0.518 | 1.0% |
| 2,000,000 | 1.461 | 0.768 | 15.7% |
| 3,000,000 | 2.191 | 0.888 | 43.6% |
Doubling the load multiplies the false-positive rate by about 16, and tripling it makes the filter close to useless. This is what “degrades quickly rather than gracefully” means in Section 14.2: p is a k-th power of the fill fraction, so a modest rise in fill is amplified seven times over. Size for the load you will actually reach, or use a scalable Bloom filter.
14.2 ★ Match the structure to the mistake. For each task, pick a structure from the table in Section 14.1 and say which direction its error goes and why that direction is acceptable here. (a) Before querying the database, check whether a username might already be taken. (b) Count distinct daily visitors across 50 web servers. (c) Find the source IPs sending the most packets through a router. (d) Track which articles each user has already seen, where articles expire and must be removed.
Solution
(a) Bloom filter. False positives only. A false “maybe taken” costs one database query to confirm; a false negative would let a duplicate through, and a Bloom filter never produces one.
(b) HyperLogLog, one per server, merged at a coordinator by taking the register-wise maximum. Error is about ±1% in either direction, which is fine for a dashboard number, and the merge means no raw visitor IDs cross the network.
(c) Count-Min Sketch. Overestimates only, and the error is bounded by ε·N, so it is small relative to heavy hitters and large relative to rare items. That is the right bias for this task: the top talkers are estimated accurately, and nobody cares about precise counts for IPs that sent three packets.
(d) Cuckoo filter (or a counting Bloom filter). Still false positives only, which here means occasionally hiding an article the user has not actually seen: a mild cost. Expiry needs deletion, which a plain Bloom filter cannot do. The rule from Section 14.3 applies: delete only articles that were actually inserted.
14.3 ★★ Trace a Count-Min Sketch. A sketch has d = 2 rows and w = 5 columns, with hashes
| Item | h₀ | h₁ |
|---|---|---|
| a | 0 | 1 |
| b | 2 | 1 |
| c | 0 | 3 |
| d | 4 | 3 |
Process the stream a a a b c c d. (a) Show both rows. (b) Give the estimate for each item and compare it to the true count. (c) For ε = 0.001 and δ = 0.01, what w and d does Section 14.6 prescribe?
Solution
(a) True counts: a = 3, b = 1, c = 2, d = 1.
row 0 (h₀): [5] [0] [1] [0] [1] cell 0 = a + c = 3 + 2
row 1 (h₁): [0] [4] [0] [3] [0] cell 1 = a + b, cell 3 = c + d
(b)
| Item | Row 0 | Row 1 | Estimate (min) | True | Error |
|---|---|---|---|---|---|
| a | 5 | 4 | 4 | 3 | +1 |
| b | 1 | 4 | 1 | 1 | 0 |
| c | 5 | 3 | 3 | 2 | +1 |
| d | 1 | 3 | 1 | 1 | 0 |
Every estimate is ≥ the truth, as promised. a and c are overestimated because both of their rows had collisions; the minimum only helps when at least one row is clean. More rows make that more likely, which is what d buys.
(c) w = ⌈e/ε⌉ = ⌈2718.28⌉ = 2,719 and d = ⌈ln(1/δ)⌉ = ⌈ln 100⌉ = ⌈4.61⌉ = 5, so 13,595 counters. With probability at least 99%, every estimate is within 0.001 × N of the truth, where N is the total stream length, regardless of how many distinct items there are.
14.4 ★★ HyperLogLog arithmetic. (a) Four registers hold maximum leading-zero counts M = [2, 3, 2, 10]. Compare the arithmetic mean and the harmonic mean of the per-register estimates 2^M[i]. Which better reflects the three “normal” registers? (b) How many registers does HyperLogLog need for a standard error of 1%, given that m must be a power of two? How much memory at 6 bits per register? (c) Explain why merging two sketches by register-wise maximum gives exactly the sketch of the union.
Solution
(a) The per-register estimates are 4, 8, 4, 1024.
- Arithmetic mean: (4 + 8 + 4 + 1024) / 4 = 260.
- Harmonic mean: 4 / (1/4 + 1/8 + 1/4 + 1/1024) = 4 / 0.62598 ≈ 6.39.
One unlucky register drags the arithmetic mean up by a factor of 50. In the harmonic mean, the outlier contributes 1/1024 to the denominator, almost nothing, so the result stays near the typical register. This is why the estimator in Section 14.5 sums 2^(−M[i]).
(b) Solve 1.04/√m ≤ 0.01: √m ≥ 104, so m ≥ 10,816. The next power of two is 2¹⁴ = 16,384 (2¹³ = 8,192 gives 1.15%, not good enough). At 6 bits each that is 16,384 × 6 / 8 = 12,288 bytes, 12 KB, the figure the chapter quotes, with an actual standard error of 0.81%.
(c) A register’s value depends only on the elements whose hashes route to it: M[i] = max of the leading-zero count over those elements. For the union, the elements routed to register i are those from A plus those from B, and the maximum over a union is the maximum of the two maxima. Duplicates do no harm, because the same element produces the same hash and the same count in both sketches. So max(M_A[i], M_B[i]) is not an approximation of the union’s register; it is the union’s register.
14.5 ★★ Find the bug. Someone replaces the Kirsch-Mitzenmacher positions in BloomFilter with a “simpler” version:
def _positions(self, item):
h = hash(item)
for i in range(self.k):
yield (h + i) % self.m
m and k are still sized for 1%. The filter has no false negatives and is still about half full after n insertions. What goes wrong, and roughly how badly?
Hint
Picture the bit array after many insertions. Does a run of 7 consecutive 1-bits now happen by coincidence?
Solution
The k positions are no longer independent: each item sets one run of k consecutive bits. The false-positive formula assumes the k positions of a query are scattered, so each is independently 1 with probability about ½, giving (½)⁷ ≈ 1%. Here the query also tests a run of 7 consecutive bits, and the set bits are clumped into runs, so a run of 7 ones is far more common than (½)⁷. In particular, any query whose start lands inside an existing run (or in a region where overlapping runs have merged) is a false positive with no coincidence required.
Simulating it (n = 1,000, m = 9,586, k = 7, uniform random h) gives a false-positive rate of about 22%, against 1.05% for h1 + i*h2 with the same m and k. The fill fraction is the same in both (about 50%); only the correlation changed.
The fix is the chapter’s version: two independent hashes, with positions h1 + i·h2. h2 must also be non-zero mod m, or every position collapses to h1 and that item behaves as if k = 1, so a careful implementation guards against it.
14.6 ★★★ Derive the optimal k. Starting from p = (1 − e^(−kn/m))^k, show that the false-positive rate is minimised at k = (m/n) ln 2, that the filter is then exactly half full, and that the bits per element needed for a target p is about 1.44 log₂(1/p). Use it to reproduce the 1% row of the table in Section 14.2.
Hint
Substitute q = e^(−kn/m), the expected fraction of bits still 0, and write ln p in terms of q alone.
Solution
Let q = e^(−kn/m). Then k = −(m/n) ln q, and
ln p = k · ln(1 − q) = −(m/n) · ln q · ln(1 − q).
For fixed m and n, minimising p means maximising f(q) = ln q · ln(1 − q) over 0 < q < 1. Both factors are negative, so f is positive, and f is symmetric: f(q) = f(1 − q). Its derivative, f′(q) = ln(1 − q)/q − ln q/(1 − q), vanishes at q = ½, and that is its only zero in (0, 1), so q = ½ is the maximum.
- q = ½ means half the bits are still 0: the optimal filter is half full.
- e^(−kn/m) = ½ gives k = (m/n) ln 2.
- The false-positive rate is then p = (1 − ½)^k = 2^(−k) = 2^(−(m/n) ln 2).
Solving for bits per element: log₂(1/p) = (m/n) ln 2, so
m/n = log₂(1/p) / ln 2 ≈ 1.44 · log₂(1/p),
which is the “Space” line in Section 14.2’s properties list, and equals −ln p / (ln 2)², the formula in the constructor.
For p = 1%: log₂ 100 = 6.644, so m/n = 6.644 / 0.6931 = 9.59 bits, and k = 9.59 × 0.6931 = 6.64, rounded to 7. Each extra bit per element multiplies p by 2^(−ln 2) ≈ 0.62, which is why every 4.8 bits per element buys a factor of 10.
14.7 ★★★ Why MinHash works. (a) Let h be a random hash function with no ties, so the element of A ∪ B with the smallest hash is equally likely to be any of them. Prove that Pr[min h(A) = min h(B)] = |A ∩ B| / |A ∪ B|. (b) Implement signature(items, k) and estimate_jaccard(sig_a, sig_b), and check it on A = {0, …, 599} and B = {300, …, 899}.
Hint
Look at the single element x of A ∪ B with the smallest hash. When is it the minimum of A? Of B? Of both?
Solution
(a) Let x be the element of A ∪ B with the smallest hash value. x is the minimum of A if x ∈ A (nothing in A can be smaller than the minimum of a superset), and similarly for B. If x ∈ A ∩ B, both minima equal h(x). If x is in only one set, say A, then min h(A) = h(x), while min h(B) is the hash of some other element and is strictly larger (no ties). So the minima agree exactly when x ∈ A ∩ B. Since x is uniform over A ∪ B,
Pr[min h(A) = min h(B)] = |A ∩ B| / |A ∪ B| = J(A, B).
Each of k independent hash functions gives an independent yes/no trial with success probability J, so the fraction of agreeing minima estimates J with standard error √(J(1 − J)/k) ≤ 1/(2√k).
(b)
import hashlib
def h(seed, item):
"""One member of a family of hash functions, chosen by `seed`."""
data = ("%d:%s" % (seed, item)).encode()
return int.from_bytes(hashlib.blake2b(data, digest_size=8).digest(), "big")
def signature(items, k):
return [min(h(seed, x) for x in items) for seed in range(k)]
def estimate_jaccard(sig_a, sig_b):
return sum(x == y for x, y in zip(sig_a, sig_b)) / len(sig_a)
A = set(range(0, 600))
B = set(range(300, 900)) # |A & B| = 300, |A | B| = 900
est = estimate_jaccard(signature(A, 400), signature(B, 400))
assert abs(est - 1 / 3) < 0.07 # standard error is about 0.024
The true similarity is 300/900 = 1/3. The signatures are 400 integers each regardless of set size, and comparing them costs O(k), not O(|A| + |B|).
One trap worth knowing: the proof needs the minimum to be uniform over the set, and cheap linear hashes such as (a·x + b) mod p do not deliver that on structured keys like consecutive integers. On this exact example, a linear family with p = 2⁶¹ − 1 gives estimates around 0.28 to 0.29 instead of 0.33, and the bias stays when k is raised to 4,000, because it is in each hash function, not in the sampling. Use a well-mixed hash.
Where this connects
- Chapter 12: Hash Tables. The exact structure these approximate
- Chapter 16: External Memory and Cache-Oblivious Structures. Why Bloom filters are what make LSM-tree reads viable
Chapter 15: Spatial and Geometric Data Structures
15.1 The Spatial Query Problem
Every structure so far has assumed a total order. You can ask a BST for everything between 40 and 60 because “between” means something on a line. In two or more dimensions it stops meaning anything: there is no ordering of points in the plane that keeps neighbors adjacent, so a sorted array of coordinates cannot answer “which restaurants are within 500 metres of me.”
Spatial structures exist to answer three query types that ordered structures cannot:
- Range query: which objects fall inside this rectangle or circle?
- Nearest neighbor (NN): which object is closest to this point? Which k are closest?
- Intersection query: which objects overlap this one?
The shared strategy is the same one trees always use. Recursively partition the space so that a query can discard most of it without examining its contents. What differs is how the partition is chosen: by alternating coordinate (KD-tree), by fixed geometric subdivision (quadtree), or by grouping the objects themselves (R-tree).
15.2 K-Dimensional Trees (KD-Trees)
KD-trees partition k-dimensional space:
2D KD-Tree:
Level 0: Split on x-axis
Level 1: Split on y-axis
Level 2: Split on x-axis
...
Split on x: x < 7
│
┌─────┴─────┐
│ │
[2,3] │ [8,1]
│
Split on y: y < 5
│
┌────┴────┐
│ │
[1,8] [5,4]
A KD-tree is a BST where the comparison dimension cycles with depth. At depth d in a k-dimensional tree, nodes compare on axis d mod k. Every node therefore splits space with an axis-aligned hyperplane, and the subtree below it occupies a rectangular cell.
Construction. Building a balanced KD-tree means choosing the median along the current axis at each level:
def build_kdtree(points, depth=0):
if not points:
return None
axis = depth % len(points[0])
points.sort(key=lambda p: p[axis]) # O(n log n) per level
mid = len(points) // 2
return KDNode(
point=points[mid],
axis=axis,
left=build_kdtree(points[:mid], depth + 1),
right=build_kdtree(points[mid + 1:], depth + 1),
)
Sorting at every level costs O(n log² n). Using a linear-time median selection (introselect / nth_element) brings it to O(n log n), which is what production implementations do.
Nearest neighbor search is where the structure earns its keep. Descend to the leaf containing the query point, then unwind, but at each ancestor, check whether the splitting plane is closer than the best distance found so far. If it is, the other side of that plane could hold something better and must be searched. If it isn’t, an entire subtree is discarded.
def nearest(node, target, best=None):
if node is None:
return best
if best is None or dist(target, node.point) < dist(target, best):
best = node.point
axis = node.axis
diff = target[axis] - node.point[axis]
near, far = (node.left, node.right) if diff < 0 else (node.right, node.left)
best = nearest(near, target, best)
# Only cross the splitting plane if a closer point could exist beyond it
if abs(diff) < dist(target, best):
best = nearest(far, target, best)
return best
That pruning test (abs(diff) < dist(target, best))is the entire algorithm. Everything else is bookkeeping.
The curse of dimensionality. KD-tree NN search is O(log n) on average in low dimensions and O(n) in the worst case. The worst case stops being rare as k grows: in high dimensions almost every cell is close enough to the query that the pruning test fails, and the search degenerates to a full scan. The rule of thumb is that KD-trees stop paying for themselves somewhere around k ≈ 10–20, or more precisely once n < 2^k. Beyond that, use approximate methods. LSH, or HNSW graphs, which is what modern vector databases do.
| Operation | Average | Worst case |
|---|---|---|
| Build | O(n log n) | O(n log n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
| Nearest neighbor | O(log n) | O(n) |
| Range query | O(n^(1−1/k) + m) | O(n) |
KD-trees do not rebalance on insertion. A long-lived tree under heavy insertion degrades, and the standard fix is periodic bulk rebuild rather than rotations. Rotating would break the axis-cycling invariant.
15.3 Quad Trees
Divide 2D space into four quadrants recursively:
Level 0: ┌─────────┐
│ │
│ │
└─────────┘
Level 1: ┌───┬───┐
│ NW │ NE │
├───┼───┤
│ SW │ SE │
└───┴───┘
Where a KD-tree splits on a data point, a quadtree splits on geometry, always at the exact centre of the current cell, regardless of what the data looks like. That single difference drives everything else about the structure.
Point quadtrees subdivide a cell once it holds more than some threshold of points. Region quadtrees subdivide until each cell is uniform. The classic use is image compression, where a solid-colored region collapses to a single leaf no matter how large it is.
class QuadTree:
def __init__(self, boundary, capacity=4):
self.boundary = boundary # (x, y, width, height)
self.capacity = capacity
self.points = []
self.divided = False
def insert(self, point):
if not self.boundary.contains(point):
return False
if len(self.points) < self.capacity and not self.divided:
self.points.append(point)
return True
if not self.divided:
self.subdivide() # create nw, ne, sw, se
return (self.nw.insert(point) or self.ne.insert(point)
or self.sw.insert(point) or self.se.insert(point))
Because the subdivision is geometric rather than data-driven, depth depends on how clustered the data is, not on how much of it there is. A million points spread evenly gives a shallow tree; a thousand points stacked nearly on top of each other gives a very deep one. Implementations guard this with a maximum depth.
The 3D generalization is the octree (eight children instead of four), used throughout graphics for frustum culling, collision broadphase, and voxel storage, Minecraft-style voxel worlds are octrees.
15.4 R-Trees
R-trees index rectangles/hyper-rectangles:
R-Tree:
┌──────────────────┐
│ [MBR of all] │
│ ┌──┐ ┌──┐ │
│ │ │ │ │ │
│ └──┘ └──┘ │
│ ┌──────┐ │
│ │ │ │
│ └──────┘ │
└──────────────────┘
KD-trees and quadtrees index points. R-trees index extended objects (roads, building footprints, delivery zones) and they are the structure databases actually ship.
An R-tree is a B-tree whose keys are minimum bounding rectangles (MBRs). Each internal entry stores the MBR enclosing everything in its subtree. A query descends into every child whose MBR intersects the query region, which may be more than one, and that is the crucial difference from a B-tree. Where a B-tree descends exactly one path, an R-tree may descend several.
This gives R-trees B-tree virtues: balanced by construction, high fanout, tuned to disk pages, and O(log n) height. It also gives them their central problem: overlap. Sibling MBRs may intersect, and every intersection means a query that could have followed one path now follows two. Search degrades toward O(n) as overlap grows.
The whole R-tree literature is about controlling overlap when a node splits and its entries must be divided in two. Guttman’s original 1984 paper offered linear and quadratic split heuristics. The R-tree* (Beckmann et al., 1990) minimizes a combination of overlap, MBR area, and margin, and reinserts a fraction of entries on overflow instead of splitting immediately; it is meaningfully better in practice and is what most implementations mean by “R-tree” today. The R+-tree eliminates overlap entirely by duplicating objects across cells, trading space and update cost for query speed.
For static data, bulk loading, either by sorting along a space-filling curve (Hilbert packing) or by Sort-Tile-Recursive (STR) packing, produces far better trees than repeated insertion.
15.5 Grids, Geohashes, and Space-Filling Curves
The simplest spatial index is a uniform grid: divide space into fixed cells, hash each object into the cells it touches. Insert and point lookup are O(1), which no tree can match. The catch is that a grid has no way to adapt. Cell size must be chosen up front, and real geographic data is wildly non-uniform. A grid sized for Manhattan is useless for Montana.
Space-filling curves offer a different trick: map 2D coordinates to a single number that mostly preserves locality, then use an ordinary B-tree.
- Z-order (Morton) curve: interleave the bits of x and y. Cheap to compute, but has discontinuities where the curve jumps across the space.
- Hilbert curve: better locality preservation and no long jumps, at higher computational cost.
Geohash applies Z-order to latitude/longitude and base-32 encodes the result, so that a shared string prefix means geographic proximity, u4pruyd and u4pruyf are neighbors. This makes spatial proximity queryable in any plain key-value store, which is why geohashes are everywhere. The failure mode is boundary effects: two points either side of a major cell boundary are physically adjacent but share no prefix, so correct implementations query the eight neighboring cells as well.
Production systems have largely moved to hierarchical cell systems built on this idea: Google’s S2 (Hilbert curve projected onto a sphere) and Uber’s H3 (hexagonal cells, so all neighbors are equidistant, which matters for routing and surge pricing).
15.6 Choosing a Spatial Structure
| Structure | Best for | Weakness |
|---|---|---|
| Uniform grid | Uniform density, fast updates | Non-uniform data wastes space or overflows cells |
| KD-tree | Static point sets, low dimensions, kNN | Degrades badly above ~10 dimensions; no rebalancing |
| Quadtree / Octree | Clustered 2D/3D points, image regions, collision broadphase | Depth driven by clustering, not data size |
| R-tree / R*-tree | Extended objects, disk-resident data, GIS | Overlap degrades queries; complex splits |
| Geohash / S2 / H3 | Distributed stores, sharding by location | Boundary effects need neighbor queries |
| HNSW / LSH | High-dimensional similarity search | Approximate, not exact |
The practical decision tree is short. Points or shapes? Shapes means R-tree. Points in memory and static? KD-tree. Points, clustered, and 2D/3D? Quadtree or octree. Needs to live in a database or shard across machines? Geohash or S2. More than ~20 dimensions? Give up on exactness and use HNSW.
15.7 Applications
KD-Trees:
- Nearest neighbor search
- Point clouds
- Ray tracing
Quad Trees:
- Image compression
- Collision detection
- Sparse data
R-Trees:
- Geographic Information Systems
- Database spatial indexes
- Map applications
In shipped systems: PostGIS and Oracle Spatial index with R-trees (PostgreSQL’s GiST is a generalized R-tree); SQLite ships an R*-tree module; MongoDB and Redis use geohash-backed indexes for $near and GEORADIUS; scikit-learn’s KDTree and BallTree back its neighbor queries; game engines use octrees and BSP trees for visibility and collision; and ray tracers use KD-trees or bounding volume hierarchies, a BVH is essentially an R-tree for triangles.
15.8 Historical Context
Jon Bentley introduced KD-trees in 1975 while a graduate student at Stanford, as a multidimensional generalization of binary search. Raphael Finkel and Bentley described quadtrees the previous year, in 1974. Antonin Guttman published the R-tree in 1984 specifically to make spatial data indexable on disk, and the R*-tree refinement followed from Beckmann, Kriegel, Schneider, and Seeger in 1990.
The space-filling curves are much older than the structures that use them: Giuseppe Peano constructed the first in 1890 and David Hilbert described his variant in 1891, as pure mathematics with no application in view. G. M. Morton put Z-order to work for geographic databases at IBM in 1966: a rare case of a piece of nineteenth-century mathematics arriving in computing essentially unchanged.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
15.1 ★ Build a KD-tree. Run build_kdtree from Section 15.2 on the points (2,3), (5,4), (9,6), (4,7), (8,1), (7,2). Draw the resulting tree, giving each node’s point and splitting axis, and sketch how the root and its children cut the plane.
Solution
- Depth 0 (axis x): sorted by x the points are (2,3), (4,7), (5,4), (7,2), (8,1), (9,6).
mid = 3, so the root is (7,2). Left gets the first three, right gets (8,1), (9,6). - Depth 1, left (axis y): sorted by y: (2,3), (5,4), (4,7). The median is (5,4), with (2,3) on its left and (4,7) on its right.
- Depth 1, right (axis y): sorted by y: (8,1), (9,6).
mid = 1, so the node is (9,6) with (8,1) as its left child and no right child. - Depth 2 (axis x): (2,3), (4,7) and (8,1) are leaves.
(7,2) x
/ \
(5,4) y (9,6) y
/ \ /
(2,3) x (4,7) x (8,1) x
The root draws the vertical line x = 7. On the left half, (5,4) draws the horizontal line y = 4, separating (2,3) below from (4,7) above. On the right half, (9,6) draws y = 6, with (8,1) below it. Every node’s subtree occupies a rectangle bounded by its ancestors’ lines.
15.2 ★★ Trace a nearest-neighbour search. On the tree from 15.1, run nearest(root, (9, 2)). List the nodes visited in order, the best point and distance after each, and every pruning decision. Which subtree is never examined?
Hint
At each node, the pruning test compares |diff| (the distance to the splitting line) with the best distance so far.
Solution
- (7,2), axis x. Distance √(4 + 0) = 2.000; best = (7,2). diff = 9 − 7 = 2 ≥ 0, so near = right subtree (9,6), far = left subtree (5,4).
- (9,6), axis y. Distance 4.000, not better. diff = 2 − 6 = −4 < 0, so near = left (8,1), far = right (empty).
- (8,1), axis x. Distance √(1 + 1) ≈ 1.414; best = (8,1). Both children are empty.
- Back at (9,6): is |−4| < 1.414? No. Its (empty) far side is skipped.
- Back at (7,2): is |2| < 1.414? No. The whole left subtree, (5,4) with (2,3) and (4,7), is pruned.
Result: (8,1) at distance √2, after visiting 3 of 6 nodes. The pruning is sound: every point in the left subtree has x < 7, so it is at least 2 away from the target, which already loses to √2.
15.3 ★★ Find the bug. A developer “simplifies” the pruning test in nearest to compare against the current node’s own distance:
def nearest(node, target, best=None):
if node is None:
return best
if best is None or dist(target, node.point) < dist(target, best):
best = node.point
axis = node.axis
diff = target[axis] - node.point[axis]
near, far = (node.left, node.right) if diff < 0 else (node.right, node.left)
best = nearest(near, target, best)
if dist(target, node.point) < dist(target, best): # changed line
best = nearest(far, target, best)
return best
Give a small point set and query where this returns the wrong answer, and explain what the correct test measures.
Solution
Build the tree from (4,0), (5,5), (9,9): the root is (5,5) splitting on x, with (4,0) on the left and (9,9) on the right. Query (6,0).
- At the root, distance √(1 + 25) ≈ 5.10, so best = (5,5). diff = 6 − 5 = 1, so near = right.
- At (9,9), distance √(9 + 81) ≈ 9.49. Not better.
- Back at the root, the buggy test asks whether 5.10 < 5.10. It is false (the root is the best), so the left subtree is skipped.
The buggy version returns (5,5) at 5.10. The correct answer is (4,0), at distance 2.
The node’s own distance says nothing about what lies across the splitting line. The correct test, abs(diff) < dist(target, best), asks whether the circle of radius best-distance around the target crosses that line. Here |diff| = 1 < 5.10, so the circle crosses x = 5 and the left side must be searched. A KD-tree search is only correct if it prunes on the distance to the region, never the distance to a representative point.
15.4 ★★ Range query on a quadtree. The QuadTree in Section 15.3 shows only insert. Write subdivide and query_range(area), which returns every stored point inside a query rectangle. Note that this insert leaves a node’s original points in place when it subdivides, so internal nodes hold points too.
Hint
Two tests drive the recursion: does this node’s boundary intersect the query at all (if not, prune), and is each stored point inside the query?
Solution
boundary needs contains and intersects, so it is a small class rather than a tuple. Using half-open boxes means a point on a shared edge belongs to exactly one child.
class Rect:
"""Half-open box: x <= px < x + w and y <= py < y + h."""
def __init__(self, x, y, w, h):
self.x, self.y, self.w, self.h = x, y, w, h
def contains(self, p):
return (self.x <= p[0] < self.x + self.w
and self.y <= p[1] < self.y + self.h)
def intersects(self, other):
return not (other.x >= self.x + self.w or other.x + other.w <= self.x
or other.y >= self.y + self.h or other.y + other.h <= self.y)
class QuadTree:
def __init__(self, boundary, capacity=4):
self.boundary = boundary
self.capacity = capacity
self.points = []
self.divided = False
def insert(self, point): # as in Section 15.3
if not self.boundary.contains(point):
return False
if len(self.points) < self.capacity and not self.divided:
self.points.append(point)
return True
if not self.divided:
self.subdivide()
return (self.nw.insert(point) or self.ne.insert(point)
or self.sw.insert(point) or self.se.insert(point))
def subdivide(self):
b, hw, hh = self.boundary, self.boundary.w / 2, self.boundary.h / 2
self.sw = QuadTree(Rect(b.x, b.y, hw, hh), self.capacity)
self.se = QuadTree(Rect(b.x + hw, b.y, hw, hh), self.capacity)
self.nw = QuadTree(Rect(b.x, b.y + hh, hw, hh), self.capacity)
self.ne = QuadTree(Rect(b.x + hw, b.y + hh, hw, hh), self.capacity)
self.divided = True
def query_range(self, area, found=None):
if found is None:
found = []
if not self.boundary.intersects(area):
return found # prune the whole subtree
for p in self.points: # internal nodes keep points too
if area.contains(p):
found.append(p)
if self.divided:
for child in (self.nw, self.ne, self.sw, self.se):
child.query_range(area, found)
return found
import random
qt = QuadTree(Rect(0, 0, 100, 100))
pts = [(random.uniform(0, 100), random.uniform(0, 100)) for _ in range(500)]
for p in pts:
assert qt.insert(p)
area = Rect(20, 30, 25, 10)
assert sorted(qt.query_range(area)) == sorted(p for p in pts if area.contains(p))
The intersection test is the whole point: a query covering a small corner of the space descends only into the cells that touch it, and everything else is discarded at the top. Forgetting the points stored in internal nodes is the easy bug with this variant of insert; it silently drops the first capacity points of every subdivided cell.
15.5 ★ Z-order by hand. On an 8 × 8 grid, the Morton code interleaves the bits of x and y, with x’s bits in the even positions (bit 0 of the code is bit 0 of x, bit 1 is bit 0 of y, and so on). (a) Compute the codes of (5,3), (3,3) and (4,3). (b) (3,3) and (4,3) are horizontal neighbours. A B-tree range scan over codes 15 to 26 is meant to find “cells near them”. How many cells does it return, and which unwanted ones?
Solution
(a) Write each coordinate in 3 bits and interleave as y₂x₂ y₁x₁ y₀x₀:
| Point | x | y | Interleaved | Code |
|---|---|---|---|---|
| (5,3) | 101 | 011 | 01 10 11 | 27 |
| (3,3) | 011 | 011 | 00 11 11 | 15 |
| (4,3) | 100 | 011 | 01 10 10 | 26 |
(b) The scan returns 12 cells: (3,3), then (4,0), (5,0), (4,1), (5,1), (6,0), (7,0), (6,1), (7,1), (4,2), (5,2), and finally (4,3). Between two adjacent cells, the curve detours through 10 cells of the lower-right quadrant, including (6,0) and (7,0), which are three rows down and several columns across. This is the “discontinuity” Section 15.5 warns about: x = 3 to x = 4 crosses the top-level split, where the curve jumps. Production systems answer a range query with several smaller code ranges, one per curve segment, rather than one big one, and the Hilbert curve reduces (but does not eliminate) how often this happens.
15.6 ★★ Design: a food-delivery backend. You must support three queries: (1) “restaurants within 3 km of this customer”, over 500,000 restaurants that rarely move; (2) “which delivery zone contains this address”, where zones are hand-drawn polygons; (3) “the 5 nearest available couriers”, over 20,000 couriers each reporting a new position every 4 seconds. Pick a structure for each and say what you are giving up.
Solution
- Restaurants: geohash or S2 cells in the existing database, or an R-tree index (PostGIS). The data is static points that must live in a database and probably shard by region. Cover the 3 km circle with a handful of cells, scan those key ranges, then filter by exact distance. Given up: the cell cover over-fetches near its edges, and you must query neighbouring cells to avoid the boundary problem.
- Zones: R-tree. These are extended objects, not points, which rules out KD-trees and point quadtrees. Index each polygon’s bounding rectangle, use the R-tree to find candidate zones whose MBR contains the address, then run an exact point-in-polygon test on those few. Given up: overlapping MBRs mean some queries check several candidates; with few, rarely edited zones, that is cheap.
- Couriers: a uniform grid (or geohash/H3 cells) kept in a hash map from cell to the set of couriers. 20,000 couriers × one update per 4 s is 5,000 updates per second, and a grid makes each update O(1): remove from the old cell, add to the new one. For k-nearest, search the courier’s cell, then rings of neighbouring cells until 5 are found and the next ring cannot contain anything closer. A KD-tree is the wrong choice: it does not rebalance (Section 15.2), so it would need rebuilding constantly. Given up: the grid’s cell size is fixed, so dense downtown cells hold many couriers and sparse suburbs need several rings of empty cells. That is acceptable at this scale, and per-city grid sizes or hierarchical H3 resolutions fix it if it is not.
15.7 ★★★ Where O(√n) comes from. Section 15.2 gives a KD-tree range query as O(n^(1−1/k) + m). Prove the 2D case: in a balanced KD-tree over n points (with distinct coordinates), any vertical line intersects the regions of only O(√n) nodes. Then explain how that gives O(√n + m) for an axis-aligned rectangle query reporting m points, and how the argument generalises to n^(1−1/k).
Hint
Look two levels at a time. A vertical line meets one child of an x-splitting node, but both children of a y-splitting node.
Solution
The line bound. Let Q(n) be the number of nodes whose regions a vertical line ℓ meets, in a subtree with n points whose root splits on x.
- The root’s vertical split line puts ℓ on one side, so ℓ enters only one child (n/2 points, splitting on y).
- That child splits horizontally, and a vertical line crosses a horizontal split, so ℓ enters both grandchildren, each with about n/4 points and splitting on x again.
So Q(n) ≤ 2 + 2Q(n/4) (the 2 counts the root and the one child). Unrolling over log₄ n levels gives a geometric sum dominated by its last term: Q(n) = O(2^(log₄ n)) = O(n^(1/2)) = O(√n). Starting from a y-splitting root only adds one level. A horizontal line is symmetric.
The range query. Every node a rectangle query visits is one of:
- fully inside the rectangle: report its whole subtree, O(size of subtree), paid for by the output m;
- disjoint from it: never visited, because its parent pruned it;
- crossing the boundary: then the node’s region meets one of the rectangle’s four edges, and each edge lies on a vertical or horizontal line.
By the line bound, each of the four lines meets O(√n) regions, so at most O(√n) boundary nodes are visited. The parents of pruned or fully-inside nodes are themselves boundary nodes, so they add at most a constant factor. Total: O(√n + m).
In k dimensions, the boundary is made of hyperplanes. A hyperplane perpendicular to one axis enters one child at the level splitting on that axis and both children at each of the other k − 1 levels, so k levels cover 2^(k−1) subtrees of n/2^k points: Q(n) = 2^(k−1) Q(n/2^k) + O(2^k), which solves to O(n^((k−1)/k)) = O(n^(1−1/k)). At k = 10 this is n^0.9, barely better than scanning everything, which is the curse of dimensionality showing up in the bound itself.
Where this connects
- Chapter 16: External Memory and Cache-Oblivious Structures. Why KD-trees degrade once the data leaves cache
- Chapter 19: Emerging and Specialized Structures. HNSW and the high-dimensional case these structures cannot handle
Chapter 16: External Memory and Cache-Oblivious Structures
16.1 The Memory Hierarchy
Modern computers have multiple levels of memory:
- L1 cache: ~32KB, ~1ns
- L2 cache: ~256KB, ~4ns
- L3 cache: ~8MB, ~15ns
- Main memory: ~64GB, ~100ns
- SSD: ~100GB, ~100μs
- Hard disk: ~TB, ~10ms
Read that list again as ratios rather than absolutes. Main memory is roughly 100× slower than L1. A disk seek is roughly 10,000,000× slower. Every complexity result in this book so far has assumed the RAM model from Chapter 1, where any memory access costs the same O(1). Across a spread that wide, that assumption is not an approximation. It is simply false, and it produces wrong predictions about which structure is faster.
The classic demonstration: a linked list and an array with identical asymptotic complexity for traversal, O(n), differ by 10× or more in wall-clock time. The array walks contiguous cache lines and the hardware prefetcher predicts every access. The list chases pointers to arbitrary addresses, and each hop is a potential cache miss. Same O(n), different machines being used.
Two things matter and the RAM model captures neither:
- Transfers are blocked. Memory does not move one word at a time. It moves in cache lines (typically 64 bytes) or disk pages (typically 4KB). Reading one byte costs the same as reading the whole block it sits in.
- Locality is free performance. If a structure arranges the data an algorithm touches together so it arrives in the same block, the remaining accesses cost nothing.
The structures in this chapter are the ones designed under those two facts instead of in spite of them.
16.2 External Memory Model
The I/O model accounts for disk access:
- B: Block size (elements per block)
- M: Internal memory size
- D: Disk access time relative to memory
Goal: Minimize block transfers.
The external memory model (also called the I/O model or the Aggarwal–Vitter model, after its 1988 authors) replaces “count the operations” with “count the block transfers.” Computation on data already in memory is free; only I/O counts. This sounds crude, and it predicts real performance remarkably well.
The model changes the answers, not just the constants:
| Problem | RAM model | External memory model |
|---|---|---|
| Scan n elements | O(n) | O(n/B) |
| Sort n elements | O(n log n) | O((n/B) · log_(M/B) (n/B)) |
| Search, B-tree | O(log n) | O(log_B n) |
| Search, binary search tree | O(log n) | O(log n), one I/O per level |
| Search, binary search on sorted array | O(log n) | O(log (n/B)) |
The last three rows are the whole argument for B-trees. A balanced BST and a B-tree are both O(log n) in the RAM model, so the RAM model says they are equivalent. In the I/O model the BST costs one transfer per level while the B-tree packs B keys into each transfer, giving log_B n instead of log₂ n. With B = 512, a billion keys take 30 I/Os in a BST and 4 in a B-tree. That is not a constant-factor difference in any practical sense. It is the difference between a usable database index and an unusable one.
Sorting is the other headline result. The optimal external sort is a multiway merge with fanout M/B, not the binary merge you would write in memory: read M/B blocks at a time, merge them, write out. Reducing the number of passes over the data is everything, because each pass is n/B transfers. This is why external merge sort in a database uses hundreds of runs at once rather than merging two at a time.
Cache-aware vs. cache-oblivious. A structure that takes B and M as tuning parameters is cache-aware (B-trees are the canonical example: you pick the node size to match the page size). This works, but it must be re-tuned per machine, and it can only be tuned for one level of a hierarchy that has five. Tune your B-tree node to the disk page and you have said nothing about L1, L2, or L3.
16.3 Cache-Oblivious Structures
Cache-oblivious structures perform well at all cache levels without tuning:
van Emde Boas Layout:
Recursively divide at mid-level:
┌───────────────┐
│ ○ │
├───────┬───────┤
│ ○ │ ○ │
├───┬───┼───┬───┤
│ ○ │ ○ │ ○ │ ○ │
└───┴───┴───┴───┘
A cache-oblivious structure achieves the optimal I/O bound without knowing B or M. This sounds impossible (how do you optimize for a block size you were never told?)and the resolution is elegant: build the structure so that it is simultaneously well-organized at every scale. Whatever B turns out to be, some level of the recursion matches it.
The van Emde Boas layout is the foundational trick. Take a complete binary tree of height h and cut it horizontally at the middle, producing a top subtree of height h/2 and roughly √n bottom subtrees of height h/2. Lay each of those out recursively, and store them contiguously.
Tree: Layout in memory:
1 [1 | 2 4 5 | 3 6 7]
/ \ ↑ ↑ ↑
2 3 top sub1 sub2 ← each recursively vEB-laid-out
/| |\
4 5 6 7
Now consider a root-to-leaf search under any block size B. Somewhere in the recursion there is a level whose subtrees have size between √B and B: those subtrees fit in one block. The search path crosses O(log_B n) such subtrees, so it costs O(log_B n) transfers. That is the same bound a B-tree achieves, obtained without ever naming B. And because the argument holds for every B simultaneously, the same layout is optimal for L1, L2, L3, RAM, and disk at once, which no cache-aware structure can be.
Compare the layouts directly:
| Layout | Search cost in I/Os | Needs tuning? |
|---|---|---|
| Sorted array + binary search | O(log(n/B)) | No, but poor locality at the top |
| Level-order (BFS) binary tree | O(log n) | No, worst of both |
| B-tree | O(log_B n) | Yes, node size = B |
| van Emde Boas layout | O(log_B n) | No |
The level-order row is worth noting because it is the layout most people write by default. Storing a binary tree breadth-first feels cache-friendly (it is contiguous, after all) but a root-to-leaf path in it touches one new block per level near the bottom, where almost all the nodes are.
Other cache-oblivious results. Funnelsort achieves the optimal sorting bound obliviously, using a recursively-defined merger structure. Cache-oblivious B-trees combine the vEB layout with a packed-memory array to support updates. These are theoretically beautiful and less common in production than the theory would suggest. The constant factors are worse than a well-tuned B-tree, and in practice you usually do know your page size.
16.4 What Production Systems Actually Do
The ideas in this chapter show up in shipped code more often through their conclusions than their specific structures.
B-trees everywhere. Every relational database index, every filesystem (NTFS, HFS+, ext4, APFS all use B-trees or variants), and embedded stores like LMDB. Node size is matched to the page size.
LSM trees take the opposite approach to the same problem. Where a B-tree updates in place (costing a random write per update)a Log-Structured Merge tree buffers writes in a memory table, flushes them as sorted immutable runs, and merges runs in the background. Every disk write becomes sequential. Reads get slower (you may check several runs, which is what the Bloom filters from Chapter 14 mitigate) and space amplification goes up, but write throughput improves by an order of magnitude on both spinning disks and SSDs. This is the write-heavy tradeoff, and it is why LevelDB, RocksDB, Cassandra, and ScyllaDB use it.
Column stores (Parquet, ORC, ClickHouse) are external-memory thinking applied to analytics. A query touching 3 columns of a 200-column table reads 3/200ths of the blocks instead of all of them. Same asymptotics, ~60× fewer transfers.
Struct-of-arrays is the same reasoning at cache-line scale. Storing {x[], y[], z[]} rather than {x,y,z}[] means a loop over just the x values fills each cache line entirely with x values. Games and numerics rely on this heavily.
Practical rules that follow from the model:
- Prefer contiguous layouts.
std::vectorbeatsstd::listalmost always, even when the asymptotics favor the list. - Match node sizes to blocks. A tree node should fill a cache line or a page, not straddle two.
- Count passes over data, not operations. Two passes over 10GB is a real cost; the arithmetic in between usually is not.
- Batch and sort. Random access converted into sequential access is often a 100× win.
- Measure with hardware counters, not just a stopwatch.
perf statreports cache misses directly, which tells you whether you have a locality problem or a computation problem.
16.5 Historical Context
Alok Aggarwal and Jeffrey Vitter formalized the external memory model in their 1988 paper “The Input/Output Complexity of Sorting and Related Problems,” establishing the sorting bound that still bears their names, though the practical wisdom substantially predates the theory, since Knuth’s treatment of external sorting in The Art of Computer Programming Volume 3 (1973) covers tape-based merging in detail.
Cache-oblivious algorithms arrived much later. Harald Prokop’s 1999 MIT master’s thesis, supervised by Charles Leiserson, introduced the model and the van Emde Boas layout application, with the fuller treatment in Frigo, Leiserson, Prokop, and Ramachandran’s FOCS 1999 paper. The layout itself is named for Peter van Emde Boas, who used the recursive halving idea in his 1975 priority queue: a structure solving an entirely different problem.
The LSM tree came from Patrick O’Neil and colleagues in 1996, and sat relatively unused until Google’s Bigtable (2006) made it the default architecture for write-heavy distributed storage.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
16.1 ★ Count the I/Os. An index holds n = 2³⁰ keys (about a billion) on disk, and a 4 KB page holds B = 256 keys. Using the table in Section 16.2, how many page reads does a lookup cost with (a) a balanced BST, one node per page; (b) binary search over a sorted array; (c) a B-tree with fanout 256? (d) How much memory would it take to cache the B-tree’s top two levels, and how many reads does a lookup cost then?
Solution
(a) A balanced BST has height log₂ 2³⁰ = 30, and each level is a separate page: 30 reads.
(b) Binary search narrows the range by half per probe, but once it is down to B keys the remaining probes stay in one page: about log₂(n/B) = log₂ 2²² = 22 reads.
(c) log₂₅₆ 2³⁰ = 30/8 = 3.75, so the tree has 4 levels (256³ = 2²⁴ keys is too few; 256⁴ = 2³² is enough): 4 reads.
(d) The top two levels are 1 + 256 = 257 pages, about 1 MB. With them in memory, a lookup reads only the bottom two levels: 2 reads. This is why B-tree databases are fast in practice: the upper levels of every hot index sit in the buffer pool, and the cost of a lookup is one or two real I/Os. The same 257 pages would cache only the top 8 levels of the one-node-per-page BST (2⁸ − 1 = 255 pages), leaving 22 reads.
16.2 ★★ External merge sort. Sort N = 100 GB with M = 1 GB of memory and 1 MB blocks. (a) How many sorted runs does the first pass create? (b) How many merge passes does a multiway merge with fanout M/B need, and how many does a binary (two-way) merge need? (c) Compare the total data read and written. (d) Roughly how large could N be while still finishing in two passes?
Solution
(a) Read 1 GB at a time, sort it in memory, write it out: 100 runs of 1 GB.
(b) Memory holds M/B = 1,000 one-block buffers. Keep one for output and the other 999 can each hold the current block of one run, so all 100 runs merge in one pass. A two-way merge halves the number of runs per pass: 100 → 50 → 25 → 13 → 7 → 4 → 2 → 1, which is ⌈log₂ 100⌉ = 7 passes.
(c) Every pass reads and writes all 100 GB, so it moves 200 GB.
| Strategy | Passes (run formation + merges) | Data moved |
|---|---|---|
| Multiway, fanout ~1,000 | 1 + 1 = 2 | 400 GB |
| Two-way | 1 + 7 = 8 | 1.6 TB |
At 500 MB/s of sequential throughput, that is about 13 minutes against about 53. The comparison counts are similar; the difference is entirely passes over the data, which is the point of the O((n/B) · log_(M/B)(n/B)) bound: here n/B = 100,000 blocks and log₁₀₀₀ 100,000 ≈ 1.7, so two passes.
(d) One merge pass can combine up to about 999 runs of 1 GB, so N up to roughly 1 TB sorts in two passes. A third pass multiplies that by another ~1,000, to about 1 PB. With a reasonable amount of memory, external sorting almost never needs more than three passes.
16.3 ★★ The van Emde Boas layout by hand. Number a complete binary tree of height 4 in level order (root 1, children of i are 2i and 2i + 1, leaves 8 to 15). (a) Write out its van Emde Boas layout, cutting so the top tree has height 2. (b) Memory is read in aligned blocks of 3 nodes. How many blocks does the search path 1 → 2 → 5 → 11 touch in the vEB layout, and how many in the plain level-order layout 1, 2, …, 15?
Solution
(a) The top tree is {1, 2, 3}. Below its leaves hang four bottom trees of height 2, rooted at 4, 5, 6 and 7, each stored as root then children:
[1 2 3 | 4 8 9 | 5 10 11 | 6 12 13 | 7 14 15]
(Each piece has height at most 2, so the recursion stops there.)
(b) With blocks of 3 the vEB layout splits exactly into those five pieces:
- vEB blocks:
[1 2 3] [4 8 9] [5 10 11] [6 12 13] [7 14 15]. The path 1, 2, 5, 11 touches[1 2 3]and[5 10 11]: 2 blocks. - Level-order blocks:
[1 2 3] [4 5 6] [7 8 9] [10 11 12] [13 14 15]. The path touches[1 2 3],[4 5 6]and[10 11 12]: 3 blocks.
Every root-to-leaf path costs 2 blocks in the vEB layout and 3 in level order. The difference is small at this size, but it is structural: in level order, the nodes on a path near the bottom are far apart because each level is twice as wide as the last, while the vEB layout keeps each small subtree, and therefore each short stretch of path, together.
16.4 ★★ Predict the cache misses. A 16384 × 16384 matrix of 8-byte doubles is stored row-major. A cache line holds 8 doubles, and the cache is an ideal fully associative LRU cache of 256 KB (4,096 lines). Count the misses for summing the matrix (a) row by row and (b) column by column. (c) Repeat (b) for a 2048 × 2048 matrix. What general rule does this show?
Hint
In (b), the next column wants the neighbouring double in each line you just loaded. Is that line still in the cache when you come back for it?
Solution
(a) Row by row reads memory sequentially. Each line is loaded once and all 8 doubles in it are used: n²/8 = 2²⁸/8 = 2²⁵ ≈ 33.6 million misses.
(b) Walking down a column touches one double in each of 16,384 different lines (consecutive rows are 128 KB apart). The cache holds only 4,096 lines, so by the time the walk returns to the top for the next column, the line holding its neighbour was evicted long ago. Every access misses: n² = 2²⁸ ≈ 268 million misses, 8 times as many as (a).
(c) A 2048 × 2048 column walk touches 2,048 lines, which fits in the 4,096-line cache. They survive until the next 7 columns reuse them, so the column-wise sum also costs only n²/8 = 2¹⁹ ≈ 0.5 million misses, the same as row-wise.
The rule: a traversal is cheap as long as its working set of blocks fits in memory, and falls off a cliff (here a factor of B = 8) the moment it does not. The RAM model sees both loop orders as identical O(n²). The I/O model predicts both the gap and where it starts. (Real caches are set-associative, and power-of-two strides map many rows to the same sets, so the cliff on actual hardware usually comes earlier than this ideal-cache count suggests. That is one more reason to traverse in storage order.)
16.5 ★★ Design: B-tree or LSM tree? Choose a storage engine for each workload and justify it. (a) An IoT platform ingesting 500,000 sensor readings per second, queried mostly as “the last hour of readings for device X”. (b) A bank’s account-balance table: small, frequent updates to existing rows, and point reads that must have predictable latency. (c) For workload (a), the per-run Bloom filters from Chapter 14 do almost nothing for the “last hour” query. Why?
Solution
(a) LSM tree. The workload is overwhelmingly writes, and an LSM tree turns every write into a sequential append to a memtable flush, where a B-tree would pay a random page write for each one. Reads are recent and keyed by (device, time), so they mostly hit the newest runs, which are small and likely cached. The price is background compaction (write amplification and I/O you do not directly control) and higher space amplification, both acceptable for append-mostly data.
(b) B-tree. Updates modify existing keys in place, and a point read is one root-to-leaf path, a predictable 1 to 2 I/Os with the upper levels cached. An LSM tree would leave several versions of hot accounts spread across runs until compaction, and a read may have to check several runs; compaction also introduces latency spikes. When predictable read latency matters more than write throughput, the B-tree’s in-place update is the right trade.
(c) A Bloom filter answers “is this exact key in this run?”. A range query asks “does this run hold any key between t₁ and t₂ for device X?”, which a membership filter cannot answer without testing every possible key in the range. So a range scan must consult every run whose key range overlaps the query. What helps instead is each run’s min/max key metadata (skip runs whose range does not overlap) and, if keys share a prefix such as the device ID, a filter built on that prefix rather than on the full key, which is what RocksDB’s prefix Bloom filters do.
16.6 ★★★ Measure the vEB layout. Write veb_order(height), returning the level-order node numbers of a complete binary tree in van Emde Boas order (give the top tree the smaller half of the height). Then, for a tree of height 20 (about a million nodes) and aligned blocks of B = 16, 64 and 512 nodes, find the worst-case number of blocks on any root-to-leaf path, for both the vEB layout and the level-order layout. Compare with log_B n and explain the results.
Hint
In level-order numbering, the leaves of a top tree of height t rooted at r are r · 2^(t−1) up to r · 2^(t−1) + 2^(t−1) − 1, and the bottom trees hang from their children. To find a path, walk up from a leaf with node //= 2.
Solution
def veb_order(height, root=1):
"""Level-order numbers (root = 1, children 2i and 2i+1) of a complete
binary tree of the given height, listed in van Emde Boas order."""
if height == 1:
return [root]
top_h = height // 2 # top gets the smaller half
bottom_h = height - top_h
order = veb_order(top_h, root)
# The bottom subtrees hang below the top tree's leaves, left to right.
first_leaf = root << (top_h - 1)
for leaf in range(first_leaf, first_leaf + (1 << (top_h - 1))):
for child in (2 * leaf, 2 * leaf + 1):
order.extend(veb_order(bottom_h, child))
return order
def blocks_on_path(position, leaf, block):
"""Distinct blocks touched by the root-to-leaf path ending at `leaf`."""
seen = set()
node = leaf
while node >= 1:
seen.add(position[node] // block)
node //= 2
return len(seen)
def worst_case(height, block, layout):
if layout == "veb":
order = veb_order(height)
else:
order = list(range(1, 2 ** height)) # level order
position = {node: i for i, node in enumerate(order)}
leaves = range(2 ** (height - 1), 2 ** height)
return max(blocks_on_path(position, leaf, block) for leaf in leaves)
assert veb_order(3) == [1, 2, 4, 5, 3, 6, 7]
assert veb_order(4) == [1, 2, 3, 4, 8, 9, 5, 10, 11, 6, 12, 13, 7, 14, 15]
Running worst_case(20, B, layout) (a few seconds in CPython):
| B | log_B n (n ≈ 2²⁰) | vEB layout | Level order |
|---|---|---|---|
| 16 | 5.0 | 11 | 17 |
| 64 | 3.3 | 6 | 15 |
| 512 | 2.2 | 5 | 12 |
Level order costs h − log₂ B + 1 blocks: the top log₂ B levels share the first block, and then every level below costs a new block, because level d occupies 2^d consecutive slots and the path jumps further each time. That is Θ(log(n/B)), the same as binary search on a sorted array; for n much larger than B it is close to log₂ n, which is why Section 16.3’s table lists it as O(log n). Larger blocks barely help it: going from B = 16 to B = 512 saves only 5 blocks.
The vEB layout tracks log_B n within a small constant factor, and it improves steadily as B grows, without the code ever being told B. The constant comes from the argument in Section 16.3: the path crosses subtrees whose height is between ½ log₂ B and log₂ B, so it crosses at most about 2 log_B n of them, and an unaligned subtree of at most B nodes can straddle 2 blocks. A B-tree with node size exactly B would do better on its one tuned level (5, 4 and 3 levels here), which is the practical case for B-trees made in Section 16.3: the oblivious layout is within a constant of optimal at every level of the hierarchy at once, but on any single level a tuned structure beats it.
Where this connects
- Chapter 10: Multiway Search Trees and B-Trees. The B-trees this model exists to explain
- Chapter 22: Practical Considerations. Turning these findings into profiling decisions
Chapter 17: Persistent Data Structures
17.1 Persistence Defined
A persistent data structure preserves previous versions when modified.
Types:
- Partial persistence: Query old versions, update current
- Full persistence: Query and update any version
- Confluent persistence: Merge versions
Every structure so far has been ephemeral: modifying it destroys what was there before. Insert into a BST and the old tree is gone. Persistence removes that destruction. An update returns a new version while every old version remains valid and queryable.
The naive implementation is to copy the whole structure on every update, which is correct, obvious, and O(n) per operation in both time and space. The entire subject is about achieving persistence without paying that price. The key insight is that an update usually touches a small part of the structure, so the new version can share everything it did not touch with the old one.
The three levels of persistence form a strict hierarchy:
| Level | Query | Update | Version structure |
|---|---|---|---|
| Partial | Any version | Newest only | A line |
| Full | Any version | Any version | A tree |
| Confluent | Any version | Any version, plus merge | A DAG |
Confluent persistence is genuinely harder than the other two. When versions can merge, a node can be reachable by exponentially many paths, and the naive analysis of sharing breaks down.
Immutability is the enabling property. Sharing is only safe if shared nodes are never modified in place. Otherwise a change made through the new version would be visible through the old one, which is exactly what persistence is supposed to prevent. This is why persistent structures and functional programming arrived together.
17.2 Persistent BSTs
Share unchanged nodes on modification. Inserting 35 requires copying every node on the path from the root down to the insertion point, and only those nodes. Everything hanging off that path is shared with the previous version:
Before (version 1): After (version 2), inserting 35:
A(50) A(50) A'(50) ← new root
/ \ / \ / \
B(30) C(70) B(30) C(70) B'(30) │
/ / / \ │
D(10) D(10) D(10) E(35) │
↑ ↑ ↑ │
└──────────────┘ │ │
shared new shared
node (C(70))
Version 1 root = A, version 2 root = A'.
Copied: A → A', B → B'. New: E(35). Shared: D(10), C(70).
Note that B must be copied, not shared: its right-child pointer changes to point at the new node E. This is the part that is easy to get wrong. Any node whose pointers change must be copied; a node is only shareable if nothing about it changes. Since only nodes along the root-to-leaf path have changed children, exactly O(log n) nodes are copied in a balanced tree.
def insert(node, key):
"""Returns the root of a NEW version; `node` remains valid and unchanged."""
if node is None:
return Node(key, None, None)
if key < node.key:
return Node(node.key, insert(node.left, key), node.right) # copy, new left
elif key > node.key:
return Node(node.key, node.left, insert(node.right, key)) # copy, new right
return node # already present
v1 = build_tree([50, 30, 70, 10])
v2 = insert(v1, 35) # v1 still queryable, unchanged
v3 = insert(v2, 60) # three coexisting versions
There is no mutation anywhere in that function (it only ever constructs new nodes) which is what makes the old roots remain valid.
This is path copying, and its cost is the height of the tree:
| Operation | Time | Extra space per version |
|---|---|---|
| Insert / delete (balanced) | O(log n) | O(log n) |
| Query any version | O(log n) | n/a |
| Insert (unbalanced worst case) | O(n) | O(n) |
Balance matters more here than in the ephemeral case, because an unbalanced tree costs you both time and permanent space on every update. Red-black trees and AVL trees both path-copy cleanly; the rotations simply produce a few more copied nodes.
Path copying is not the only technique. Section 17.3 covers the two alternatives, fat nodes and node copying, which avoid copying the path at all.
17.3 Fat Nodes and Node Copying
Path copying pays for the whole root-to-leaf path because of a cascade: a changed pointer forces a copy of the node holding it, which changes a pointer in its parent, and so on up to the root. Driscoll, Sarnak, Sleator and Tarjan (“Making Data Structures Persistent”, STOC 1986; journal version 1989) asked the general question. Take any ephemeral pointer structure, where an update is a sequence of update steps (each writes one field of one node) and a query is a sequence of access steps (each reads one field). How cheaply can it be made persistent? They gave two answers, both of which stop the cascade at the first node.
Fat nodes
Never overwrite a field. Each field keeps its whole history as a list of (version, value) pairs. A write in version v appends (v, value); a read in version v takes the latest entry stamped ≤ v. Under partial persistence versions are numbered 1, 2, 3, … and writes only go to the newest version, so each history is sorted by construction and a read is a binary search.
from bisect import bisect_right
class FatNode:
"""A BST node whose child fields keep their whole history."""
def __init__(self, key):
self.key = key # never changes
self.left = ([0], [None]) # (version stamps, values), stamps ascending
self.right = ([0], [None])
def read(field, v):
stamps, values = field
return values[bisect_right(stamps, v) - 1] # last write stamped <= v: O(log m)
def write(field, v, value):
stamps, values = field
stamps.append(v) # v is the newest version, so order holds
values.append(value)
class FatBST:
"""Partially persistent BST: query any version, insert into the newest."""
def __init__(self):
self.roots = [None] # roots[v] is the root of version v
def insert(self, key):
v = len(self.roots) # the version this insert creates
root = self.roots[-1]
self.roots.append(root if root is not None else FatNode(key))
node = root
while node is not None and node.key != key:
field = node.left if key < node.key else node.right
child = read(field, v)
if child is None:
write(field, v, FatNode(key)) # the only change: one field entry
node = child
return v
def contains(self, key, v):
node = self.roots[v]
while node is not None and node.key != key:
node = read(node.left if key < node.key else node.right, v)
return node is not None
t = FatBST()
for k in [50, 30, 70, 10, 35]:
t.insert(k) # versions 1 to 5
assert t.contains(35, 5) and not t.contains(35, 4)
assert t.contains(10, 4) and not t.contains(10, 3)
Trace the same keys as Section 17.2. Each insert allocates one node and appends one entry to one field: version 4 writes B(30)’s left, version 5 writes B(30)’s right. After version 5, B’s right field holds stamps [0, 5] and values [None, E(35)]. The query contains(35, 4) reaches B and reads right at version 4: bisect_right([0, 5], 4) - 1 = 0, so it sees None and reports 35 absent. At version 5 the index is 1 and it finds E. Nothing was copied; A, B, C and D are the same objects in every version.
The bounds: O(1) worst-case space per update step (one appended pair), and an O(log m) slowdown per access step, where m is the number of writes to that field. A search of depth d in an old version costs O(d log m) rather than O(d). For full persistence the versions form a tree, so “latest version ≤ v” needs an order on that tree. DSST keep the versions in an order-maintenance list (a linear order consistent with the version tree, comparable in O(1)) and store each field’s history in a search tree under that order. The space stays O(1) per update step and the slowdown O(log m).
Node copying
Node copying keeps the O(1) space and removes the log factor, for partial persistence of structures with bounded in-degree: no node is pointed to by more than p nodes, for a constant p. A binary tree with parent pointers qualifies with p = 3 (a parent and two children point at each node).
Each node keeps the field values it was created with, plus a fixed number of modification slots, 2p of them, each holding (version, field, value). It also keeps up to p back pointers to the nodes that point at it in the newest version; those are only ever needed for the newest version, so they are overwritten in place.
- Read field f in version v: take the creation value, overridden by the latest slot for f stamped ≤ v. There are at most 2p slots, so this is O(1) worst case.
- Write field f in the newest version v: if the node has a free slot, fill it. If all 2p are full, make a copy holding the newest value of every field (with this write applied) and no slots in use. Each of the at most p nodes that point at the old node, found through its back pointers, must now point at the copy in version v, and the copy’s children get their back pointers redirected to it. Redirecting a predecessor is a write to its field, done by this same procedure, so it may fill a slot or cascade into another copy. If the copied node was the root, the copy becomes version v’s root.
The cascade can run far, but it cannot run often. Let c be the cost of copying a node (a constant, since nodes have bounded size) and let the potential be Φ = c × (number of filled slots in nodes of the newest version). Claim: every write has amortized cost at most 2c.
- Free slot: actual cost at most c, and Φ rises by c. Amortized: at most 2c.
- Full node: the copy costs c. The old node leaves the newest version and takes its 2p filled slots with it, so Φ falls by 2pc; the copy starts with none. Then come at most p recursive writes, each amortized at most 2c by induction. Amortized: at most c − 2pc + p · 2c = c.
So each update step costs O(1) amortized time and space (copies are the only space beyond the slots), and each access step costs O(1) worst case: no slowdown at all. This is the headline DSST result: any pointer structure with bounded in-degree can be made partially persistent with O(1) amortized overhead per update step and O(1) per access step. Their node splitting method extends it to full persistence with the same amortized bounds.
A red-black tree insertion performs O(1) amortized update steps (at most two rotations and O(1) amortized recolorings), so a node-copying persistent red-black tree costs O(1) amortized space per insertion, against O(log n) for path copying. Sarnak and Tarjan used exactly this for planar point location. Sweep a vertical line across a planar subdivision with n edges, keeping the edges that cross the line in a persistent search tree; each vertex the sweep passes creates a new version. That is O(n) space in total, and a query takes O(log n): binary-search the x-coordinate to pick the version, then search that version’s tree by y.
Comparing the three
| Path copying | Fat nodes | Node copying | |
|---|---|---|---|
| Space per update | Length of the path: O(log n) in a balanced tree | O(1) worst case per update step | O(1) amortized per update step |
| Time per access step | O(1) | O(log m) | O(1) |
| Old versions’ nodes | Never touched | Histories grow in place | Slots filled in place |
| Purely functional | Yes | No | No |
| Level | Full | Partial; full with an ordered version list | Partial; full by node splitting |
| Restriction | No parent or back pointers | None | Bounded in-degree |
The restriction on path copying is real: if children point back at their parent, copying a node forces a copy of each child (its parent pointer must now lead to the copy), then of their children, and the copying spreads to the whole structure. That is why persistent trees in functional languages have no parent pointers.
Path copying still wins in practice, for reasons the asymptotics do not show. It never writes to memory an old version can see, so readers of old versions need no synchronization (the property Section 17.7 builds on) and it works in languages with no mutation at all. A version nobody references can be reclaimed by the garbage collector, while fat nodes and node copying embed every version’s history inside nodes that stay live. And it is a few lines of code. Fat nodes and node copying are the theory’s answer, and the right tool when space per update is what matters, as in the point-location sweep. Chapter 24 (Section 24.9) sketches a fat-node modification log at the research level.
17.4 Persistent Arrays and HAMTs
Trees path-copy naturally because they are already logarithmic-depth pointer structures. Arrays do not. A persistent array cannot copy 1,000,000 elements per write.
The standard solution is to stop using a flat array and use a wide, shallow tree instead, then path-copy that. Clojure’s persistent vector is a 32-way branching trie: with a branching factor of 32, a vector of a billion elements is only 6 levels deep, so an update copies 6 nodes of 32 pointers each rather than a billion elements. Depth is ⌈log₃₂ n⌉, which for any realistic n is at most 7. Close enough to constant that these are often described as “effectively O(1)” operations.
32-way trie holding 1,000,000 elements, 4 levels deep:
[root: 32 ptrs]
/ | \
[32 ptrs] [32 ptrs] [32 ptrs] ← copied only along the path
/ | | \
... [32 ptrs] ... ...
|
[32 values] ← leaf: the element lives here
Update one element: copy 4 nodes (~128 pointers), share everything else.
Inside the persistent vector
Three design decisions make this work in Clojure’s PersistentVector, and Scala’s immutable Vector uses the same 32-way radix layout.
Bit-partitioned indexing. Nodes have 2^b children (b = 5 gives 32), and every leaf except the last is full, so an index is a path. Read it b bits at a time from the top: in a three-level trie, index 13,399 = 01101 00010 10111 in binary goes to slot 13 of the root, slot 2 of the next node, and slot 23 of the leaf. Each level is a shift and a mask, (i >> level) & 31, with no comparisons and no keys stored.
Path copying. set(i, x) rebuilds the one node per level on that path and shares every other child pointer.
The tail. The last partial leaf (up to 32 elements) is kept outside the trie, in a separate tail array. An append that fits copies only the tail. Only every 32nd append pushes the full tail into the trie as a new leaf, path-copying O(log₃₂ n) nodes, and when the trie is completely full the root grows a level. The last elements, which stack-like code reads most, are found without entering the trie at all.
Here is a small version with the branching factor as a parameter. Nodes are tuples, so nothing is modified in place:
class PVector:
"""Bit-partitioned persistent vector (Clojure's design) with 2**bits-way nodes.
The last, possibly partial, leaf lives in `tail`, outside the trie."""
def __init__(self, bits=5, count=0, shift=None, root=(), tail=()):
self.bits, self.width, self.mask = bits, 1 << bits, (1 << bits) - 1
self.count, self.root, self.tail = count, root, tail
self.shift = bits if shift is None else shift # index bits above the leaf level
def _new(self, count, shift, root, tail):
return PVector(self.bits, count, shift, root, tail)
def _tail_offset(self): # index of tail[0]
if self.count < self.width:
return 0
return ((self.count - 1) >> self.bits) << self.bits
def __len__(self):
return self.count
def __getitem__(self, i):
if not 0 <= i < self.count:
raise IndexError(i)
if i >= self._tail_offset():
return self.tail[i - self._tail_offset()]
node = self.root
for level in range(self.shift, 0, -self.bits): # one chunk of bits per level
node = node[(i >> level) & self.mask]
return node[i & self.mask]
def set(self, i, x):
if not 0 <= i < self.count:
raise IndexError(i)
off = self._tail_offset()
if i >= off:
t = self.tail
return self._new(self.count, self.shift, self.root,
t[:i - off] + (x,) + t[i - off + 1:])
def assoc(node, level): # path copying: one new node per level
j = (i >> level) & self.mask
child = x if level == 0 else assoc(node[j], level - self.bits)
return node[:j] + (child,) + node[j + 1:]
return self._new(self.count, self.shift, assoc(self.root, self.shift), self.tail)
def append(self, x):
if len(self.tail) < self.width: # common case: copy only the tail
return self._new(self.count + 1, self.shift, self.root, self.tail + (x,))
# The tail is full: it becomes a leaf of the trie, and x starts a new tail.
if (self.count >> self.bits) > (1 << self.shift): # no room: grow a level
root = (self.root, self._path(self.shift, self.tail))
return self._new(self.count + 1, self.shift + self.bits, root, (x,))
return self._new(self.count + 1, self.shift,
self._push_tail(self.shift, self.root), (x,))
def _path(self, level, leaf): # fresh chain of one-child nodes
return leaf if level == 0 else (self._path(level - self.bits, leaf),)
def _push_tail(self, level, node):
j = ((self.count - 1) >> level) & self.mask # slot on the path to the new leaf
if level == self.bits:
child = self.tail
elif j < len(node):
child = self._push_tail(level - self.bits, node[j])
else:
child = self._path(level - self.bits, self.tail)
return node[:j] + (child,) + node[j + 1:]
The overflow test reads: after this push the trie holds count >> bits full leaves, and a trie whose root sits shift bits above the leaves has room for 2^shift of them.
With 4-way nodes (bits=2) the trie gets deep quickly, which makes the structure easy to see. Appending 0, 10, …, 200 gives 21 elements:
shift = 4, tail = (200,), tail offset 20
root ─┬─ [0] ─┬─ (0, 10, 20, 30) indices 0..3
│ ├─ (40, 50, 60, 70) 4..7
│ ├─ (80, 90, 100, 110) 8..11
│ └─ (120, 130, 140, 150) 12..15
└─ [1] ─── (160, 170, 180, 190) 16..19
The 21st append is the one that grew the root. Its tail (160 to 190) was full, the trie already held 4 leaves (= 2^2, full for shift = 2), so 20 >> 2 = 5 > 4: the old root became child 0 of a new root and a one-child path to the new leaf became child 1. Looking up index 13 = 00 11 01 takes slot 0, then slot 3, then slot 1: the value 130. set(13, -1) copies the root, node [0] and leaf 3, three tuples, and shares the other three leaves, node [1] and the tail:
v = PVector(bits=2) # 4-way nodes, so the trie gets deep fast
for i in range(21):
v = v.append(i * 10)
assert (v.shift, v.tail, len(v)) == (4, (200,), 21)
assert v[13] == 130 # 13 = 0b00_11_01: slots 0, 3, 1
w = v.set(13, -1)
assert v[13] == 130 and w[13] == -1 # v is untouched
assert w.root[1] is v.root[1] and w.root[0][0] is v.root[0][0] # shared, not copied
What “effectively constant” means. Lookup and update cost Θ(log₃₂ n) = Θ(log₂ n / 5). That is a constant factor of 5 fewer levels than a binary tree, not a different growth rate. The claim of “effectively O(1)” rests on the fact that n is bounded in practice: with 32-bit indices there are at most 7 levels (32 bits in 5-bit chunks), and by the same logic a balanced binary tree is “effectively at most 32 levels”. The concrete costs are what matter. A lookup is up to 7 dependent pointer loads where an array needs one (the top levels usually sit in cache, the lower ones often do not). An update allocates up to 7 nodes of 32 slots, a couple of hundred words, where an array writes one. Clojure and Scala offer transient vectors and builders for bulk construction, which mutate nodes that no other version can see yet and then freeze the result.
The design has one hard limit: the index arithmetic requires every leaf except the last to be full, so concatenating two vectors means re-appending one of them element by element, O(n), and a real slice from the middle has to be rebuilt the same way. (Clojure’s subvec is O(1) only because it returns a view that keeps the whole original alive.) RRB trees (relaxed radix balanced trees) allow some nodes to be less than full and store a small table of subtree sizes in those nodes, which gives O(log n) concatenation and splitting while keeping radix lookup on the full parts.
The Hash Array Mapped Trie (HAMT) applies the same structure to maps. Hash the key, then use 5 bits of the hash per level to index into a 32-wide node. The refinement that makes it space-efficient is a bitmap in each node marking which of the 32 slots are occupied, so a node with 3 children stores 3 pointers and a 32-bit mask rather than 32 mostly-null pointers. Population count on the bitmap converts a logical index to a physical one in one instruction.
HAMTs are the backbone of persistent maps in Clojure, Scala, and Haskell, and the same idea appears in Erlang and in immutable-collections libraries for JavaScript.
17.5 Persistent Queues: Amortization Meets Persistence
The functional queue is the two-stack queue of Exercise 5.5 (Chapter 5) built from immutable lists: a front list F, a rear list R holding the newest element first, enqueue conses onto R, dequeue takes from F, and when F runs out R is reversed to become the new F. Every element is reversed once, so n operations cost O(n): amortized O(1). Exercise 17.6 runs the experiment that breaks it. Take a version whose F is empty and whose R holds n elements, and call dequeue on that same version n times. Every call reverses all n elements and returns the result inside a new version that the caller throws away: n² work for n operations.
The analysis failed because it is a credit argument. Each cheap enqueue puts a coin in the bank, and the expensive reversal spends the coins. Under persistence a version has many futures, and every future spends the same coins. No credit argument survives that, because the same savings can be withdrawn any number of times.
Debits instead of credits
Okasaki’s repair turns the accounting around and changes the code to match. It has two ingredients.
- Lazy evaluation with memoization. The rotation is not performed. It is stored in the new version as a suspension, a thunk that runs the first time anyone needs its result and caches the answer. Every version derived from that one shares the same suspension object, so the work runs at most once, however many futures reach it.
- Schedule the expensive work early. Rotate as soon as R would become longer than F, building
F ++ reverse(R)lazily. The invariant |R| ≤ |F| puts the reversed part behind |F| elements, so on any path through the version tree, |F| dequeues must happen before anything can force it.
The accounting uses debits. When a suspension is created, its cost is recorded as a debt against it, and the rule is that it may only be forced after earlier operations have paid that debt off. If two futures each do their |F| dequeues, the debt is paid twice, which is harmless overpayment; memoization guarantees the real cost is incurred only once. Credits can be double-spent; debits can only be double-paid. That asymmetry is the whole idea.
For this banker’s queue the bookkeeping is concrete. Number the cells of F from 0 and let D(i) be the total debt on cells 0 through i. The invariant is
D(i) ≤ min(2i, |F| − |R|)
- Cell 0 always carries zero debt, so the dequeue that forces it is allowed.
- An enqueue that does not rotate lowers |F| − |R| by one, so it pays off 1 debit.
- A dequeue moves every cell one place forward (lowering 2i by 2) and lowers |F| − |R| by one, so it pays off 2 debits.
- A rotation happens when |R| reaches |F| + 1, with |F| = m. Just before that enqueue, |F| = |R| = m, so the invariant forced every D(i) to 0: the old front was fully paid for. The rotation puts 1 debit on each of the first m cells (each step of the lazy append is a small suspension) and m + 1 on cell m (the reversal), so D(i) = i + 1 for i < m and D(m) = 2m + 1. The enqueue pays the debit on cell 0, leaving D(i) = i ≤ 2i and D(m) = 2m ≤ min(2m, 2m + 1). The invariant holds again.
Every operation does O(1) unshared work and pays at most 2 debits, so the banker’s queue is O(1) amortized per operation, under any pattern of persistent use.
Python is strict, so laziness has to be simulated. A Susp holds a thunk and memoizes it, and a stream is a Susp whose value is None or a (head, stream) pair:
class Susp:
"""A memoized thunk: the computation runs at most once, ever."""
def __init__(self, thunk):
self.thunk, self.value = thunk, None
def force(self):
if self.thunk is not None:
self.value, self.thunk = self.thunk(), None
return self.value
def ready(cell):
"""A stream cell that is already evaluated."""
s = Susp(None)
s.value = cell
return s
EMPTY = ready(None) # a stream is a Susp whose value is None or (head, stream)
steps = 0 # counts reversal work, for the experiments below
def append(s, t):
"""Lazy s ++ t: each cell costs O(1), paid only when that cell is forced."""
def cell():
c = s.force()
return t.force() if c is None else (c[0], append(c[1], t))
return Susp(cell)
def reverse(lst):
"""Lazy but monolithic: the first force reverses the whole cons list."""
def run():
global steps
out, rest = EMPTY, lst
while rest is not None:
steps += 1
out, rest = ready((rest[0], out)), rest[1]
return out.force()
return Susp(run)
# A banker's queue is (len_f, front stream, len_r, rear cons list), len_r <= len_f.
EMPTY_Q = (0, EMPTY, 0, None)
def check(lf, f, lr, r):
if lr <= lf:
return (lf, f, lr, r)
return (lf + lr, append(f, reverse(r)), 0, None) # rotate early, lazily
def enqueue(q, x):
lf, f, lr, r = q
return check(lf, f, lr + 1, (x, r))
def dequeue(q):
lf, f, lr, r = q
x, rest = f.force()
return x, check(lf - 1, rest, lr, r)
Now attack it the way Exercise 17.6 attacks the naive queue. Enqueue 0 to 1022, which rotates at |R| = 1, 2, 4, …, 512 and leaves |F| = 1023, |R| = 0. Dequeue down to the version p whose next dequeue must force the 512-element reversal, and replay that dequeue from p a thousand times:
q = EMPTY_Q
for i in range(1023):
q = enqueue(q, i) # rotations at |R| = 1, 2, 4, ..., 512
assert steps == 0 # nothing has been reversed yet: all lazy
p = q
for i in range(511):
x, p = dequeue(p) # p: the 512-element reversal is next in line
assert steps == 511 # the smaller reversals, 1 + 2 + ... + 256
for _ in range(1000):
x, _ = dequeue(p) # replay the expensive dequeue 1000 times
assert x == 511
assert steps == 1023 # the big reversal ran once, not 1000 times
Every element was reversed exactly once in total. Change force to rerun the thunk on every call instead of caching it, and the replay loop alone does 512,000 reversal steps, 512 per call: the failure of the naive queue again. Memoization alone is not enough either: Exercise 17.8 keeps it but rotates only when F is empty, and a replay attack comes back. The two ingredients only work together.
Real-time queues
A worst-case bound needs no accounting at all, and no usage pattern can break it: if no operation ever costs more than c, replaying one costs at most c too. Hood and Melville (1981) made the functional queue O(1) worst case by doing the reversal a few steps at a time. Okasaki (1995) found a much simpler construction from the same lazy pieces:
- Make the rotation incremental.
rotate(f, r, acc)computesf ++ reverse(r) ++ accone O(1) cell at a time, moving one element of r onto the accumulator for each cell of f. It needs |r| = |f| + 1 so that the reversal finishes exactly when f does, and that is exactly when the banker’s queue rotates. - Keep a schedule. A pointer s to the first unevaluated cell of the front, with |s| = |F| − |R|. Every operation forces exactly one cell of s and advances it. When s runs out, |R| = |F| + 1 and the next rotation starts.
The schedule forces each cell of the front before any dequeue reaches it, so no operation does more than one O(1) step of rotation: O(1) worst case per operation, persistent or not.
def rotate(f, r, acc):
"""Lazy f ++ reverse(r) ++ acc, one O(1) step per cell. Needs |r| == |f| + 1."""
def cell():
global steps
steps += 1
c = f.force()
y, r_rest = r
if c is None: # r has exactly one element left
return (y, acc)
return (c[0], rotate(c[1], r_rest, ready((y, acc))))
return Susp(cell)
# A real-time queue is (front stream, rear cons list, schedule), |schedule| == |f| - |r|.
RT_EMPTY = (EMPTY, None, EMPTY)
def exec1(f, r, s):
c = s.force() # force exactly one cell of the front
if c is not None:
return (f, r, c[1])
f = rotate(f, r, EMPTY) # schedule used up: |r| == |f| + 1
return (f, None, f)
def rt_enqueue(q, x):
f, r, s = q
return exec1(f, (x, r), s)
def rt_dequeue(q):
f, r, s = q
x, rest = f.force()
return x, exec1(rest, r, s)
A test that operates on randomly chosen old versions, checks every answer against a plain list, and measures the most rotation work any single call does:
import random
versions = [(RT_EMPTY, [])] # (queue, the list it should hold)
worst = 0
for _ in range(20000):
q, ref = random.choice(versions) # operate on ANY old version
before = steps
if ref and random.random() < 0.45:
x, q2 = rt_dequeue(q)
assert x == ref[0]
versions.append((q2, ref[1:]))
else:
versions.append((rt_enqueue(q, len(versions)), ref + [len(versions)]))
worst = max(worst, steps - before)
assert worst == 1 # never more than one rotate step per call
In practice the banker’s queue is usually faster, because it does less bookkeeping per operation; the real-time queue is for code where a latency bound matters more than throughput. Both are why a lazy functional language can offer an O(1) persistent queue without any mutation.
17.6 Finger Trees
A deque, an indexable sequence, a priority queue, an ordered set and an interval tree are usually five structures. Hinze and Paterson’s 2-3 finger tree (2006) is one persistent structure that provides all five, by changing one parameter.
Shape. A finger tree is empty, a single element, or a Deep node holding a prefix and a suffix of 1 to 4 elements each (the “fingers”), plus a middle finger tree whose elements are 2-3 nodes (Node2 or Node3) of the outer element type. The middle’s middle holds nodes of nodes, so level k of the spine holds complete 2-3 trees of depth k. The ends of the sequence sit at the top of the structure, which is the point: the elements touched most are the cheapest to reach.
To push x onto the back, add it to the suffix if the suffix has fewer than 4 elements. If the suffix is full, [a, b, c, d], it becomes [d, x] and Node3(a, b, c) is pushed onto the back of the middle tree, by the same rule one level down. Pushing 1 to 10 in order:
after 5: Deep [1] Empty [2, 3, 4, 5]
after 6: Deep [1] (Single N3(2,3,4)) [5, 6]
after 9: Deep [1] (Deep [N3(2,3,4)] Empty [N3(5,6,7)]) [8, 9]
after 10: Deep [1] (Deep [N3(2,3,4)] Empty [N3(5,6,7)]) [8, 9, 10]
Costs. A push reaches the middle only when a digit is full, and it leaves that digit with two elements, so that level overflows again only after three more pushes; deeper levels are reached geometrically less often, like the carries of a counter. Pushes and pops at either end are amortized O(1). Hinze and Paterson keep the middle tree lazy and use the debit argument of Section 17.5, so these bounds hold under persistent use. Concatenation is O(log(min(n₁, n₂))) and splitting at position i is O(log(min(i, n − i))); both work down the spine, regrouping the loose digit elements into 2-3 nodes at each level.
Measures. Each node caches a measure of its subtree, taken from a monoid: an associative operation ⊕ with an identity element. The measure of a node is the ⊕ of its children’s measures, left to right, so it is maintained in O(1) whenever a node is built. A split with a predicate that is false and then true as elements are added left to right walks down the tree, skipping every digit and subtree whose cached measure does not flip the predicate.
With the size measure (each element measures 1, ⊕ is +), finding index 6 (0-based, the element 7) in the tree above goes: the outer prefix [1] measures 1, which is ≤ 6, so skip it and look for index 5 in the middle; the middle’s prefix N3(2,3,4) measures 3, which is ≤ 5, so skip it and look for index 2; the middle’s middle is empty; the middle’s suffix starts with N3(5,6,7), and index 2 inside it is 7. Three cached measures were consulted and no element was scanned one by one.
Changing the monoid changes the structure:
| Element measure, ⊕, identity | Split predicate | Result |
|---|---|---|
| 1, +, 0 | running size > i | Indexable sequence: index, split and concatenate in O(log n). This is Haskell’s Data.Sequence. |
| priority, max, −∞ | running max ≥ max of the whole tree | Max-priority queue: the root’s measure is the maximum, and split finds and removes it in O(log n). |
| key, “rightmost key”, no key | running key ≥ k | Ordered sequence (elements kept sorted): insert, delete and search by key in O(log n), and merge. |
| (low, high), componentwise max, (−∞, −∞) | running max high ≥ q | Interval tree (intervals sorted by low endpoint): the first interval reaching q contains q if its low endpoint is ≤ q, and otherwise no interval does. |
The table is the real contribution. The tree code is written once against an abstract monoid, and each structure is a few lines of instance declaration. Here is what split computes, written as a linear scan so the semantics are easy to check; the finger tree computes exactly this in O(log n) by skipping subtrees whose measures cannot flip the predicate:
from collections import namedtuple
Monoid = namedtuple("Monoid", "identity op measure")
def split(m, pred, xs):
"""What a finger tree split computes: the first x at which pred becomes true
on the running measure. The tree does it in O(log n) by skipping subtrees
whose cached measure cannot flip pred; this reference version scans."""
acc = m.identity
for i, x in enumerate(xs):
acc = m.op(acc, m.measure(x))
if pred(acc):
return xs[:i], x, xs[i + 1:]
return xs, None, []
size = Monoid(0, lambda a, b: a + b, lambda x: 1)
priority = Monoid(float("-inf"), max, lambda job: job[1])
interval = Monoid((float("-inf"), float("-inf")), # (largest low, largest high)
lambda a, b: (max(a[0], b[0]), max(a[1], b[1])),
lambda iv: iv)
assert split(size, lambda n: n > 3, list("finger")) == (list("fin"), "g", list("er"))
jobs = [("a", 3), ("b", 9), ("c", 4), ("d", 9)]
top = max(p for _, p in jobs) # in the tree: the root's cached measure, O(1)
assert split(priority, lambda p: p >= top, jobs)[1] == ("b", 9)
ivs = [(1, 4), (2, 3), (5, 9), (6, 7)] # kept sorted by low endpoint
_, hit, _ = split(interval, lambda m: m[1] >= 6, ivs)
assert hit == (5, 9) and hit[0] <= 6 # first interval reaching 6; it contains 6
The low-endpoint half of the interval measure is not used by this query. It is the ordered-sequence key, used to split by low endpoint when inserting a new interval in its sorted place.
In practice. Haskell’s Data.Sequence (in the containers library) is a finger tree specialised to the size measure, with O(1) length, O(log(min(i, n − i))) indexing and O(log(min(n₁, n₂))) concatenation, and the fingertree package exposes the general measured version. The price is constant factors: each Deep node, its digits and their cached measures are several allocations per element, so for plain stack or queue use, a list or the banker’s queue is faster. The finger tree is for when one sequence needs several of these operations at once.
17.7 Functional Data Structures
Functional languages favor immutable structures:
- Thread-safe by default
- Undo/redo trivial
- Predictable performance
Examples:
- Clojure’s persistent vectors
- Haskell’s persistent maps
- Scala’s immutable collections
Each of those bullets deserves unpacking, because they are the practical reasons persistence is worth its overhead.
Thread-safe by default is the big one. Every concurrency hazard in Chapter 18 (torn reads, lost updates, iterator invalidation) comes from one thread mutating what another is reading. If nothing is ever mutated, there is nothing to synchronize. Readers need no locks at all, and a writer publishes a new version with a single atomic pointer swap. This is why Clojure’s concurrency story is as simple as it is.
Undo/redo becomes free. Keeping a stack of old roots is the undo history; no command objects, no inverse operations, no replay. Editors and CAD tools built on persistent structures get unlimited undo as a side effect of the data model.
Predictable performance cuts both ways honestly. Persistent structures avoid the latency spikes of a dynamic array’s O(n) resize, but they allocate constantly, which puts pressure on the garbage collector. The constant factors are genuinely worse than mutable equivalents, typically 2–4× for a HAMT versus a good mutable hash table.
Where persistence earns its cost:
- Version control. Git is a persistent data structure, which is exactly why committing a one-line change to the Linux kernel does not copy the kernel (details below).
- Databases. MVCC (multi-version concurrency control) in PostgreSQL is partial persistence: readers see a consistent snapshot at their transaction’s start while writers proceed, without either blocking the other (details below). CouchDB and Datomic go further and keep every version permanently.
- Filesystems. ZFS and Btrfs are copy-on-write; a snapshot is just a retained old root, which is why it is instant and initially free.
- UI frameworks. React’s rendering model assumes immutable props, so change detection is a reference comparison rather than a deep traversal.
- Debugging. Time-travel debuggers replay old versions directly, because they still exist.
The cost side, stated plainly: 2–4× slower on write-heavy single-threaded workloads, higher memory use and allocation churn, and worse cache locality than a flat array. The wide-trie designs mitigate that last one but do not eliminate it. Persistence is the right default in concurrent and versioned settings, and the wrong one in a tight numerical loop.
Persistence in the wild: Git and MVCC
Git’s object store is built from four object types, each named by the hash of its content (SHA-1, or SHA-256 in repositories created with that option). A blob is a file’s bytes, a tree is a directory listing of (mode, name, hash) entries, a commit names one root tree and its parent commits, and a tag names another object. Edit src/lib/util.c and commit, and Git writes a new blob, new trees for src/lib, src and the root, and a new commit. That is path copying, with the directory path as the path; every other blob and tree is shared, by hash, with the parent commit.
Naming objects by content adds two things path copying alone does not give. Sharing is global rather than only along history: identical files anywhere, in any commit, are one blob, and reverting a file reuses its old blob. And equal hashes mean equal subtrees, which makes the store a Merkle DAG (the structure Dynamo uses to compare replicas in Chapter 31): git diff skips any pair of subtrees whose hashes match without opening them, and git fetch transfers only the objects the other side lacks. Merge commits have two parents, so the history is confluent (Exercise 17.1). A branch is a mutable name for an immutable root, the same atomic root pointer as above, and git gc is a garbage collector: it deletes objects that no branch, tag or reflog entry can reach. (Packfiles also delta-compress objects on disk; that is storage compression, separate from the structural sharing.)
MVCC keeps old versions of rows so that readers can work from a snapshot. PostgreSQL never overwrites a row in an UPDATE: it writes a new row version, and each version records the transaction that created it (xmin) and the one that superseded or deleted it (xmax). A reader compares those stamps against its snapshot to decide which version it sees. That is the fat node method of Section 17.3 applied per row, version-stamped values with a lookup for the newest one visible at the reader’s version, and like fat nodes the history accumulates in place, so PostgreSQL needs VACUUM to reclaim versions no snapshot can still see. InnoDB and Oracle instead update rows in place and keep old versions in undo logs, rebuilding an older row by applying undo records backwards. LMDB takes the path-copying route: its B+ tree is copy-on-write, a write transaction copies the root-to-leaf paths it touches and publishes a new root, and a reader keeps using the root it started with. Spanner’s timestamped row versions and Delta Lake’s versioned table log are covered in Chapter 31 (Sections 31.1 and 31.4).
17.8 Historical Context
Driscoll, Sarnak, Sleator, and Tarjan’s 1986 paper “Making Data Structures Persistent” (journal version 1989) is the foundational work. It defined partial and full persistence and introduced fat nodes, node copying and node splitting, proving that any pointer-based structure with bounded in-degree can be made partially or fully persistent with O(1) amortized time and space per update step and no slowdown on access. That is a much stronger and more general result than the path-copying technique most implementations actually use. Sarnak and Tarjan applied it the same year to planar point location with persistent search trees. Confluent persistence was named later, by Driscoll, Sleator and Tarjan in their work on catenable lists (1994), and Brodal (1996) made the update cost of bounded-degree partial persistence O(1) in the worst case.
Chris Okasaki’s Purely Functional Data Structures (1998), which grew out of his 1996 CMU thesis, addressed the complementary question: which structures can be implemented efficiently without any mutation at all? His treatment of amortization under persistence is the subtle part. The usual credit argument breaks when an expensive operation can be re-executed by replaying an old version, and Okasaki’s solution using lazy evaluation and memoization (Section 17.5) is why the book remains standard reading. Hood and Melville had made functional queues O(1) worst case in 1981 by spreading the reversal over many operations; Okasaki’s 1995 real-time queue reached the same bound much more simply with lazy evaluation and a schedule.
Finger search trees, which keep a “finger” at a position of interest so that nearby searches are fast, go back to Guibas, McCreight, Plass and Roberts (1977). Ralf Hinze and Ross Paterson’s 2-3 finger trees (2006) brought the idea into purely functional programming, with a monoid annotation that made one structure serve as sequence, priority queue and search tree; Haskell’s Data.Sequence is built on it.
Phil Bagwell introduced the Hash Array Mapped Trie in 2001. Rich Hickey built Clojure’s collections on it and on the 32-way bit-partitioned vector in 2007, which more than anything else moved persistent structures from a functional-programming specialty into general practice. Bagwell and Tiark Rompf’s RRB trees (2011) added efficient concatenation to those vectors. Git, written by Linus Torvalds in 2005, put a content-addressed persistent structure in front of most working programmers.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
17.1 ★ Which level of persistence? Classify each system as partial, full, or confluent persistence, and name the shape of its version history (line, tree, or DAG).
- PostgreSQL MVCC, as described in 17.7: a transaction reads the snapshot that existed when it started, and writers only ever modify the current state.
- An editor with an undo tree (Vim and Emacs both have one): you can undo back to any earlier state, make a new edit there, and the abandoned branch stays reachable.
- Git, including merge commits.
- A ZFS filesystem with read-only snapshots.
Solution
| System | Level | Version history | Why |
|---|---|---|---|
| PostgreSQL MVCC | Partial | Line | Old snapshots are readable, but every write goes to the newest state. |
| Undo tree | Full | Tree | Editing an old state creates a new branch from it, so updates apply to any version. |
| Git | Confluent | DAG | A merge commit has two parents: two versions combine into one. |
| ZFS read-only snapshots | Partial | Line | Snapshots are retained old roots that can be read but not written; only the live filesystem changes. |
The ZFS answer changes if you use clones, which are writable copies of a snapshot. Writing to a clone updates an old version, which makes the history a tree: full persistence.
17.2 ★ Trace a second path copy. Start from the two versions in 17.2: v1 holds 50, 30, 70, 10, and v2 = insert(v1, 35). Now run v3 = insert(v2, 60). Which nodes does this call allocate? Which nodes does v3 share with v2, and which with v1? How many Node objects exist across all three versions, and how many would three full copies need?
Hint
Follow the search path for 60 from the root of v2. Only the nodes on that path are copied.
Solution
The search path for 60 in v2 is A’(50), then right to C(70), then left to an empty slot. So the call copies A’ and C and allocates one new leaf:
v3 root = A''(50)
/ \
B'(30) C'(70) A'', C' are copies; F(60) is new
/ \ /
D(10) E(35) F(60)
- Allocated by this call: A’‘(50), C’(70), F(60). That is 3 nodes: 2 copies plus the new leaf.
- Shared with v2: B’(30), D(10), E(35). v3’s left subtree is exactly v2’s left subtree, the same objects.
- Shared with v1: only D(10). Every other v1 node (A, B, C) has since been replaced on some copied path.
Totals: v1 has 4 nodes, v2 added 3 (A’, B’, E), v3 added 3 (A’‘, C’, F), so 10 Node objects back all three versions. Three independent copies would need 4 + 5 + 6 = 15.
17.3 ★★ Find the bug. A colleague wants persistence without writing a recursive copy, so they copy the root and then reuse an existing in-place insert:
def _insert_mutating(node, key):
"""Ordinary ephemeral BST insert: modifies the tree in place."""
if key < node.key:
if node.left is None:
node.left = Node(key, None, None)
else:
_insert_mutating(node.left, key)
elif key > node.key:
if node.right is None:
node.right = Node(key, None, None)
else:
_insert_mutating(node.right, key)
def insert(root, key):
if root is None:
return Node(key, None, None)
new_root = Node(root.key, root.left, root.right) # copy the root...
_insert_mutating(new_root, key) # ...then insert into the copy
return new_root
Build v1 holding 50, 30, 70 with the chapter’s correct insert, then call v2 = insert(v1, 20) with this one. What does an in-order traversal of v1 print afterwards? Why did the colleague’s tests, which inserted into a one-node tree and checked both versions, pass?
Hint
The new root is a copy, but its child pointers are not. What object does new_root.left point at?
Solution
v1 prints [20, 30, 50, 70]: the “old” version has the new key in it.
new_root.left is the same node 30 that v1’s root points at. _insert_mutating walks from new_root to that shared 30 and sets its left field in place, so the change is visible through both roots. Persistence is broken for every insert that lands two or more levels below the root.
The one-node test passed by accident. Inserting 40 into a tree holding only 50 attaches the new leaf directly to new_root, which really is a fresh copy, so v1 is untouched. The bug only appears when the modified node is below the root.
The fix is the rule from 17.2: every node whose pointers change must be copied, and that is every node on the root-to-insertion path, not just the root. The chapter’s recursive insert does exactly that by building a new node at each level of the recursion. A good regression test records the in-order keys of every old version and asserts they never change after later operations.
17.4 ★★ The price of an unbalanced persistent tree. Insert the keys 1, 2, …, n in increasing order into the chapter’s path-copying BST (no balancing), keeping every version. Exactly how many Node objects are allocated in total? Evaluate it for n = 1000 and compare with an ephemeral BST and with a balanced persistent tree.
Solution
When key k is inserted, the current tree is a right-leaning chain 1 → 2 → … → k−1, and the search path for k visits all k−1 nodes. Each of them gets a new right pointer, so all are copied, plus one new leaf: k allocations for the k-th insert.
Total: 1 + 2 + … + n = n(n+1)/2, which is Θ(n²). For n = 1000 that is 500,500 nodes, all of them reachable from some retained version, so none can be freed.
An ephemeral BST fed the same input allocates 1,000 nodes (it is just as slow, Θ(n²) comparisons, but it does not keep the waste). A balanced persistent tree copies O(log n) nodes per insert, so O(n log n) in total: on the order of n log₂ n ≈ 10,000 for n = 1000, plus a few extra copies per rotation. Even random insertion order into the unbalanced tree averages about 750 allocations for n = 100, against 5,050 for sorted input.
This is the point of the line in 17.2 that balance matters more under persistence: an unbalanced ephemeral tree wastes time, but an unbalanced persistent tree also turns that time into permanent memory.
17.5 ★★ HAMT bitmap indexing. A HAMT node stores a 32-bit bitmap (bit i set means logical slot i is occupied, bit 0 is least significant) and a compact array holding only the occupied children, in slot order. One node has bitmap 0b10110010 and children ['a', 'b', 'c', 'd'].
- Which logical slots are occupied, and which child is in each?
- Look up slot 5 and slot 6.
- Write
physical_index(bitmap, slot),lookup(bitmap, children, slot), andwith_child(bitmap, children, slot, child). The last one must return a new bitmap and children list without modifying the inputs, since the old node may be shared with an older version. What does adding child'x'at slot 3 produce?
Hint
The physical position of slot s is the number of occupied slots below s, which is a population count of the bitmap masked to bits 0 through s−1.
Solution
- Bits 1, 4, 5, and 7 are set, so slot 1 →
'a', slot 4 →'b', slot 5 →'c', slot 7 →'d'. - Slot 5: bit 5 is set. The bits below it are
0b10010(bits 1 and 4), popcount 2, so the answer ischildren[2] == 'c'. Slot 6: bit 6 is clear, so the slot is empty and the lookup fails without touching the array. - The three functions:
def physical_index(bitmap, slot):
return bin(bitmap & ((1 << slot) - 1)).count("1")
def lookup(bitmap, children, slot):
if not (bitmap >> slot) & 1:
return None
return children[physical_index(bitmap, slot)]
def with_child(bitmap, children, slot, child):
"""Return a NEW (bitmap, children); the inputs are not modified."""
i = physical_index(bitmap, slot)
if (bitmap >> slot) & 1: # replace
return bitmap, children[:i] + [child] + children[i + 1:]
return bitmap | (1 << slot), children[:i] + [child] + children[i:]
bm, ch = 0b10110010, ['a', 'b', 'c', 'd']
assert lookup(bm, ch, 5) == 'c' and lookup(bm, ch, 6) is None
bm2, ch2 = with_child(bm, ch, 3, 'x')
assert bm2 == 0b10111010 and ch2 == ['a', 'x', 'b', 'c', 'd']
assert ch == ['a', 'b', 'c', 'd'] # old node intact
assert lookup(bm2, ch2, 5) == 'c' # index shifted, lookup still right
Adding slot 3: one occupied slot (slot 1) lies below it, so 'x' goes at physical index 1. The new bitmap is 0b10111010 and the new array is ['a', 'x', 'b', 'c', 'd']. Note that 'b', 'c', and 'd' all moved one position right, yet lookups still find them, because the physical index is recomputed from the bitmap every time. In production code the popcount is a single instruction (int.bit_count() in Python 3.10+, POPCNT on x86).
17.6 ★★★ Amortization breaks under persistence. Here is the classic two-list queue made persistent with immutable cons cells: None is the empty list and (head, tail) is a cell.
steps = 0
def reverse(lst):
global steps
out = None
while lst is not None:
steps += 1
head, lst = lst
out = (head, out)
return out
def enqueue(q, x):
front, back = q
return (front, (x, back)) # O(1)
def dequeue(q):
front, back = q
if front is None: # front ran out: reverse back into front
front, back = reverse(back), None
x, front = front
return x, (front, back)
Ephemerally, this queue is O(1) amortized: each element is moved by reverse once. Enqueue 0 through n−1 into (None, None) to get version q. Then (a) dequeue all n elements in a chain, always using the latest version, and (b) call dequeue(q) n times on the same version q. How many reverse steps does each pattern take? Explain what went wrong with the amortized argument, and how Okasaki’s approach from Section 17.5 repairs it.
Hint
In pattern (b), does the work done by one call’s reverse help the next call?
Solution
In q, front is empty and back holds all n elements.
- (a) Chain: the first dequeue reverses n cells, producing a version whose
frontholds the rest. The next n−1 dequeues pop from thatfrontwith no reversal. Total: n steps, O(1) amortized, exactly as in the ephemeral analysis. - (b) Replay: every call receives the same
qwith an emptyfront, so every call reverses all n cells again. The reversed list built by one call is returned inside that call’s new version, which the caller discards. Total: n² steps, O(n) per operation.
Measured with n = 1000: 1,000 steps for (a), 1,000,000 for (b).
The amortized argument charges the expensive reversal to the n cheap enqueues that preceded it, which works only if that “credit” is spent once. Persistence lets you return to version q as often as you like, and each return spends the same credit again. Any amortized bound that relies on an expensive operation happening rarely is vulnerable in the same way.
Okasaki’s fix is to make the expensive work shared rather than repeated. The reversal is created as a lazy suspension stored inside the version itself and memoized when it is first forced, and the queue creates it early (as soon as the back list grows longer than the front) so that enough cheap operations have already paid for it. Every version that descends from q holds the same suspension object, so whichever one forces it first pays, and the rest reuse the memoized result. The debt is paid once per version, not once per use, and O(1) amortized holds even under persistence. Section 17.5 builds this queue (the banker’s queue) and proves the bound.
17.7 ★★ Index arithmetic in a 32-way vector. A PVector from Section 17.4 with the default bits=5 holds n = 1,000,000 elements, built by appending 0, 1, 2, … in order.
- Where does the tail start, how many elements does it hold, what is
shift, and how many children does the root have? - Which slot does
v[777_777]take at each level? - How many nodes does
v.set(777_777, x)copy, and how many slots do the copies hold in total? - Of the 1,000,000 appends, how many pushed a tail into the trie, and how many grew a new root level?
Solution
- The tail offset is ((1,000,000 − 1) >> 5) << 5 = 31,249 × 32 = 999,968, so the tail holds the 32 elements 999,968 to 999,999. The trie holds the other 999,968 elements in 31,249 full leaves. Since 32² = 1,024 < 31,249 ≤ 32³ = 32,768, three levels of internal nodes sit above the leaves:
shift = 15. Each root child covers 1,024 leaves, so the root has ⌈31,249 / 1,024⌉ = 31 children. - 777,777 is below the tail offset, so it is in the trie. In binary it is
10111 10111 10001 10001: slot 23 of the root, slot 23 of the next node, slot 17 of the next, and slot 17 of the leaf. Check: 23 × 32,768 + 23 × 1,024 + 17 × 32 + 17 = 777,777. - One node per level: the root (31 slots), two internal nodes (32 each) and the leaf (32), so 4 nodes and 127 slots. A mutable array writes 1 slot; copying the whole vector would write 1,000,000.
- An append pushes the tail exactly when the tail is full, which happens when the current count is a positive multiple of 32: counts 32, 64, …, 999,968, so 31,249 pushes, one per leaf. The root grows when the number of leaves passes 2^shift: from 32 to 33 leaves (shift 5 to 10) and from 1,024 to 1,025 (shift 10 to 15), so twice. The other 968,751 appends copied only the tail.
17.8 ★★★ Memoization is not enough. Keep Susp, append, reverse, enqueue and dequeue from Section 17.5, but change check to rotate only when the front is empty, the way the naive queue does. Used single-threaded, this is still O(1) amortized. Find a persistent usage pattern that makes it cost Θ(n) per operation, measure it for n = 1000, and explain why the banker’s check, which rotates as soon as |R| > |F|, is immune to the same pattern.
Hint
Memoization only saves work when two futures force the same suspension. Which call creates the rotation suspension, and how soon after can it be forced?
Solution
Enqueue 0 to n − 1. The first enqueue sees an empty front and rotates [0] into it; the rest go to the rear, leaving |F| = 1, |R| = n − 1. Now, from that same version q, dequeue twice, over and over. The first dequeue empties the front, so its check builds a rotation suspension inside the version it returns. That is a new object on every call, shared with no other future, so memoization never gets a chance. The second dequeue forces it at once: n − 1 reversal steps per round.
def check(lf, f, lr, r): # replaces the check of Section 17.5
if lf > 0:
return (lf, f, lr, r)
return (lr, append(f, reverse(r)), 0, None) # rotate only when F is empty
n = 1000
q = EMPTY_Q
for i in range(n):
q = enqueue(q, i)
assert (q[0], q[2]) == (1, n - 1) # 0 was rotated into the front at once
steps = 0
for _ in range(n):
_, q1 = dequeue(q) # empties the front: builds a NEW rotation
dequeue(q1) # ...and forces it immediately
assert steps == 999_001 # 999 per round, plus 1 for the first rotation
The banker’s check defeats this because of where it puts the work. A rotation created by any operation sits behind all |F| elements of the front, so a future must perform |F| more dequeues before it can force that rotation, and those dequeues pay its debits. A pattern that keeps going back to q and creating fresh rotations never gets far enough to force them. Running the same loop with the banker’s check (where q has |F| = 511 and |R| = 489) does 3 reversal steps in total. Laziness makes repeated work shareable; early scheduling guarantees that unshared work has been paid for before it runs.
17.9 ★★ Pick the measure. A music player keeps a playlist as a finger tree of (title, seconds) songs, and needs both (a) “which song is playing t seconds into the playlist, and how far into it?” and (b) “what is the i-th song?” in O(log n), from one tree. Give the monoid and the two split predicates, and check them with the reference split from Section 17.6 on [("Intro", 95), ("Blue", 240), ("Static", 185), ("Coda", 60)].
Hint
A pair of monoids, combined componentwise, is again a monoid.
Solution
Measure each song as the pair (1, seconds), combine pairs by adding componentwise, with identity (0, 0). Associativity and the identity law hold in each component, so they hold for the pair. Every song adds at least 1 to the count and a non-negative duration, so the running totals never decrease and each predicate below flips from false to true exactly once, which is what split needs.
- (a) Split where the running seconds exceed t. The song found is playing, and it started at the total seconds of the left part, which the tree has as the measure of that part.
- (b) Split where the running count exceeds i.
songs = [("Intro", 95), ("Blue", 240), ("Static", 185), ("Coda", 60)] # (title, seconds)
both = Monoid((0, 0), lambda a, b: (a[0] + b[0], a[1] + b[1]),
lambda song: (1, song[1])) # (count, total seconds)
def playing_at(t): # (a): the song playing t seconds in
left, song, _ = split(both, lambda m: m[1] > t, songs)
played = sum(s for _, s in left) # in the tree: the measure of `left`
return song[0], t - played # title, and how far into it we are
assert playing_at(0) == ("Intro", 0)
assert playing_at(95) == ("Blue", 0)
assert playing_at(400) == ("Static", 65)
assert split(both, lambda m: m[0] > 2, songs)[1][0] == "Static" # (b): song index 2
At t = 400 the running seconds are 95, 335, 520: the first to exceed 400 is “Static”, which started at 335, so it is 65 seconds in. The same tree also supports moving a song (split it out, concatenate it elsewhere) in O(log n) while keeping both answers correct, because every node’s cached pair is rebuilt as the tree is reassembled.
Where this connects
- Chapter 18: Concurrent Data Structures. The concurrency hazards immutability removes outright
- Chapter 7: Binary Search Trees. The BST being made persistent here
- Chapter 5: Stacks and Queues. The two-stack queue whose amortized bound Section 17.5 rebuilds to survive persistence
- Chapter 31: Real-World Case Studies. MVCC in Spanner and the versioned table log of Delta Lake
Chapter 18: Concurrent Data Structures
18.1 Thread Safety
Concurrent access requires synchronization.
Correctness criteria:
- Linearizability: Each operation appears atomic
- Sequential consistency: Operations match program order
- Lock-freedom: At least one thread progresses
- Wait-freedom: All threads progress in bounded steps
To see why these criteria are needed, look at what breaks without them. Consider two threads pushing onto the singly linked stack from Chapter 5:
void push(Stack *s, Node *n) {
n->next = s->head; // (1) read head
s->head = n; // (2) write head
}
Thread A executes (1) and is preempted. Thread B runs both lines and pushes its node. Thread A resumes and executes (2), overwriting head with a node whose next still points at the old head. Thread B’s node is gone: silently, with no error, no crash, and no way to detect it later. That is a lost update, and it happens because the read and the write were not one indivisible step.
The two properties above address different questions:
Safety. What results are legal. Linearizability is the standard: every operation appears to take effect instantaneously at some point between its call and its return, and that ordering is consistent with real time. It matters because it composes. Linearizable components can be combined and the result stays reasonable, which is not true of weaker conditions like sequential consistency.
Liveness: whether threads make progress. These form a hierarchy:
| Guarantee | Promise | Cost |
|---|---|---|
| Blocking | None, a stalled thread can block everyone | Cheapest, simplest |
| Obstruction-free | A thread running alone finishes | Weak in practice |
| Lock-free | Some thread always makes progress | System-wide throughput; individual threads may starve |
| Wait-free | Every thread finishes in bounded steps | Strongest; usually the slowest in the common case |
The distinction that matters in production: with locks, a thread that is descheduled, page-faults, or crashes while holding a lock stalls every other thread indefinitely. Lock-free structures cannot suffer that failure mode. This matters far more in a real-time or kernel context than in a typical server, which is worth remembering before reaching for lock-free code.
18.2 Lock-Free Techniques
Compare-and-Swap (CAS) is the primitive everything else is built from. Its semantics are: atomically, compare the value at an address to an expected value, and if they match, replace it with a new value. Report whether the swap happened.
The critical word is atomically. This is a single indivisible hardware instruction (LOCK CMPXCHG on x86, LDREX/STREX or CAS on ARM), not something you can write in plain C. The following is what CAS is specified to do, and is emphatically not a valid implementation, since the read and the write can be interleaved by another thread exactly as in the lost-update example above:
/* SPECIFICATION ONLY. This is what the hardware does atomically.
Written like this in plain C it is a race, not a CAS. */
bool cas_semantics(int *addr, int expected, int new_value) {
if (*addr == expected) { // ← another thread can run between
*addr = new_value; // these two lines
return true;
}
return false;
}
The real thing comes from the compiler or the standard library:
#include <stdatomic.h>
/* C11: compiles to a single LOCK CMPXCHG on x86.
On failure, `expected` is updated with the actual value. */
bool ok = atomic_compare_exchange_weak(&head, &expected, new_value);
The standard usage pattern is a retry loop: read the current value, compute the new one, attempt to swap, and start over if someone beat you to it.
void lock_free_push(_Atomic(Node*) *head, Node *n) {
Node *old_head = atomic_load(head);
do {
n->next = old_head;
} while (!atomic_compare_exchange_weak(head, &old_head, n));
/* If the CAS fails, old_head now holds the current value; retry. */
}
No thread ever waits for another. A failed CAS means someone else succeeded, which is why this is lock-free rather than wait-free: the system always progresses, but one unlucky thread could in principle retry forever.
The ABA problem is the classic trap. CAS checks whether a value is unchanged, but what you actually care about is whether the state is unchanged, and those differ. Thread A reads head = X. Thread B pops X, pops Y, then pushes X back. Thread A’s CAS on X succeeds (the pointer matches) but the list beneath it is now completely different, and A may splice in a node pointing at freed memory.
The standard defenses:
- Tagged pointers: pack a counter alongside the pointer and CAS both together (a double-width CAS,
LOCK CMPXCHG16B). The counter increments on every update, so a recycled pointer no longer compares equal. - Hazard pointers: each thread publishes the pointers it is currently dereferencing; memory is not reclaimed while any hazard pointer references it.
- Epoch-based reclamation / RCU: defer reclamation until every thread has passed through a quiescent state.
- Garbage collection: in a GC’d language, ABA via memory reuse largely disappears, which is why lock-free code is considerably easier to write correctly in Java than in C.
Memory reclamation is the hard part of lock-free programming in a non-GC language, and it is where most bugs live. Removing a node from a lock-free structure is easy; knowing when no other thread can still be reading it is not. This is the single strongest argument for using a well-tested library rather than writing your own.
Memory ordering is the other subtlety. Modern CPUs and compilers reorder memory operations aggressively. Correct lock-free code requires explicit ordering constraints. memory_order_acquire on loads that must see prior writes, memory_order_release on stores that must be visible to subsequent readers. Defaulting to memory_order_seq_cst is correct and slower; anything weaker demands genuine care. x86 has a strong memory model that hides many mistakes; the same code on ARM or POWER then fails in production, which is a well-known way to ship a bug.
18.3 Concurrent Data Structures
| Structure | Implementation | Technique |
|---|---|---|
| Counter | Atomic operations | CAS |
| Stack | Lock-free | CAS on head |
| Queue | Michael-Scott | Head/tail pointers with CAS |
| Hash map | Segmented locks | Lock per bucket |
| Skip list | Lock-free | CAS on pointers |
The Michael–Scott queue (1996) is the standard lock-free FIFO and repays study. It keeps separate head and tail pointers with a permanent dummy node so that the empty case needs no special handling, and enqueue proceeds in two CAS steps: first link the new node to the current last node, then advance the tail pointer.
Between those two steps the queue is in an intermediate state where tail lags one node behind reality. The trick that makes this work is that any thread which observes the lagging tail helps fix it before proceeding:
void enqueue(Queue *q, Node *n) {
n->next = NULL;
while (1) {
Node *tail = atomic_load(&q->tail);
Node *next = atomic_load(&tail->next);
if (tail != atomic_load(&q->tail)) continue; // stale, re-read
if (next != NULL) {
/* Someone else is mid-enqueue, so help them finish. */
atomic_compare_exchange_weak(&q->tail, &tail, next);
continue;
}
if (atomic_compare_exchange_weak(&tail->next, &next, n)) {
atomic_compare_exchange_weak(&q->tail, &tail, n); // may fail; fine
return;
}
}
}
That final CAS is allowed to fail, because if it does, some other thread has already performed the fix-up. This helping pattern (threads completing each other’s partial operations rather than waiting) is the general technique for building lock-free structures with multi-step updates.
Concurrent hash maps are where most real applications actually meet this material, and the design has evolved:
- One global lock: correct, trivially, and a bottleneck at any real concurrency.
- Lock striping: N independent locks, bucket i guarded by lock
i mod N. Java’sConcurrentHashMapused 16 segments by default through Java 7. Simple and effective. - Per-bucket locking with lock-free reads: Java 8 onward CASes into empty buckets and locks only the first node of a non-empty one, while reads are entirely lock-free over
volatilefields. Reads scale perfectly; writes contend only on the exact bucket. - Split-ordered lists (Shalev and Shavit, 2006): a genuinely lock-free hash table that supports resizing without ever blocking. Resizing being the operation that makes concurrent hash tables hard, since it touches everything at once.
Concurrent skip lists are worth knowing because they are why ConcurrentSkipListMap exists while a concurrent balanced BST does not. Insertion is local (CAS a few forward pointers) whereas a red-black tree rebalance rotates nodes far from the insertion point, which is very hard to do lock-free. Randomized structure buys concurrency. This is the same trade that makes skip lists attractive in MemSQL, LevelDB’s memtable, and Redis sorted sets.
Read-Copy-Update (RCU) deserves separate mention because it is the dominant technique inside the Linux kernel. Readers pay nothing at all: no atomics, no barriers on most architectures, literally just a dereference. Writers copy the structure, modify the copy, and atomically swap the pointer, then wait for a grace period before freeing the old version. It is the right answer for the extremely common read-mostly case, and the wrong one for write-heavy workloads.
18.4 When Not to Go Lock-Free
Lock-free programming is one of the easiest ways to write code that is subtly, intermittently, unreproducibly wrong. Before choosing it, work down this list:
- Don’t share. Thread-local state, sharding, or message passing eliminates the problem instead of solving it. This is by far the best option when it applies.
- Use immutable data. Persistent structures (Chapter 17) need no synchronization for readers at all.
- Use a plain lock. An uncontended mutex costs ~20ns. Correct, readable, and fast enough for the overwhelming majority of code.
- Use a well-tested concurrent library.
ConcurrentHashMap,folly::ConcurrentHashMap,crossbeam,java.util.concurrent. These were written by specialists and tested for years. - Only then write lock-free code yourself, and only with model checking or stress testing under a race detector (TSan,
loomin Rust, JCStress in Java). Reasoning alone is not sufficient; neither is testing on x86 alone.
The honest summary: lock-free structures win on tail latency and on immunity to a stalled thread, not usually on average throughput. A striped lock frequently beats a hand-rolled lock-free structure on both performance and correctness.
18.5 Historical Context
Leslie Lamport defined sequential consistency in 1979 and produced the first lock-free queue (for one reader and one writer) in 1977. Maurice Herlihy and Jeannette Wing introduced linearizability in 1990, giving the field its correctness criterion.
Herlihy’s 1991 paper “Wait-Free Synchronization” is the theoretical foundation: it established the consensus hierarchy, proving that primitives have a consensus number (the maximum number of threads for which they can solve consensus) and that atomic read/write registers have consensus number 1, while compare-and-swap has consensus number ∞. That result is why CAS is the universal primitive and why hardware designers ship it: with CAS you can build a wait-free implementation of any object, and without something like it you provably cannot.
Maged Michael and Michael Scott published their queue in 1996; it went into java.util.concurrent and has been the reference lock-free FIFO ever since. Michael followed with hazard pointers in 2004, addressing the reclamation problem. Paul McKenney’s RCU work brought the read-mostly approach into the Linux kernel from 2002 onward, where it is now used in tens of thousands of places.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
18.1 ★ Classify the progress guarantee. For each, say whether it is blocking, lock-free (but not wait-free), or wait-free, using the table in 18.1.
- A counter protected by a mutex.
lock_free_pushfrom 18.2.- A spinlock built from CAS:
int zero = 0; while (!atomic_compare_exchange_weak(&lock, &zero, 1)) { zero = 0; }, followed by a critical section andatomic_store(&lock, 0). - An RCU reader that loads the current pointer and reads through it.
Solution
- Blocking. If the holder is descheduled inside the critical section, every other thread waits.
- Lock-free, not wait-free. A failed CAS means another thread’s push succeeded, so the system as a whole progresses. But a single thread can lose the race on every attempt, so its own step count is unbounded.
- Blocking. Using CAS does not make an algorithm lock-free. A thread that acquires the spinlock and is then preempted stalls every other thread, which spins forever. The progress guarantee is a property of the algorithm, not of the instructions it uses.
- Wait-free. The reader performs a fixed number of its own steps (a load and a dereference) and never retries or waits, regardless of what writers do. Writers are a different story: they wait for a grace period.
18.2 ★ Lost update, then fixed. The stack is head → X → Y. Thread A calls push(P) and thread B calls push(Q) using the unsynchronized push from 18.1. They interleave as A(1), B(1), B(2), A(2). Draw the final list. Then replay the same scheduling idea with lock_free_push from 18.2: A loads old_head and sets P->next, B runs its whole push, then A attempts its CAS. What happens, and what is the final list?
Solution
Unsynchronized:
| Step | Effect | State |
|---|---|---|
| A(1) | P->next = head (X) | P → X |
| B(1) | Q->next = head (X) | Q → X |
| B(2) | head = Q | head → Q → X → Y |
| A(2) | head = P | head → P → X → Y |
Final list: P → X → Y. Q still points at X but nothing points at Q, so B’s push is lost.
With lock_free_push: A loads old_head = X and sets P->next = X. B completes its push, so head = Q. A’s CAS compares head (Q) with old_head (X), fails, and writes Q into old_head. A loops: P->next = Q, and the CAS now succeeds. Final list: P → Q → X → Y. Both pushes survive, and A paid one extra loop iteration.
18.3 ★★ ABA, step by step. Here is the matching lock-free pop (C11, ignoring memory reclamation):
Node *pop(_Atomic(Node*) *head) {
Node *old = atomic_load(head);
while (old && !atomic_compare_exchange_weak(head, &old, old->next))
;
return old;
}
The stack is A → B → C. Thread 1 calls pop, loads old = A, evaluates old->next (B) as the CAS argument, and is preempted just before the CAS executes. Thread 2 then pops A, pops B and frees B, and pushes A back (reusing the node). (a) What does the stack look like after thread 2? (b) What happens when thread 1’s CAS runs? (c) Show how a tagged pointer, where the tag increments on every successful CAS, changes the outcome. (d) Is there a problem tagging does not fix?
Hint
The CAS compares only the pointer value. After thread 2 finishes, is head equal to A?
Solution
(a) After thread 2: popping A leaves B → C, popping B leaves C, pushing A sets A->next = C. The stack is A → C, and B’s memory has been freed.
(b) Thread 1’s CAS compares head (A) with old (A). They match, so it installs its stale argument B: head now points at freed memory, and C has dropped out of the stack. The next pop dereferences a dangling pointer.
(c) With tags, head is a (pointer, tag) pair swapped by a double-width CAS:
| Event | head |
|---|---|
| Initial | (A, 0) |
| Thread 1 reads | (A, 0) |
| Thread 2 pops A | (B, 1) |
| Thread 2 pops B | (C, 2) |
| Thread 2 pushes A | (A, 3) |
| Thread 1 CAS expects (A, 0) | fails, reloads (A, 3) |
| Thread 1 retries with next = C | (C, 4), returns A |
The final stack is C, which is correct: A was popped twice and pushed once, B was popped once.
(d) Tagging prevents the wrong CAS, but thread 1 still read old->next from a node that another thread could have freed. If A itself had been freed and returned to the operating system, that read is a use-after-free even though the CAS would later fail. Preventing that requires a reclamation scheme (hazard pointers, epochs, or a garbage collector), which is why 18.2 calls reclamation the hard part.
18.4 ★★ Helping in the Michael–Scott queue. The queue holds only its dummy node D: D->next == NULL and head == tail == D. Thread A calls enqueue(X). Its CAS on D->next succeeds, and A is preempted before its final CAS on q->tail. Thread B now calls enqueue(Y) and runs to completion. Trace each iteration of B’s loop, then say what happens when A resumes. What is the final state? Why must B help rather than wait for A?
Solution
State when A stops: D → X, tail == D (lagging by one).
B, iteration 1: tail = D, next = D->next = X. The tail re-check passes. Since next != NULL, B performs A’s unfinished step: CAS(&q->tail, D, X) succeeds, tail == X. continue.
B, iteration 2: tail = X, next = NULL. B’s CAS(&X->next, NULL, Y) succeeds, linking Y. B’s CAS(&q->tail, X, Y) succeeds. B returns.
A resumes: it executes CAS(&q->tail, D, X). q->tail is Y, not D, so the CAS fails, and A returns. That failure is harmless because the work it would have done was already done by B.
Final state: D → X → Y, head == D, tail == Y. The FIFO order is X then Y, matching the order in which the linking CASes succeeded.
If B waited for A to advance the tail, then a preempted, page-faulting, or crashed A would stall B indefinitely, and the queue would be blocking: exactly the failure mode lock-freedom exists to rule out. Helping means any thread can finish any other thread’s half-done operation, so no thread ever depends on another being scheduled. (compare_exchange_weak may also fail spuriously; in every branch a failure just leads to a retry or leaves the tail lagging for the next operation to repair, so the algorithm stays correct.)
18.5 ★★ Lock striping by the numbers. A hash map has 256 buckets guarded by 16 locks, with bucket i under lock i mod 16, as in 18.3.
- Which buckets share a lock with bucket 37?
- Two threads each write one key at the same moment, with keys hashing uniformly. What is the probability they contend for a lock, under a global lock, under 16-way striping, and under per-bucket locking?
- With 8 threads writing simultaneously, what is the probability that at least two of them contend under 16-way striping?
- Why must a resize from 256 to 512 buckets acquire all 16 locks?
Solution
- 37 mod 16 = 5, so lock 5 guards buckets 5, 21, 37, 53, …, 245: the 16 buckets congruent to 5 mod 16.
- Global lock: 1 (they always contend). Striping: 1/16 ≈ 6%. Per-bucket: 1/256 ≈ 0.4%.
- This is the birthday problem. The chance all 8 land on distinct stripes is (16 × 15 × 14 × 13 × 12 × 11 × 10 × 9) / 16⁸ ≈ 0.121, so the chance of at least one collision is about 0.88. Sixteen stripes sounds like a lot until eight writers are active. In practice contention also depends on how long the lock is held, which is why short critical sections matter as much as stripe count.
- A resize reads every bucket and moves entries to buckets that are guarded by different stripes. If it held only some locks, a writer holding another stripe could insert into a bucket the resize has already copied, and that write would be lost when the old table is discarded. Holding all 16 stops the world for the duration of the resize, which is exactly the problem split-ordered lists were invented to avoid.
18.6 ★★ Design: a read-mostly configuration map. A service has 32 worker threads that look up configuration values about a million times per second in total. One background thread reloads the whole configuration once a minute. Choose among a single mutex around a hash map, ConcurrentHashMap, and an immutable map published through an atomic pointer (the RCU style from 18.3, using the persistent structures from Chapter 17). Justify the choice and state when it would be wrong.
Solution
Use the immutable map behind an atomic pointer. Readers do one acquire load of the pointer and then read an ordinary immutable map with no locks, no CAS, and no shared writes, so the 32 threads never touch a common cache line except the pointer itself, which is read-only between reloads. The writer builds a complete new map off to the side and publishes it with one release store. Old maps are reclaimed by the garbage collector or after an RCU grace period.
It also gives a property the other two lack: a reader that loads the pointer once sees a consistent snapshot of every key. With ConcurrentHashMap, a reader looking up two related keys during a reload can see one old value and one new.
The cost is on the write side: each update copies the map (O(n), or O(log n) per changed key with a HAMT). Once a minute, that is negligible.
- A single mutex serializes every lookup across 32 threads. Correct, and the worst option here.
ConcurrentHashMapworks and has lock-free reads, but buys fine-grained write concurrency this workload never uses, and loses snapshot consistency.
The choice flips if writes become frequent, for example a per-request counter in the same map. Copying the whole map on every write would then dominate, and ConcurrentHashMap (or sharding the counters per thread) is the right answer.
18.7 ★★★ A tiny model checker. 18.4 says reasoning alone is not enough; model checking explores every interleaving. Write outcomes(n_threads, increments) that returns every possible final value of a shared counter when each thread performs increments non-atomic increments, each made of two steps: r = counter (load) then counter = r + 1 (store). Report the results for (2, 1), (2, 2), and (2, 3). Explain why 1 is impossible with two increments per thread. Then change the increment to a CAS retry loop (load r, then CAS(counter, r, r + 1), retry on failure) and confirm only the correct total is reachable.
Hint
Recursively try every runnable thread as the next one to take a step. The state is the counter, each thread’s program counter, and each thread’s register.
Solution
def outcomes(n_threads, increments):
"""Every final counter value reachable when each thread runs
`increments` copies of: r = counter (load), counter = r + 1 (store)."""
results = set()
def explore(counter, pcs, regs):
# pcs[t] counts thread t's steps: even = about to load, odd = about to store
if all(pc == 2 * increments for pc in pcs):
results.add(counter)
return
for t in range(n_threads):
pc = pcs[t]
if pc == 2 * increments:
continue # thread t is done
new_pcs = pcs[:t] + (pc + 1,) + pcs[t + 1:]
if pc % 2 == 0: # load
explore(counter, new_pcs, regs[:t] + (counter,) + regs[t + 1:])
else: # store
explore(regs[t] + 1, new_pcs, regs)
explore(0, (0,) * n_threads, (0,) * n_threads)
return sorted(results)
assert outcomes(2, 1) == [1, 2]
assert outcomes(2, 2) == [2, 3, 4]
assert outcomes(2, 3) == [2, 3, 4, 5, 6]
For two threads with 2 or 3 increments each, every value from 2 up to the correct total is reachable. The low end is the surprising part: six increments can produce 2.
Why not 1 with two increments each? The final value is whatever the last store wrote, which is one more than some value loaded by the thread that made it. Suppose thread T makes the last store. That is T’s second store, and T’s second load happened after T’s first store had written a value of at least 1. Every store writes at least 1, so the counter is never 0 again after that point, and T’s second load returns at least 1. The last store therefore writes at least 2.
The CAS version: the store step only succeeds if the counter still holds the loaded value, and a failure sends the thread back to load.
def outcomes_cas(n_threads, increments):
results = set()
def explore(counter, pcs, regs, done):
if all(d == increments for d in done):
results.add(counter)
return
for t in range(n_threads):
if done[t] == increments:
continue
if pcs[t] == 0: # load
explore(counter, pcs[:t] + (1,) + pcs[t + 1:],
regs[:t] + (counter,) + regs[t + 1:], done)
elif counter == regs[t]: # CAS succeeds
explore(counter + 1, pcs[:t] + (0,) + pcs[t + 1:], regs,
done[:t] + (done[t] + 1,) + done[t + 1:])
else: # CAS fails: retry
explore(counter, pcs[:t] + (0,) + pcs[t + 1:], regs, done)
explore(0, (0,) * n_threads, (0,) * n_threads, (0,) * n_threads)
return sorted(results)
assert outcomes_cas(2, 2) == [4]
assert outcomes_cas(3, 1) == [3]
Every interleaving now ends at n × k. The search also terminates, even though a CAS loop can retry: a CAS fails only when some other thread’s CAS succeeded since the load, and the total number of successes is bounded. That is lock-freedom in miniature: retries happen, but only because the system made progress.
Real model checkers such as loom and JCStress do this same exhaustive (or systematically sampled) exploration, plus the reorderings that weak memory models allow, which this sketch ignores.
Where this connects
- Chapter 17: Persistent Data Structures. Immutability as the alternative to synchronisation
- Chapter 12: Hash Tables. The hash table these techniques are usually applied to
Chapter 19: Emerging and Specialized Structures
This chapter surveys directions the field is currently moving in. Some of these are mature enough to deploy today; others are research with an unclear path to production. Each entry says which. Where a topic gets a full treatment later in the book, this chapter gives the short version and points you there.
19.1 Fibonacci Heaps Revisited
Recent work has produced simpler implementations while maintaining theoretical bounds.
The Fibonacci heap from Chapter 9 is the standard example of a structure that wins on paper and loses in practice. Its O(1) amortized decrease-key improves Dijkstra’s algorithm from O(E log V) to O(E + V log V), which is asymptotically optimal for comparison-based implementations. Yet almost nobody uses one. The constant factors are large, the node structure is heavy (parent pointers, child lists, mark bits), and the cascading-cut logic is cache-hostile. A plain binary heap usually wins on real graphs, and a d-ary heap tuned to the cache line usually wins by more.
The response has been a search for structures with the same bounds and less machinery:
- Pairing heaps (Fredman et al., 1986) are dramatically simpler (a single multiway tree with a
mergeoperation) and fast in practice. Their exact amortizeddecrease-keycomplexity was an open problem for two decades; it is now known to be O(log log n), not O(1), yet they still beat Fibonacci heaps on essentially every real workload. - Rank-pairing heaps (Haeupler, Sen, Tarjan, 2011) achieve the full Fibonacci bounds with substantially simpler restructuring.
- Strict Fibonacci heaps (Brodal, Lagogiannis, Tarjan, 2012) attain the same bounds in the worst case rather than amortized: theoretically significant for real-time systems, still not competitive in practice.
The durable lesson is the one from Chapter 1: asymptotic superiority is a claim about behavior in a limit, and the limit may sit far beyond any input you will ever see.
Status: mature theory, rarely deployed. Use a binary or d-ary heap unless profiling proves decrease-key dominates.
19.2 Succinct Data Structures
Store data in space close to the information-theoretic minimum:
- Operations directly on compressed representation
- Rank, select, navigation
A succinct structure uses Z + o(Z) bits, where Z is the information-theoretic minimum, while still supporting fast queries: crucially, without decompressing. That last property is what separates succinct structures from ordinary compression: gzip achieves better ratios but you must decompress before you can query.
The canonical example: a binary tree of n nodes takes 2n + o(n) bits succinctly, against roughly 128n bits for a pointer-based representation with two 64-bit pointers per node. That is a 64× reduction, and it turns “this index does not fit in RAM” into “this index fits in RAM”, which is a far bigger performance win than any constant-factor speedup.
Everything is built on two primitives over a bit vector:
rank(i): how many 1s occur before position iselect(k): the position of the k-th 1
Both answer in O(1) using auxiliary structures occupying o(n) extra bits. Tree navigation, string search, and set membership all reduce to these two operations.
Chapter 24 covers the machinery properly: LOUDS, balanced parentheses, DFUDS, wavelet matrices, and the FM-index.
Status: deployed where memory is the binding constraint. Genomic aligners (BWA, Bowtie) index the human genome with FM-indexes. Succinct tries back autocomplete at scale. The Rust succinct and C++ sdsl-lite libraries are production-quality.
19.3 External Memory Hash Tables
For massive datasets that don’t fit in memory:
- Cuckoo hashing on disk
- Buffered repository trees
A hash table’s defining virtue is that a lookup is one random probe. On disk, one random probe is a ~10ms seek, and the virtue becomes the defect, which is why disk-resident indexes are overwhelmingly B-trees rather than hash tables, as Chapter 16 explains.
The techniques that make hashing viable in external memory all amount to trading probes for batching:
- Linear hashing and extendible hashing grow one bucket at a time rather than rehashing everything, so a resize never stalls. Both date to 1979–80 and both are still in use: linear hashing indexes Berkeley DB and, more recently, PostgreSQL hash indexes.
- Cuckoo hashing on disk bounds lookups to a constant number of probes (two, in the basic scheme), which matters far more when a probe is 10ms than when it is 100ns. The cost is expensive insertions when eviction chains grow long.
- Buffered repository trees and B^ε-trees buffer updates in internal nodes and flush them down in batches, converting many random writes into few sequential ones. This is the same insight as the LSM tree, arrived at from the theory side. TokuDB and its successor, Percona’s fractal tree indexes, shipped it commercially.
Status: mature. The interesting modern development is that NVMe changes the calculus. A random read on NVMe is ~10μs rather than ~10ms, which narrows the gap between hash and tree indexes considerably and is quietly reopening design questions that were settled in the disk era.
19.4 Learned Indexes
Machine learning for index structures:
- Replace B-trees with neural networks
- Can be faster for certain access patterns
- Active research area
The idea, from Kraska et al.’s 2018 paper “The Case for Learned Index Structures,” is a genuine reframing: an index is a function from key to position, and a model can approximate a function. If your keys are integers 1 to 100,000,000 stored in order, the “index” is position = key − 1, no tree needed. Real data is not that clean, but real data is rarely random either, and a model that captures the shape of the key distribution can beat a structure that assumes nothing about it.
A learned index predicts a position, then does a bounded local search to correct the prediction. The Recursive Model Index stages simple models (usually linear regressions, not neural networks, because inference must cost nanoseconds) with each stage narrowing the range.
Reported results are strong: up to 3× faster lookups at a fraction of the memory of a B-tree. The caveats are equally real, and they are what keeps this out of most production systems:
- Updates are the hard part. The original design was read-only. ALEX (2020) and PGM-index (2020) support updates, but a distribution shift may require retraining.
- Worst-case bounds vanish. A B-tree is O(log n) on adversarial input. A learned index is fast on data resembling its training distribution and can degrade badly otherwise.
- Sorted data is the precondition. The technique assumes a sorted array underneath; it accelerates the search, it does not replace the storage.
Status: active research, early production. The PGM-index has strong theoretical guarantees and a usable implementation. Learned bloom filters and learned cache-eviction policies are seeing more real adoption than learned indexes proper.
19.5 Delta Encoding and CRDTs
Conflict-free replicated data types for distributed systems:
- Eventual consistency
- No coordination needed
- Used in collaborative applications
A CRDT is a structure whose merge operation is commutative, associative, and idempotent. Those three algebraic properties are the entire trick: if merging is order-independent and repeat-safe, replicas that receive the same updates in any order, possibly more than once, provably converge to the same state. With no coordination, no consensus, and no leader.
That means a CRDT keeps working while partitioned. In CAP terms it chooses AP and gets convergence anyway, by restricting itself to operations that cannot conflict.
The building blocks, in increasing order of difficulty:
| CRDT | Merge rule | Use |
|---|---|---|
| G-Counter | Per-replica counts, take max, sum | Metrics |
| PN-Counter | Two G-Counters (increments, decrements) | Counters that decrease |
| G-Set | Union | Append-only sets |
| LWW-Register | Highest timestamp wins | Last-writer-wins fields |
| OR-Set | Unique tags per add; remove tags observed | Sets with removal |
| RGA / Logoot / Yjs | Ordered identifiers between elements | Collaborative text |
Delta CRDTs address the practical problem with the basic formulation: naive state-based CRDTs ship the entire state on every sync, which is untenable for a large document. Delta CRDTs transmit only the changed portion while preserving the convergence properties.
Collaborative text editing is the demanding case, since concurrent inserts at the same position must produce a consistent order without a coordinator. Yjs and Automerge are the mature implementations, and both are fast enough for real editors: Yjs handles documents with millions of operations.
Chapter 27 develops the theory and the distributed-systems context.
Status: production-ready and spreading fast. Figma, Linear, Apple Notes, and Redis’s conflict-free replicated types all ship CRDTs. This is the most immediately practical topic in this chapter.
19.6 Structures for Vector Search
One significant omission from the original survey, added because it went from research to ubiquitous in roughly three years.
Embedding models turn text, images, and audio into high-dimensional vectors (typically 384 to 1,536 dimensions) and searching them means approximate nearest neighbor over millions of points. Chapter 15 explained why KD-trees collapse at these dimensionalities. The structures that work instead:
- HNSW (Hierarchical Navigable Small World, Malkov and Yashunin, 2016) builds a layered proximity graph and greedily descends it. A skip list where the “links” are nearest neighbors. It is the default in most vector databases: excellent recall, fast queries, high memory use, awkward deletion.
- IVF (inverted file index) clusters vectors and searches only the nearest clusters. Lower memory, tunable recall.
- Product quantization compresses vectors into compact codes, letting billion-scale indexes fit in RAM at some accuracy cost. Usually combined with IVF.
- ScaNN (Google, 2020) uses anisotropic quantization tuned for inner-product search specifically.
Status: production, moving very fast. FAISS, hnswlib, pgvector, Pinecone, Weaviate, Qdrant, and Milvus all ship these. Every retrieval-augmented LLM application depends on one.
19.7 Reading the Frontier
A few honest heuristics for evaluating structures like these, since most novel structures do not survive contact with production:
What tends to succeed solves a problem created by a hardware or workload shift. LSM trees won because write amplification on flash mattered. HNSW won because embeddings created a genuinely new query type. CRDTs won because collaborative editing became a product requirement.
What tends to fail improves an asymptotic bound while worsening constants, requires the workload to be well-behaved, or optimizes something that was not the bottleneck. Fibonacci heaps are the enduring cautionary example.
Questions worth asking of any new structure: What is the constant factor, measured? How does it behave on adversarial input? Does it support updates, or only bulk builds? What happens at the cache and page level? Is there a tested implementation, or only a paper?
That last question filters out most of them.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
19.1 ★ Rank and select by hand. Take the bit vector below, with positions numbered from 0, rank(i) counting the 1s strictly before position i, and select(k) giving the position of the k-th 1 (counting k from 1).
position: 0 1 2 3 4 5 6 7 8 9
bit: 1 0 1 1 0 0 1 0 1 1
- Compute
rank(4),rank(7), andrank(10). - Compute
select(1),select(4), andselect(6). - Check that
rank(select(k)) = k − 1for those three values of k, and say why it holds in general. - 19.2 compares 2n bits against 128n bits for a binary tree. Put numbers on that for a tree of 100 million nodes.
Solution
rank(4)counts positions 0 to 3: bits 1, 0, 1, 1, so 3.rank(7)adds positions 4 to 6 (0, 0, 1): 4.rank(10)counts the whole vector: 6.- The 1s sit at positions 0, 2, 3, 6, 8, 9. So
select(1) = 0,select(4) = 6,select(6) = 9. rank(0) = 0,rank(6) = 3,rank(9) = 5, which are k − 1 for k = 1, 4, 6. In general,select(k)is the position of the k-th 1, and exactly k − 1 ones come strictly before it.- Pointers: 128 × 10⁸ bits = 1.6 × 10⁹ bytes = 1.6 GB. Succinct: 2 × 10⁸ bits = 25 MB, plus the o(n) rank/select directories (typically a few percent to a quarter of that). That is the 64× reduction from 19.2: the succinct tree fits in RAM on a laptop, while the pointer version needs a machine sized for it.
19.2 ★★ When does the Fibonacci heap’s bound pay? Estimate Dijkstra’s operation counts with a binary heap, O((V + E) log V), and a Fibonacci heap, O(E + V log V), for (a) a road network with V = 10⁶ and E = 4 × 10⁶, and (b) a dense graph with V = 10⁴ and E = 5 × 10⁷. Treat each bound as an exact operation count with log₂. By what factor would a Fibonacci heap operation have to be slower than a binary heap operation for the binary heap to win in each case? What does the estimate leave out?
Solution
log₂ 10⁶ ≈ 19.9 and log₂ 10⁴ ≈ 13.3.
| Graph | Binary heap (V + E) log V | Fibonacci heap E + V log V | Ratio |
|---|---|---|---|
| Road, V = 10⁶, E = 4 × 10⁶ | 5 × 10⁶ × 19.9 ≈ 1.0 × 10⁸ | 4 × 10⁶ + 2.0 × 10⁷ ≈ 2.4 × 10⁷ | ≈ 4.2 |
| Dense, V = 10⁴, E = 5 × 10⁷ | ≈ 6.6 × 10⁸ | 5 × 10⁷ + 1.3 × 10⁵ ≈ 5.0 × 10⁷ | ≈ 13 |
On the road network, the binary heap wins if a Fibonacci heap operation costs more than about 4× as much. That is easily exceeded: the Fibonacci heap’s heavy nodes, pointer-chased child lists, and cascading cuts miss cache where an array-backed binary heap does not. On the dense graph the theoretical advantage is about 13×, which is where Fibonacci heaps have a real case. But at that density the plain unsorted-array version from Chapter 21 costs V² = 10⁸ simple scans with no heap at all, which is competitive with both.
What the estimate leaves out: the binary heap bound charges a log V decrease-key to every edge, but in practice only a fraction of relaxations improve a distance, so the binary heap does much less work than (V + E) log V. That narrows the gap further, and it is the main reason the 19.1 advice is “use a binary or d-ary heap unless profiling proves decrease-key dominates”.
19.3 ★★ A learned index by hand. A sorted array holds 12 keys at positions 0 to 11:
keys: 2 3 5 7 11 13 17 19 23 29 31 37
The model is the straight line through the first and last points: pos(k) = 11 × (k − 2) / 35, rounded to the nearest integer.
- Compute the predicted position of every key and the maximum error ε.
- Describe a lookup for 23 and for 24 (absent) using the prediction plus a bounded local search.
- Now append the key 1000 at position 12 and refit the line through the endpoints. What happens to ε, and which caveat from 19.4 does this illustrate?
Hint
The local search only has to cover positions within ε of the prediction, so its cost is O(log ε), not O(log n).
Solution
- Predictions (unrounded, then rounded) and errors:
| Key | 2 | 3 | 5 | 7 | 11 | 13 | 17 | 19 | 23 | 29 | 31 | 37 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Exact | 0.00 | 0.31 | 0.94 | 1.57 | 2.83 | 3.46 | 4.71 | 5.34 | 6.60 | 8.49 | 9.11 | 11.00 |
| Rounded | 0 | 0 | 1 | 2 | 3 | 3 | 5 | 5 | 7 | 8 | 9 | 11 |
| True | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| Error | 0 | 1 | 1 | 1 | 1 | 2 | 1 | 2 | 1 | 1 | 1 | 0 |
So ε = 2.
-
Lookup 23: predict 7, then binary search positions 5 to 9 (7 ± 2) and find 23 at position 8. Lookup 24: predict round(6.91) = 7, search positions 5 to 9, and conclude it is absent because 23 < 24 < 29 are adjacent. Each lookup is one multiply-add plus a binary search over 2ε + 1 = 5 slots, no matter how large the array is.
-
With 1000 appended, the line is
pos(k) = 12 × (k − 2) / 998. Every original key now predicts less than 0.5, so all of them round to position 0, and key 37 (true position 11) is off by 11: ε jumped from 2 to 11, and the “bounded” search now covers the whole original array. One outlier wrecked the model. That is the caveat “worst-case bounds vanish”: a B-tree’s cost does not depend on the key distribution, while a learned index is only as good as its fit. Practical designs such as the RMI and the PGM-index use many piecewise models, so an outlier only damages the segment it falls in.
19.4 ★ G-Counter merge. Three replicas keep a G-Counter as a map from replica name to count. Replica A has incremented 3 times, B 5 times, C twice, and none has synced yet. (a) Replica A merges B’s state, then C’s. What is A’s state and value? (b) A message bug delivers B’s state to A a second time. What changes? (c) Someone proposes merging by adding counts instead of taking the max. Show what goes wrong.
Solution
def merge(a, b):
return {r: max(a.get(r, 0), b.get(r, 0)) for r in a.keys() | b.keys()}
def value(c):
return sum(c.values())
A, B, C = {'A': 3}, {'B': 5}, {'C': 2}
ab = merge(A, B)
abc = merge(ab, C)
assert abc == {'A': 3, 'B': 5, 'C': 2} and value(abc) == 10 # (a)
assert merge(abc, B) == abc # (b) idempotent
assert merge(merge(A, B), C) == merge(A, merge(B, C)) == merge(C, merge(B, A))
def bad_merge(a, b):
return {r: a.get(r, 0) + b.get(r, 0) for r in a.keys() | b.keys()}
assert value(bad_merge(ab, ab)) == 16 # (c) double counted
(a) {A: 3, B: 5, C: 2}, value 10.
(b) Nothing changes. max(5, 5) = 5: the merge is idempotent, so duplicate delivery is harmless.
(c) Merging a state with a copy of itself doubles it: {A: 3, B: 5} merged with itself gives {A: 6, B: 10}, value 16 instead of 8. Addition is commutative and associative but not idempotent, and real networks redeliver messages. The per-replica max works because each entry is written by only one replica and only grows, so the larger number is always the more recent one.
19.5 ★★ Design: sizing a vector index. You need nearest-neighbor search over 50 million 768-dimensional float32 embeddings on a machine with 64 GB of RAM, with recall around 95% at 10 nearest neighbors. Estimate the memory for HNSW and for IVF with product quantization (64-byte codes), and pick a design. HNSW with parameter M = 16 stores up to 2M = 32 neighbor ids (4 bytes each) per vector on its bottom layer, and the upper layers add only a small fraction more.
Solution
Raw vectors: 50 × 10⁶ × 768 × 4 bytes = 153.6 GB. That alone is more than twice the RAM.
HNSW: it searches against the full vectors, so it needs the 153.6 GB plus the graph: about 32 × 4 = 128 bytes per vector on the bottom layer, 6.4 GB, so roughly 160 GB. It does not fit. Halving precision to float16 gives about 83 GB, which still does not fit.
IVF + PQ: each vector is stored as a 64-byte code: 50 × 10⁶ × 64 = 3.2 GB, plus ids (8 bytes each, 0.4 GB) and the cluster centroids (negligible). It fits with plenty of room.
The catch is recall. Compressing 3,072 bytes to 64 loses information, and PQ distances alone typically fall short of 95% recall. The standard fix is to re-rank: use IVF-PQ to fetch a few hundred candidates, then read those candidates’ full vectors from SSD and compute exact distances. At NVMe latencies of about 10μs per read (19.3), a few hundred reads add a few milliseconds, or less with parallel I/O.
So: IVF-PQ in RAM, full vectors on NVMe for re-ranking. The alternative is a machine with 192 GB or more of RAM running HNSW, which gives faster queries and simpler tuning at a much higher hardware cost. This is the 19.6 tradeoff in concrete form: HNSW buys recall and speed with memory, quantization buys memory with accuracy.
19.6 ★★★ Build an OR-Set. First, show why the naive replicated set fails: each replica keeps a plain set, remove deletes locally, and merge is union. Then implement the OR-Set from the 19.5 table: each add creates a unique tag, remove tombstones the tags it has observed, and an element is present if it has at least one tag that is not tombstoned. Trace this scenario: replica A adds x; B syncs from A; B removes x while, concurrently, A adds x again; then both sync. Is x present?
Hint
A merge can only combine information, never subtract it, so a removal has to be recorded as something that is added to the state.
Solution
Naive set. Both replicas hold {x}. B removes x, giving {}. Merging is union: {x} ∪ {} = {x}. The remove is undone by the very next sync, even with no concurrent add. Union can only grow sets, so a delete represented as “absence” is indistinguishable from “never heard of it” and always loses.
OR-Set. Removal is recorded as a set of tombstoned tags, which only grows, so merge is union on both components and inherits union’s commutativity, associativity, and idempotence.
class ORSet:
"""State-based observed-remove set."""
def __init__(self, replica):
self.replica = replica
self.counter = 0
self.adds = set() # (element, tag) pairs ever added
self.removed = set() # tags some remove has observed
def add(self, x):
self.counter += 1
self.adds.add((x, (self.replica, self.counter))) # globally unique tag
def remove(self, x):
self.removed |= {tag for (e, tag) in self.adds if e == x}
def contains(self, x):
return any(e == x and tag not in self.removed for (e, tag) in self.adds)
def merge(self, other):
self.adds |= other.adds
self.removed |= other.removed
a, b = ORSet("A"), ORSet("B")
a.add("x") # tag (A, 1)
b.merge(a) # B observes (x, (A, 1))
b.remove("x") # B tombstones (A, 1) only
a.add("x") # concurrently: tag (A, 2), which B never saw
a.merge(b)
b.merge(a)
assert a.contains("x") and b.contains("x")
assert a.adds == b.adds and a.removed == b.removed # converged
Trace:
| Step | A.adds | B.adds | removed (after step) | x present? |
|---|---|---|---|---|
| A adds x | (x, A1) | A: yes | ||
| B syncs from A | (x, A1) | (x, A1) | both: yes | |
| B removes x | (x, A1) | (x, A1) | B: {A1} | B: no |
| A adds x again | (x, A1), (x, A2) | (x, A1) | B: {A1} | A: yes |
| Both sync | (x, A1), (x, A2) | same | both: {A1} | both: yes |
x is present. B’s remove only killed the tag it had seen (A1). A’s concurrent add created A2, which no remove observed. This is add-wins semantics: a remove deletes exactly the adds that happened before it, and never a concurrent one. That is usually what users expect (“I re-added it, why did it vanish?”).
The cost is that tombstones accumulate forever in this simple version. Production implementations compact them using version vectors so that a tag can be dropped once every replica is known to have seen its removal.
Where this connects
- Chapter 24: Research-Grade Data Structures. The research-grade treatment of succinct structures
- Chapter 15: Spatial and Geometric Data Structures. The spatial structures vector search replaces
Chapter 20: Data Structure Design Patterns
The preceding chapters covered structures. This one covers the recurring shapes of the code around them: how to extend a structure without rewriting it, how to expose traversal without exposing internals, and how to keep the cost of an abstraction visible.
The patterns here are the Gang of Four patterns as they specifically apply to collections, plus a few that are particular to data structures and appear in no pattern catalog.
20.1 Wrapper/Decorator Pattern
Add functionality to existing structures:
class SynchronizedDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.lock = threading.Lock()
def __getitem__(self, key):
with self.lock:
return super().__getitem__(key)
A decorator wraps a structure in another object with the same interface, adding behavior on the way through. Synchronization, logging, validation, caching, access counting, and copy-on-write are all naturally decorators. Each is a concern orthogonal to how the data is stored, so each belongs outside the storage.
The example above illustrates the pattern and also a trap worth naming, because it is the single most common way this pattern is misapplied. Subclassing a built-in collection does not reliably intercept its operations. dict.update(), dict.get(), and dict.setdefault() are implemented in C and do not route through __getitem__, so the lock above simply does not apply to them. The structure looks synchronized and is not.
Composition rather than inheritance fixes it, by making the delegation explicit:
class SynchronizedDict:
"""Wraps a dict rather than subclassing it, so nothing bypasses the lock."""
def __init__(self, initial=None):
self._data = dict(initial or {})
self._lock = threading.RLock() # reentrant: safe if callbacks re-enter
def __getitem__(self, key):
with self._lock:
return self._data[key]
def __setitem__(self, key, value):
with self._lock:
self._data[key] = value
def get(self, key, default=None):
with self._lock:
return self._data.get(key, default)
Worth being honest about what this buys: per-operation locking makes each operation atomic, but sequences of operations still race. if k in d: d[k] += 1 acquires the lock twice and another thread can interleave between them. This is why Java deprecated Hashtable in favor of ConcurrentHashMap’s compound operations like computeIfAbsent, and why a synchronized wrapper is usually the wrong concurrency answer: see Chapter 18.
Real uses: Java’s Collections.unmodifiableList() and synchronizedMap(); Python’s types.MappingProxyType; the copy-on-write wrappers in persistent collection libraries.
20.2 Composite Pattern
Tree-like hierarchical structures:
class Component:
def operation(self): pass
class Composite(Component):
def __init__(self):
self.children = []
def add(self, c):
self.children.append(c)
def operation(self):
for c in self.children:
c.operation()
The composite pattern makes a leaf and a container of leaves interchangeable, so client code can treat “one thing” and “a tree of things” identically. Filesystems are the standard illustration. A directory’s size is the sum of its children’s sizes, and a file’s size is its own, but the caller asks the same question of both:
class Node(ABC):
@abstractmethod
def size(self) -> int: ...
class File(Node):
def __init__(self, name, size):
self.name, self._size = name, size
def size(self):
return self._size
class Directory(Node):
def __init__(self, name):
self.name, self.children = name, []
def add(self, node: Node) -> "Directory":
self.children.append(node)
return self
def size(self):
return sum(child.size() for child in self.children)
This is exactly how the expression trees in Chapter 6 work: a literal and an operator node both answer evaluate(). It is also how the DOM, scene graphs, GUI widget hierarchies, and query plan trees are built.
Two warnings. First, recursive traversal means recursive depth. A deep composite will overflow the stack, and structures with user-controlled depth need an explicit stack instead. Second, the pattern is often written with add()/remove() on the base Component so leaves and composites share one interface; that forces leaves to implement operations that make no sense for them. Keeping child management on Composite alone is the safer choice, at the cost of clients needing a type check to add children.
20.3 Iterator Pattern
Abstract traversal:
class TreeIterator:
def __init__(self, root):
self.stack = [root] if root else []
def __iter__(self):
return self
def __next__(self):
if not self.stack:
raise StopIteration
node = self.stack.pop()
if node.right:
self.stack.append(node.right)
if node.left:
self.stack.append(node.left)
return node.val
The iterator decouples what you want to visit from how the structure is laid out. Its real value is that it lets a caller consume a traversal without the structure handing over its internals, and without building an intermediate list.
The example above is a pre-order traversal made iterative: note the right child pushed before the left, so the left pops first. Doing this without recursion is not merely stylistic: it makes the traversal lazy, so a caller can stop early after examining three nodes of a million-node tree and pay for three.
In Python, generators express the same thing far more directly, and the in-order version is worth having since it is the traversal that yields a BST’s keys in sorted order:
def in_order(node):
"""Lazy in-order traversal. O(1) amortized per element, O(h) space."""
stack, current = [], node
while stack or current:
while current: # descend left, remembering the path
stack.append(current)
current = current.left
current = stack.pop()
yield current.val # visit
current = current.right # then the right subtree
# Consumes only as much of the tree as it needs:
first_five = list(itertools.islice(in_order(root), 5))
Iterator invalidation is the classic hazard: mutating a structure while iterating it. Removing from a Python list during a for loop skips elements; a C++ vector reallocation leaves every outstanding iterator dangling; Java throws ConcurrentModificationException from a modification counter checked on each next(). The three responses (undefined behavior, fail-fast, and snapshot semantics (CopyOnWriteArrayList))represent a real design choice, and fail-fast is usually the right one because it converts a silent wrong answer into a loud crash.
20.4 Builder Pattern
Complex construction:
class BSTBuilder:
def __init__(self):
self.values = []
def add(self, value):
self.values.append(value)
return self
def build(self):
self.values.sort()
return self._build_range(0, len(self.values))
def _build_range(self, lo, hi):
if lo >= hi:
return None
mid = (lo + hi) // 2
node = TreeNode(self.values[mid])
node.left = self._build_range(lo, mid)
node.right = self._build_range(mid + 1, hi)
return node
Builders matter most for data structures when bulk construction beats repeated insertion, which is often, and by more than people expect.
The example is a good illustration of why. Inserting n sorted values into a plain BST one at a time produces a linked list of height n − 1. Collecting them, sorting once, and recursively taking the midpoint produces a perfectly balanced tree of height ⌊log₂ n⌋ in O(n log n) total, and needs no rotation logic at all.
The same asymmetry recurs throughout:
| Structure | Incremental | Bulk-loaded |
|---|---|---|
| BST | O(n log n), possibly unbalanced | O(n) from sorted input, perfectly balanced |
| Binary heap | O(n log n) sift-ups | O(n) Floyd heapify |
| B-tree | O(n log n), ~70% node occupancy | O(n) sorted bulk load, ~100% occupancy |
| Hash table | O(n) with resizes along the way | O(n), pre-sized, no rehashing |
| R-tree | Poor structure, high overlap | Sort-Tile-Recursive packing, much better |
| Suffix array | n/a | O(n) with SA-IS |
The B-tree row is easy to overlook and matters in practice: incremental insertion leaves nodes about 70% full, so a bulk-loaded index is meaningfully smaller and shallower. This is exactly why CREATE INDEX on an existing table produces a better index than the same rows inserted one at a time, and why REINDEX is a real optimization.
One further note on the example: build() sorts self.values in place and can be called twice with different results if add() is called in between. Builders that are consumed by build() should say so, or copy.
20.5 Adapter, Flyweight, and Policy
Three more that earn their place in collection code.
Adapter converts one interface to another. A max-heap from a min-heap by negating keys is the smallest possible example, and Python’s heapq (min-only) makes it a daily occurrence:
class MaxHeap:
"""Adapts heapq's min-heap into a max-heap by negating."""
def __init__(self):
self._h = []
def push(self, value):
heapq.heappush(self._h, -value)
def pop(self):
return -heapq.heappop(self._h)
Also: a deque adapted to a stack or a queue, and a Set adapted from a Map with dummy values, which is literally how Java’s HashSet is implemented.
Flyweight shares immutable state between many objects. String interning is the ubiquitous case: Java and Python both intern short strings so that a million occurrences of "active" cost one allocation. Tries share prefixes for the same reason, and the shared subtrees of persistent structures in Chapter 17 are flyweights created automatically by immutability.
Policy / strategy parameterizes a structure by a decision rather than baking it in. A comparator is the everyday example; so is a hash function, an eviction policy, or an allocator. C++’s std::map<K, V, Compare, Allocator> makes all of them template parameters, which is why the same container serves ascending order, descending order, and arena allocation with no runtime cost.
20.6 Choosing a Pattern
| Need | Pattern | Watch out for |
|---|---|---|
| Add a cross-cutting concern | Decorator | Subclassing built-ins fails to intercept; per-op locks don’t make sequences atomic |
| Uniform treatment of leaves and trees | Composite | Recursion depth; child ops on leaves |
| Expose traversal, hide layout | Iterator | Invalidation on mutation |
| Efficient construction | Builder | Bulk-load beats incremental more often than expected |
| Reconcile mismatched interfaces | Adapter | Thin wrappers can hide real cost |
| Many identical immutable values | Flyweight | Only helps if genuinely immutable |
| Vary one decision | Policy | Runtime polymorphism costs a virtual call |
The pattern that applies to all of them: an abstraction over a data structure hides the layout but does not hide the cost. A List interface backed by a linked list and one backed by an array have identical signatures and completely different performance, and code written against the interface will silently get whichever it is handed. This is the practical reason C++ names std::vector and std::list distinctly instead of offering one List, and the reason Java’s List interface has been a recurring source of accidental O(n²) loops. get(i) in a loop over a LinkedList is quadratic and looks exactly like the linear version.
Abstract the interface. Document the cost.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
20.1 ★ Which calls take the lock? Using the first SynchronizedDict in 20.1 (the one that subclasses dict and overrides only __getitem__), which of these operations acquire self.lock?
d = SynchronizedDict(a=1)
d['a']
d.get('a')
'a' in d
d.setdefault('a', 0)
d['b'] = 2
for k in d:
pass
How would you check your answer empirically rather than by reading CPython’s source?
Solution
Only d['a']. get, in (__contains__), setdefault, and iteration are implemented in C on dict and never call the Python-level __getitem__. d['b'] = 2 calls __setitem__, which the class does not override at all, so writes were never locked in the first place.
To check, replace the lock with a spy that records each call:
calls = []
class Spy(dict):
def __getitem__(self, key):
calls.append(key)
return super().__getitem__(key)
d = Spy(a=1)
d['a']
assert calls == ['a']
calls.clear()
d.get('a')
'a' in d
d.setdefault('a', 0)
for k in d:
pass
assert calls == [] # none of these went through __getitem__
This is the trap 20.1 describes: the class looks synchronized because its one visible method is, while most of its interface bypasses that method.
20.2 ★★ Make a compound operation atomic. Assume the composition-based SynchronizedDict from 20.1 also has a locked __contains__. Two threads each run:
if k in d:
d[k] = d[k] + 1
else:
d[k] = 1
Show an interleaving that loses an update. Then add a method to SynchronizedDict that makes this safe, and a general version that applies any function to a key’s value atomically (in the spirit of Java’s compute).
Hint
Each line is atomic on its own. The lock is released between the check and the act.
Solution
Starting with k absent: thread 1 evaluates k in d → False and releases the lock. Thread 2 evaluates k in d → False. Thread 1 sets d[k] = 1. Thread 2 sets d[k] = 1. Two increments, final value 1. The same happens with k present: both threads read d[k] == 5, both write 6.
The fix is to hold the lock across the whole read-modify-write, which only the class itself can do:
import threading
class SynchronizedDict:
def __init__(self, initial=None):
self._data = dict(initial or {})
self._lock = threading.RLock()
def __getitem__(self, key):
with self._lock:
return self._data[key]
def __setitem__(self, key, value):
with self._lock:
self._data[key] = value
def __contains__(self, key):
with self._lock:
return key in self._data
def increment(self, key, by=1):
with self._lock:
new = self._data.get(key, 0) + by
self._data[key] = new
return new
def update_with(self, key, fn, default=None):
"""Atomically replace d[key] with fn(d.get(key, default))."""
with self._lock:
new = fn(self._data.get(key, default))
self._data[key] = new
return new
d = SynchronizedDict()
def work():
for _ in range(20_000):
d.increment('hits')
threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
assert d['hits'] == 80_000
assert d.update_with('log', lambda xs: (xs or []) + ['start']) == ['start']
update_with runs fn while holding the lock, which has a cost: a slow fn blocks every other caller, and the RLock is what makes it safe for fn to call back into d. Java’s ConcurrentHashMap.compute has the same rule (keep the function short), for the same reason.
The general lesson: an atomic interface has to offer the compound operations its callers need. Locking each primitive separately cannot be composed into atomic sequences from outside.
20.3 ★ Trace the iterators. Use this BST with the TreeIterator and in_order code from 20.3:
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
- List the values
TreeIteratoryields, and the contents of its stack (bottom to top, as values) after each of the first three calls tonext(). - List the values
in_orderyields. list(itertools.islice(in_order(root), 3))returns three values. Which nodes have been pushed onto the generator’s stack by then?
Solution
- Pre-order: 8, 3, 1, 6, 4, 7, 10, 14, 13.
| Call | Pops | Pushes (right first, then left) | Stack after | Yields |
|---|---|---|---|---|
| 1 | 8 | 10, 3 | [10, 3] | 8 |
| 2 | 3 | 6, 1 | [10, 6, 1] | 3 |
| 3 | 1 | nothing | [10, 6] | 1 |
-
In-order: 1, 3, 4, 6, 7, 8, 10, 13, 14, the sorted keys.
-
The generator descends 8 → 3 → 1 (pushing all three), pops and yields 1, pops and yields 3, moves to 6 and descends 6 → 4 (pushing both), then pops and yields 4. Pushed so far: 8, 3, 1, 6, 4, five of the nine nodes. Nodes 7, 10, 13, and 14 are never touched. That is the laziness 20.3 describes: the cost is proportional to what you consume plus the depth of the path to it.
20.4 ★★ The height of a bulk-built tree. Prove that BSTBuilder._build_range from 20.4 produces a tree of height exactly ⌊log₂ n⌋ for n ≥ 1 values (height counted in edges, as in Chapter 6). Then state the height for n = 10 and compare it with inserting the same 10 sorted values one at a time into a plain BST.
Hint
Work out the sizes of the left and right ranges when mid = (lo + hi) // 2, and use strong induction on n.
Solution
For a range of n values, mid = lo + ⌊n/2⌋ (since (lo + hi) // 2 with hi = lo + n), so the left range holds ⌊n/2⌋ values and the right range holds n − ⌊n/2⌋ − 1 = ⌈n/2⌉ − 1 values. The right range is never larger than the left.
Claim: h(n) = ⌊log₂ n⌋ for n ≥ 1, where an empty range contributes height −1.
- Base: n = 1 gives a single node, height 0 = ⌊log₂ 1⌋.
- Step: take n ≥ 2 and assume the claim for all smaller sizes. The left range has m = ⌊n/2⌋ ≥ 1 values, so its height is ⌊log₂ m⌋. The right range has at most m values, so by the hypothesis (or because it is empty) its height is at most ⌊log₂ m⌋. So h(n) = 1 + ⌊log₂ ⌊n/2⌋⌋. If 2ᵏ ≤ n < 2ᵏ⁺¹, then 2ᵏ⁻¹ ≤ ⌊n/2⌋ < 2ᵏ, so ⌊log₂ ⌊n/2⌋⌋ = k − 1 and h(n) = k = ⌊log₂ n⌋.
For n = 10: ⌊log₂ 10⌋ = 3. Inserting the same 10 sorted values one at a time builds a chain of height 9.
A quick empirical check:
class TreeNode:
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build(values, lo, hi):
if lo >= hi:
return None
mid = (lo + hi) // 2
node = TreeNode(values[mid])
node.left = build(values, lo, mid)
node.right = build(values, mid + 1, hi)
return node
def height(node):
return -1 if node is None else 1 + max(height(node.left), height(node.right))
for n in range(1, 2000):
assert height(build(list(range(n)), 0, n)) == n.bit_length() - 1 # floor(log2 n)
20.5 ★★ The adapter’s hidden assumption. The MaxHeap adapter in 20.5 negates values. Name the inputs it cannot handle, and write a version that works for any values that support <, still built on heapq.
Solution
Negation only exists for numbers. Strings, tuples, dates, and most user-defined types raise TypeError: bad operand type for unary -. (Tuples of numbers could be negated field by field, but only by writing custom code per shape.)
The general fix inverts the comparison rather than the value, by wrapping each item:
import heapq
class _Reversed:
__slots__ = ("item",)
def __init__(self, item):
self.item = item
def __lt__(self, other):
return other.item < self.item # reversed order
class MaxHeap:
def __init__(self):
self._h = []
def push(self, item):
heapq.heappush(self._h, _Reversed(item))
def pop(self):
return heapq.heappop(self._h).item
def __len__(self):
return len(self._h)
h = MaxHeap()
for word in ["pear", "apple", "fig", "kiwi"]:
h.push(word)
assert [h.pop() for _ in range(4)] == ["pear", "kiwi", "fig", "apple"]
heapq only uses <, so defining __lt__ is enough. This is still an adapter, one layer deeper: the wrapper adapts each item’s ordering, and MaxHeap adapts the heap’s interface. It costs an object allocation and a Python-level method call per comparison, so for plain numbers the negation version is faster. That is the “thin wrappers can hide real cost” row of the 20.6 table.
20.6 ★★ An accidental quadratic. Here is a linked list that supports indexing, and two ways to sum a sequence:
class LinkedList:
class _Node:
__slots__ = ("val", "next")
def __init__(self, val, nxt):
self.val, self.next = val, nxt
def __init__(self, items):
self.head, self.n, self.hops = None, 0, 0
for x in reversed(items):
self.head = self._Node(x, self.head)
self.n += 1
def __len__(self):
return self.n
def __getitem__(self, i):
if not 0 <= i < self.n:
raise IndexError(i)
node = self.head
for _ in range(i):
node = node.next
self.hops += 1
return node.val
def __iter__(self):
node = self.head
while node:
yield node.val
node = node.next
def total_by_index(seq):
t = 0
for i in range(len(seq)):
t += seq[i]
return t
def total_by_iter(seq):
t = 0
for x in seq:
t += x
return t
For a 1,000-element list, how many hops does total_by_index cost? What is the general formula and complexity? What does total_by_iter cost? What would change if __getitem__ walked from whichever end is closer, as Java’s LinkedList.get does?
Solution
seq[i] walks i links, so the total is 0 + 1 + … + (n − 1) = n(n − 1)/2. For n = 1000 that is 499,500 hops: Θ(n²). total_by_iter follows each link once, n steps in total: Θ(n).
L = LinkedList(list(range(1000)))
assert total_by_index(L) == 499_500 and L.hops == 499_500
L.hops = 0
assert total_by_iter(L) == 499_500 and L.hops == 0 # iteration never calls __getitem__
Walking from the nearer end makes get(i) cost min(i, n − 1 − i), which roughly halves the total to about n²/4. Still quadratic.
Both functions have the same signature and both are correct for any sequence. Handed a Python list, they are equally fast; handed this linked list, one is 500 times slower at n = 1000 and the gap grows linearly with n. This is the closing point of 20.6: the interface hid the layout, and the layout decided the cost. The fix is to write traversals with iteration, which every sequence can do at its own best speed, and to reserve seq[i] for structures that document O(1) indexing.
20.7 ★★★ A fail-fast iterator. Implement a small DynamicArray (wrapping a Python list is fine) whose iterator raises RuntimeError if the array is structurally modified (an element added or removed) during iteration, using a modification counter as Java does. Replacing an element in place should not count as a structural modification. Make sure a modification made while processing the last element is also caught.
Hint
The iterator records the counter when it starts and compares on every step. Think about where the last comparison happens when the loop body modifies the array after the final yield.
Solution
class DynamicArray:
def __init__(self):
self._items = []
self._mods = 0 # bumped by every structural change
def append(self, x):
self._items.append(x)
self._mods += 1
def pop(self):
self._mods += 1
return self._items.pop()
def __setitem__(self, i, x):
self._items[i] = x # replacing a value is not structural
def __len__(self):
return len(self._items)
def __iter__(self):
expected = self._mods
for i in range(len(self._items)):
if self._mods != expected:
raise RuntimeError("DynamicArray modified during iteration")
yield self._items[i]
if self._mods != expected: # catches a change made after the last yield
raise RuntimeError("DynamicArray modified during iteration")
a = DynamicArray()
for x in [1, 2, 3]:
a.append(x)
for i, x in enumerate(a):
a[i] = x * 10 # allowed
assert list(a) == [10, 20, 30]
for trigger, mutate in [(20, lambda: a.append(99)), (99, a.pop)]:
try:
for x in a:
if x == trigger:
mutate()
raise AssertionError("mutation was not detected")
except RuntimeError:
pass
assert list(a) == [10, 20, 30]
The first case appends 99 mid-iteration and is caught on the next step. That leaves 99 as the last element, so the second case pops it while processing the last element. Without the final check after the loop, that pop would go unnoticed: the generator would simply finish.
Why in-place replacement is exempt: it cannot make the iterator skip, repeat, or read out of bounds, because positions and length are unchanged. Java’s ArrayList.set does not bump modCount for the same reason.
The check is “best effort” in the same sense as Java’s: it detects modifications made through the array’s own methods, on the iterating thread. It is a debugging aid that turns the silent skipped-element bug from 20.3 into a loud error, not a concurrency control.
Where this connects
- Chapter 22: Practical Considerations. The practical judgment these patterns support
- Chapter 6: Tree Fundamentals and Binary Trees. The composite and iterator patterns in their original setting
Chapter 21: Algorithm Design Using Data Structures
Algorithm design is usually taught as a catalog of paradigms and data structures as a separate catalog of containers. They are not separate. Each paradigm is defined by a specific bookkeeping problem, and the paradigm becomes practical exactly when a structure solves that bookkeeping in the right complexity.
Dijkstra’s algorithm is the cleanest demonstration. The algorithm (repeatedly settle the nearest unsettled vertex) is unchanged since 1956. Its complexity is entirely a property of the structure answering “which is nearest?”:
| Priority queue | Complexity | Best for |
|---|---|---|
| Unsorted array | O(V²) | Dense graphs (E ≈ V²) |
| Binary heap | O((V + E) log V) | Sparse graphs, the usual choice |
| Fibonacci heap | O(E + V log V) | Theoretically optimal, rarely faster in practice |
Same algorithm, three complexities. This chapter reads each paradigm that way: what does it need to remember, and which structure remembers it best?
21.1 Divide and Conquer
Use data structures to divide problems:
- Quicksort: Partition around pivot
- Merge sort: Divide at midpoint, merge sorted halves
- Binary search: Divide search space in half
Divide and conquer splits a problem into independent subproblems, solves them recursively, and combines the results. Its bookkeeping need is the recursion itself, which is why the stack from Chapter 5 is the paradigm’s implicit data structure. Every recursive call is a stack frame, and converting a recursive algorithm to an iterative one always means making that stack explicit.
Cost follows the Master Theorem: for T(n) = a·T(n/b) + f(n), compare f(n) against n^(log_b a). Merge sort is T(n) = 2T(n/2) + O(n) = O(n log n), binary search is T(n) = T(n/2) + O(1) = O(log n). Both land in the middle case, where f(n) matches n^(log_b a) and the cost picks up a log factor.
The structural insight worth carrying: the split and the combine trade off against each other. Merge sort splits trivially at the midpoint and pays in the merge. Quicksort pays in the partition and combines for free. Same total, different placement, and it is why quicksort sorts in place while merge sort needs O(n) scratch space.
Where a structure changes the answer outright:
- Segment trees (Chapter 23) are divide-and-conquer made persistent. Rather than re-splitting per query, the split is stored once as a tree and reused, turning O(n) range queries into O(log n).
- Karatsuba multiplication and Strassen’s algorithm win by reducing the number of subproblems (3 instead of 4, 7 instead of 8) so the branching factor
adrops and the exponent falls with it. - Deep recursion on user-controlled input is a stack-overflow bug. An explicit stack is not just a style preference.
21.2 Dynamic Programming
Optimal substructure + overlapping subproblems:
- Use memoization (hash table)
- Tabulation (array)
Dynamic programming applies when subproblems overlap: the case where plain divide and conquer recomputes the same work exponentially many times. Its bookkeeping need is a map from subproblem to answer, and the choice of map is the whole implementation decision.
Memoization (top-down) uses a hash table, recursion, and computes only reachable subproblems. Tabulation (bottom-up) uses an array, iteration, and computes all of them. The tradeoff is concrete: memoization skips unreachable states, which matters when the state space is sparse; tabulation has no recursion overhead and far better cache locality, which usually makes it faster when the state space is dense.
# Memoized: sparse state space, natural recursion, hash table lookup per call
@lru_cache(maxsize=None)
def lcs(i, j):
if i == 0 or j == 0:
return 0
if a[i-1] == b[j-1]:
return 1 + lcs(i-1, j-1)
return max(lcs(i-1, j), lcs(i, j-1))
# Tabulated with rolling rows: O(min(m, n)) space instead of O(m·n)
def lcs_table(a, b):
if len(b) > len(a):
a, b = b, a # keep the inner dimension small
prev = [0] * (len(b) + 1)
for i in range(1, len(a) + 1):
cur = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
cur[j] = 1 + prev[j-1] if a[i-1] == b[j-1] else max(prev[j], cur[j-1])
prev = cur
return prev[len(b)]
The rolling-row trick in the second version is the most broadly useful DP optimization there is: if a row depends only on the previous row, only two rows need to exist. An O(m·n) table becomes O(min(m,n)) space. Sequence alignment on genomes is feasible because of this.
Structures that change what DP can do:
- Monotonic deque: sliding-window maximum in O(1) amortized, turning an O(n·k) DP into O(n). The basis of the sliding-window-maximum optimization.
- Convex hull trick / Li Chao tree, when transitions have the form
min(m·x + b), maintaining the lower envelope of lines drops an O(n²) DP to O(n log n). - Fenwick tree (Chapter 23), when a transition sums over a prefix of previous states, prefix sums in O(log n) beat re-scanning in O(n).
- Bitsets. Subset-sum over n items and capacity W runs in O(nW/64) rather than O(nW), a 64× constant-factor win that regularly decides feasibility.
21.3 Greedy Algorithms
Make locally optimal choices:
- Huffman coding: Greedy tree building
- Dijkstra’s: Greedy shortest path
- Kruskal’s: Greedy MST
A greedy algorithm commits to the locally best choice and never reconsiders. Its bookkeeping need is “what is the best remaining option?”, asked repeatedly, which is precisely the priority queue’s interface. That is not a coincidence; it is why heaps appear in nearly every greedy algorithm.
Look at the three examples through their structures:
| Algorithm | Greedy choice | Structure | Complexity |
|---|---|---|---|
| Huffman coding | Merge two least-frequent nodes | Min-heap | O(n log n) |
| Dijkstra | Settle nearest unsettled vertex | Min-heap by distance | O((V+E) log V) |
| Prim’s MST | Add cheapest edge leaving the tree | Min-heap by edge weight | O(E log V) |
| Kruskal’s MST | Add cheapest edge that doesn’t cycle | Sort + union-find | O(E log E) |
| Interval scheduling | Take earliest finish time | Sort by end time | O(n log n) |
Kruskal’s is the interesting row, because its bookkeeping is not “what’s cheapest” (sorting answers that once) but “would this edge create a cycle?” Union-find answers it in near-constant amortized time, α(n), and without union-find the cycle check would be a graph traversal per edge and the algorithm would be O(E·V). A different question needs a different structure.
Greedy is only correct when the problem has the right structure, and that is a genuine mathematical condition, not a hopeful assumption. The matroid property guarantees it. Kruskal’s is correct because forests of a graph form a matroid. Absent such a property, greedy produces plausible wrong answers: it fails on 0/1 knapsack, on set cover (though it gives a ln n approximation), and on shortest paths with negative edges, which is exactly why Dijkstra requires non-negative weights. A greedy algorithm that is nearly right is often worse than an obviously wrong one, because nobody notices.
21.4 Backtracking
Systematic search with pruning:
- Use stack to track state
- Prune when impossible
Backtracking explores a decision tree depth-first, abandoning a branch as soon as it cannot lead to a solution. Its bookkeeping need is the current partial state, cheaply undoable, and the emphasis belongs on undoable, because the difference between a fast solver and a hopeless one is usually the cost of undoing a move.
The naive approach copies the state at each node, costing O(state) per branch. The right approach mutates and reverses:
def solve(board, row, cols, diag1, diag2):
"""N-Queens. Sets give O(1) conflict checks; undo is symmetric with do."""
if row == len(board):
return True
for col in range(len(board)):
if col in cols or (row - col) in diag1 or (row + col) in diag2:
continue # prune
cols.add(col); diag1.add(row - col); diag2.add(row + col) # do
board[row] = col
if solve(board, row + 1, cols, diag1, diag2):
return True
cols.remove(col); diag1.remove(row - col); diag2.remove(row + col) # undo
return False
The three sets are the data-structure decision. Checking conflicts by scanning previously placed queens is O(n) per candidate; the sets make it O(1). Same search tree, different constant, and the constant is what makes n = 20 tractable.
Structures that make backtracking practical:
- Bitmasks replace those sets entirely for small n.
cols | diag1 | diag2in three integers, with conflict-checking and undo as single instructions. This is the standard fast N-Queens. - Dancing Links (DLX): Knuth’s doubly-linked-list technique for exact cover, where removing and restoring a row or column are both O(1) pointer updates. It is the fastest known general Sudoku and pentomino solver, and it exists entirely because of how cheap its undo is.
- Union-find with rollback (Chapter 23) provides undoable connectivity for search over graph states.
- Trie: in word search and Boggle solvers, a trie prunes the moment a prefix cannot extend to any word, which collapses the search space dramatically.
Constraint propagation deserves mention as the general principle: the more work you do to detect a dead end early, the smaller the tree. This is why SAT solvers spend most of their time in propagation rather than search.
21.5 Randomized Algorithms
Probabilistic techniques:
- Quicksort (random pivot)
- Hash tables (random hash functions)
- Skip lists (random levels)
Randomization buys two distinct things, and conflating them is a common confusion:
Las Vegas algorithms are always correct, with running time that varies. Randomized quicksort always sorts, and is O(n log n) expected. Monte Carlo algorithms have fixed running time and may be wrong: a Bloom filter always answers in O(k), and sometimes answers wrongly.
The unifying purpose across all three examples is defeating adversarial input. Deterministic quicksort with a fixed pivot has an O(n²) input, and it is easy to construct, this was a real denial-of-service vector. Deterministic hashing has a collision-flooding input, which was a widely exploited DoS against web frameworks in 2011. Randomization means the adversary cannot construct a bad input in advance, because the bad input depends on choices not yet made.
| Structure | Randomization | Buys |
|---|---|---|
| Randomized quicksort | Random pivot | O(n log n) expected regardless of input |
| Skip list | Random level per node | Balance without rotations, and easy concurrency |
| Treap | Random priority | A BST balanced in expectation, trivial to implement |
| Universal hashing | Random hash from a family | Collision bounds that hold against an adversary |
| Bloom filter | k independent hashes | Membership in ~10 bits/element |
| HyperLogLog | Hash bit-pattern statistics | Cardinality of billions in 12KB |
| Reservoir sampling | Random replacement | Uniform sample of a stream of unknown length |
Skip lists deserve a closer look because they show randomization buying something beyond speed. A skip list and a red-black tree are both O(log n), but the skip list gets there with coin flips instead of rotations, and since insertion touches only a few forward pointers rather than rebalancing a region, skip lists are far easier to make concurrent, as Chapter 18 discusses. Randomness bought simplicity and locality, and concurrency came along with them.
Two practical cautions. First, “random” must mean unpredictable to an adversary: seeding a hash function with a fixed constant, or with the process start time, reintroduces exactly the attack you were defending against. Second, expected-case bounds say nothing about any individual run. A randomized quicksort can be quadratic, just not reliably, and a system with hard latency requirements may need a guaranteed bound instead.
21.6 Choosing a Paradigm
The diagnostic question for each:
| Signal | Paradigm | Structure that makes it work |
|---|---|---|
| Independent subproblems | Divide and conquer | Stack (explicit if deep) |
| Overlapping subproblems, optimal substructure | Dynamic programming | Array (dense) or hash map (sparse) |
| Locally optimal choice is provably safe | Greedy | Priority queue; union-find for connectivity |
| Search a space, most branches invalid | Backtracking | Cheaply-undoable state: bitmask, DLX |
| Adversarial input, or determinism too slow | Randomized | Depends, the randomness is the technique |
And the thread running through all of them: identify the question the algorithm asks over and over, then pick the structure that answers that question fastest. Dijkstra asks “which is nearest.” Kruskal asks “would this cycle.” DP asks “have I computed this.” Backtracking asks “can this branch still work.” Get the question right and the structure is usually obvious; get it wrong and no amount of optimization will help.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
21.1 ★ Master Theorem cases. For T(n) = a·T(n/b) + f(n), compare f(n) with n^(log_b a) and solve each recurrence. Say which of the three cases applies.
- Karatsuba: T(n) = 3T(n/2) + O(n)
- Strassen: T(n) = 7T(n/2) + O(n²)
- Naive divide-and-conquer matrix multiplication: T(n) = 8T(n/2) + O(n²)
- T(n) = 2T(n/2) + O(n²)
Solution
The three cases: if n^(log_b a) grows polynomially faster than f(n), the leaves dominate (case 1, T = Θ(n^(log_b a))). If they match, every level costs the same (case 2, an extra log factor). If f(n) grows polynomially faster and satisfies the regularity condition a·f(n/b) ≤ c·f(n) for some c < 1, the root dominates (case 3, T = Θ(f(n))).
| Recurrence | n^(log_b a) | f(n) | Case | T(n) |
|---|---|---|---|---|
| 3T(n/2) + n | n^(log₂ 3) ≈ n^1.585 | n | 1 | Θ(n^1.585) |
| 7T(n/2) + n² | n^(log₂ 7) ≈ n^2.807 | n² | 1 | Θ(n^2.807) |
| 8T(n/2) + n² | n^(log₂ 8) = n³ | n² | 1 | Θ(n³) |
| 2T(n/2) + n² | n | n² | 3 | Θ(n²) |
For the last row, regularity holds: 2·(n/2)² = n²/2, so c = 1/2 works.
Rows 2 and 3 show the 21.1 point about Karatsuba and Strassen exactly: same f(n), but cutting a from 8 to 7 lowers the exponent from 3 to 2.807. Merge sort and binary search, from 21.1, are both case 2.
21.2 ★ Pick Dijkstra’s priority queue. A graph has V = 10,000 vertices. Using the costs in the table at the start of this chapter (with log₂ V ≈ 13.3), estimate the work for an unsorted array and a binary heap when (a) the graph is nearly complete, E ≈ V² = 10⁸, and (b) the graph is sparse, E = 40,000. Which wins each time, and by roughly how much?
Solution
| Unsorted array, V² | Binary heap, (V + E) log V | |
|---|---|---|
| (a) E = 10⁸ | 10⁸ | ≈ 10⁸ × 13.3 ≈ 1.3 × 10⁹ |
| (b) E = 4 × 10⁴ | 10⁸ | 5 × 10⁴ × 13.3 ≈ 6.6 × 10⁵ |
(a) The array wins by about 13×. With E ≈ V², every edge has to be examined anyway, and the heap adds a log V factor to each one. The array’s V scans of V entries cost the same order as reading the edges.
(b) The heap wins by about 150×. The array still pays V² regardless of how few edges exist.
The crossover is around E ≈ V² / log V. Same algorithm, and the right structure depends on a property of the input (density) rather than of the algorithm.
21.3 ★★ Rolling-row LCS by hand. Run lcs_table("AGGTAB", "GXTXAYB") from 21.2. Note the swap at the top of the function. Write out prev after each iteration of the outer loop. What is the result? Then explain why this version cannot tell you which subsequence is common, and what it would take to recover it.
Hint
After the swap, a is the longer string. Each row has len(b) + 1 entries, and cur[j] depends only on prev[j-1], prev[j], and cur[j-1].
Solution
len(b) > len(a) (7 > 6), so the strings swap: a = "GXTXAYB" drives the outer loop and b = "AGGTAB" indexes the columns.
| i | a[i−1] | prev after the iteration (columns: ∅ A G G T A B) |
|---|---|---|
| 0 | 0 0 0 0 0 0 0 | |
| 1 | G | 0 0 1 1 1 1 1 |
| 2 | X | 0 0 1 1 1 1 1 |
| 3 | T | 0 0 1 1 2 2 2 |
| 4 | X | 0 0 1 1 2 2 2 |
| 5 | A | 0 1 1 1 2 3 3 |
| 6 | Y | 0 1 1 1 2 3 3 |
| 7 | B | 0 1 1 1 2 3 4 |
The result is prev[6] = 4, for the subsequence GTAB.
The function keeps only lengths, and only two rows of them. Recovering the subsequence means walking backwards from the bottom-right cell, at each step checking whether the characters matched (move diagonally) or which neighbor the max came from (move up or left). That walk needs every row, so the simple approach keeps the full O(m·n) table. Hirschberg’s algorithm gets the subsequence in O(min(m, n)) space anyway: it runs the rolling-row computation forwards on the first half of one string and backwards on the second half to find where an optimal path crosses the middle row, then recurses on the two halves. That is divide and conquer (21.1) layered on top of DP (21.2), at roughly twice the time.
21.4 ★★ Watch greedy fail. 21.3 says greedy fails on 0/1 knapsack. (a) With capacity 10 and items (weight, value) = (6, 30), (5, 20), (5, 20), what does “take the best value-per-weight item that still fits” choose, and what is optimal? (b) Making change with coins {1, 3, 4}, what does “take the largest coin that fits” produce for 6, and what is optimal? (c) Write the DP that always gets (b) right, and state its complexity.
Solution
(a) Ratios are 5, 4, 4. Greedy takes (6, 30), leaving capacity 4, so neither 5-weight item fits: value 30. The optimum skips the best-ratio item and takes both (5, 20) items: value 40. The first choice looked best locally and blocked a better combination.
(b) Greedy: 4, then 1, then 1, which is 3 coins. Optimal: 3 + 3, 2 coins.
(c) The subproblem is “fewest coins for amount x”, and it overlaps heavily, so tabulate it in an array (21.2’s dense case):
def min_coins(coins, amount):
INF = float('inf')
best = [0] + [INF] * amount # best[x] = fewest coins summing to x
for x in range(1, amount + 1):
for c in coins:
if c <= x and best[x - c] + 1 < best[x]:
best[x] = best[x - c] + 1
return best[amount]
assert min_coins([1, 3, 4], 6) == 2
assert min_coins([1, 5, 10, 25], 63) == 6 # 25 + 25 + 10 + 1 + 1 + 1
It runs in O(amount × number of coins) time and O(amount) space. For the US coin set the greedy answer happens to be optimal (such coin systems are called canonical), which is exactly why the greedy habit survives: it works on the examples people try first.
21.5 ★★ Kruskal with union-find. Run Kruskal’s algorithm on this graph, processing edges in increasing weight. For each edge, say whether find puts its endpoints in the same set, and whether the edge is accepted or rejected.
Edges (weight: endpoints)
1: A-B 2: B-C 3: A-C 4: C-D 5: B-D 6: D-E 7: C-E
What is the MST’s total weight? How much work would the cycle check cost per edge without union-find?
Solution
| Edge | Sets before | Same set? | Decision | Sets after |
|---|---|---|---|---|
| 1: A-B | {A} {B} {C} {D} {E} | no | accept | {A,B} {C} {D} {E} |
| 2: B-C | {A,B} {C} {D} {E} | no | accept | {A,B,C} {D} {E} |
| 3: A-C | {A,B,C} {D} {E} | yes | reject (cycle A-B-C) | unchanged |
| 4: C-D | {A,B,C} {D} {E} | no | accept | {A,B,C,D} {E} |
| 5: B-D | {A,B,C,D} {E} | yes | reject | unchanged |
| 6: D-E | {A,B,C,D} {E} | no | accept | {A,B,C,D,E} |
| 7: C-E | one set | yes | reject | unchanged |
MST edges: A-B, B-C, C-D, D-E, total weight 1 + 2 + 4 + 6 = 13. After the fourth acceptance (V − 1 = 4 edges) the algorithm could stop.
Without union-find, each “would this create a cycle?” check is a traversal of the forest built so far, which has up to V − 1 edges: O(V) per edge, O(E·V) overall. With union-find (union by rank and path compression), each check is O(α(V)) amortized, so the sort, O(E log E), dominates.
21.6 ★★ Sliding-window maximum. 21.2 cites the monotonic deque. Implement window_max(xs, k), which returns the maximum of every window of k consecutive elements in O(n) total. Trace it on [1, 3, -1, -3, 5, 3, 6, 7] with k = 3, showing the deque’s values after each element. Then justify the O(n) bound.
Hint
Store indices, not values, and keep their values decreasing from front to back. A new element makes every smaller element behind it useless forever.
Solution
from collections import deque
def window_max(xs, k):
dq = deque() # indices; their values decrease front to back
out = []
for i, x in enumerate(xs):
while dq and xs[dq[-1]] <= x:
dq.pop() # dominated: older and no larger than x
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # front has left the window
if i >= k - 1:
out.append(xs[dq[0]])
return out
assert window_max([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
| i | x | Deque values after | Output |
|---|---|---|---|
| 0 | 1 | [1] | |
| 1 | 3 | [3] (1 popped) | |
| 2 | −1 | [3, −1] | 3 |
| 3 | −3 | [3, −1, −3] | 3 |
| 4 | 5 | [5] (−3, −1, 3 popped) | 5 |
| 5 | 3 | [5, 3] | 5 |
| 6 | 6 | [6] (3, 5 popped) | 6 |
| 7 | 7 | [7] (6 popped) | 7 |
Why O(n): each index is appended exactly once and removed at most once (from the back by a larger element, or from the front by leaving the window). So across the whole run there are at most n appends and n removals, even though a single step can pop many elements, as at i = 4. That is O(1) amortized per element. A popped element is safe to discard because the newer, larger x will be in every future window that the popped one would have been in.
21.7 ★★★ Bitmask N-Queens. 21.4 says bitmasks replace the three sets in solve for small n. Write count_queens(n) that counts all solutions using three integers: occupied columns, and the two diagonal directions shifted so that bit positions line up with the current row. Verify n = 8 gives 92. Explain why the diagonal masks shift by one bit per row.
Hint
free & -free isolates the lowest set bit of free.
Solution
def count_queens(n):
full = (1 << n) - 1 # n ones: every column
def place(cols, d1, d2):
if cols == full: # one queen in every column: solved
return 1
total = 0
free = full & ~(cols | d1 | d2) # columns not attacked in this row
while free:
bit = free & -free # lowest free column
free ^= bit # remove it from the candidates
total += place(cols | bit,
((d1 | bit) << 1) & full,
(d2 | bit) >> 1)
return total
return place(0, 0, 0)
assert [count_queens(n) for n in range(1, 11)] == [1, 0, 0, 2, 10, 4, 40, 92, 352, 724]
Why the shifts. A queen at column c attacks column c + 1 in the next row along one diagonal and column c − 1 along the other, then c + 2 and c − 2 a row later, and so on. Rather than store diagonal ids (row − col, row + col in the set version), the masks store which columns in the current row each diagonal family attacks. Moving down one row moves every attack one column over, which is a shift left by one for one family and right by one for the other. & full drops attacks that slide off the board; the right shift drops them automatically.
Why it is faster. The conflict check that took three hash lookups per candidate column is one ~(cols | d1 | d2) for the whole row, and the loop visits only the free columns instead of testing all n. Undo is free: each recursive call receives new integers, so there is nothing to remove afterwards. This is the 21.4 principle taken to its limit, where state is cheap enough to pass by value, so undo disappears.
Where this connects
- Chapter 9: Heaps and Priority Queues. The priority queue behind every greedy algorithm
- Chapter 11: Graphs—Modeling Relationships. The graph algorithms these paradigms produce
Chapter 22: Practical Considerations
Everything up to here has been about what structures are. This chapter is about the decisions you actually make on a Tuesday afternoon: which one to reach for, what your language already gives you, what to do when it’s too slow, and how to find the bug when it’s wrong.
22.1 Choosing the Right Structure
Questions to ask:
- What operations are most frequent?
- What is the access pattern?
- How large is the data?
- What are the memory constraints?
- Is thread safety required?
Those five questions are the right ones. Here is how to actually use them.
Start with question 1, and be specific about proportions. “I need lookups and inserts” is not an answer; “99% lookups, 1% inserts, no iteration” is. The ratio decides everything. A sorted array beats a hash table for a read-mostly set that fits in cache, and loses catastrophically the moment writes are frequent.
Question 2 is the one people skip and shouldn’t. Sequential access and random access are different problems, and Chapter 16 explains why the gap is 10–100×, not 10–20%. Ask specifically: do I ever need the elements in order? That single question separates hash tables from trees, and it is the most common source of a wrong initial choice: people reach for a hash map, then discover six months later that they need ordered iteration.
Question 3 changes which model applies. Under ~1,000 elements, constant factors dominate and a linear scan of an array frequently beats every “better” structure. It is one cache line at a time with perfect prefetching, and there is no hashing or pointer-chasing. Above what fits in RAM, the external memory model applies and B-trees or LSM trees are the only serious options.
A decision table for the common cases:
| Need | Reach for | Not |
|---|---|---|
| Key → value, any order | Hash table | Tree (slower, more memory) |
| Key → value, sorted iteration or range queries | Balanced BST / B-tree | Hash table (no order at all) |
| Append and index by position | Dynamic array | Linked list |
| Insert/remove at both ends | Deque | Array (O(n) at the front) |
| Repeatedly extract min or max | Binary heap | Sorted array (O(n) insert) |
| Membership only, huge set, false positives OK | Bloom filter | Hash set (10–100× the memory) |
| Prefix search, autocomplete | Trie / radix tree | Hash table (prefixes need order) |
| Connectivity under merging | Union-find | Graph traversal per query |
| Range sum / range min with updates | Fenwick or segment tree | Recomputing the range |
| Under ~100 items | Array, honestly | Anything clever |
Question 5 deserves a warning. “Is thread safety required?” is often answered too fast, in both directions. Wrapping every structure in a lock because the application is multithreaded is how you get a program that is slower than the single-threaded version. Conversely, a structure reachable from two threads without synchronization is broken even if it has never visibly failed. The best answer is usually to avoid sharing at all: see Chapter 18.
22.2 Language-Specific Collections
| Language | Key Collections |
|---|---|
| Python | list, dict, set, tuple |
| Java | ArrayList, HashMap, TreeMap, PriorityQueue |
| C++ | vector, unordered_map, map, priority_queue |
| JavaScript | Array, Object, Map, Set |
| Go | slice, map |
| Rust | Vec, HashMap, BTreeMap, BTreeSet |
What matters is what those names are actually implemented as, because the names hide real differences:
| Collection | Implementation | Worth knowing |
|---|---|---|
Python dict | Open addressing, compact + insertion-ordered since 3.7 | Ordering is a language guarantee now, not an accident |
Python list | Dynamic array, ~1.125× growth | insert(0, x) is O(n), use collections.deque |
Java HashMap | Chaining; buckets become red-black trees past 8 entries | The treeification defends against collision DoS |
Java TreeMap | Red-black tree | Sorted iteration, floorKey/ceilingKey |
C++ std::map | Red-black tree | Ordered, unordered_map is the hash table |
C++ std::vector | Dynamic array, typically 1.5–2× growth | reserve() when the size is known |
C++ std::list | Doubly linked | Almost always the wrong choice; vector wins even for middle insertion at small n |
Go map | Open addressing with 8-slot buckets | Iteration order is deliberately randomized |
Rust HashMap | SwissTable (hashbrown), SipHash by default | Swap in FxHash for non-adversarial internal use |
Rust BTreeMap | B-tree, not a BST | Cache-friendlier than a red-black tree |
JS Object vs Map | Hidden classes vs real hash map | Map for dynamic keys; Object keys are strings/symbols |
Three practical notes that catch people repeatedly:
- Go randomizes map iteration order on purpose, so that code cannot come to depend on it. If you need order, sort the keys.
- Rust’s default hasher is SipHash, chosen to resist collision attacks, and it is measurably slower than a non-cryptographic hash. For internal maps with trusted keys,
FxHashMapis often 2× faster. - C++
std::listis nearly always a mistake. The textbook case for a linked list (cheap insertion in the middle) loses tostd::vectorat surprisingly large n, because finding the insertion point requires a traversal and the traversal is cache-hostile. Measure before believing otherwise.
22.3 Performance Optimization
- Profiling first: Don’t optimize without measuring
- Cache awareness: Sequential access > random access
- Memory pools: Reduce allocation overhead
- Object pooling: Reuse frequently allocated objects
Profile first, and profile the right thing. A wall-clock profiler tells you where time goes; it does not tell you why. If a function is slow and the arithmetic is trivial, the answer is usually memory, and you need hardware counters to see it:
perf stat -e cache-misses,cache-references,instructions,cycles ./program
An instructions-per-cycle figure below ~1.0 with a high cache-miss rate means the CPU is waiting on memory, and no amount of algorithmic micro-tuning will help, the layout is the problem. Above ~2.0 IPC, you are compute-bound and the algorithm is the thing to change. This single distinction redirects more optimization effort than any other measurement.
The optimization ladder, roughly in order of payoff per unit of effort:
- Better algorithm or structure. O(n²) → O(n log n) beats every constant-factor trick combined. This is where the leverage is, and the rest of this book is about it.
- Better memory layout. Struct-of-arrays over array-of-structs; contiguous over pointer-chasing; shrink the hot struct so more fits per cache line. Often 2–10×.
- Fewer allocations. Pre-size containers (
reserve,make([]T, 0, n)). Reuse buffers. Arena-allocate objects with a shared lifetime. Allocation is rarely the headline cost, but allocation churn wrecks locality and GC pause times. - Batching. Amortize per-operation overhead, one bulk insert instead of n inserts, one syscall instead of n.
- Micro-optimization. Branch elimination, SIMD, intrinsics. Real, but last, and easily undone by the next compiler version.
On object pooling specifically: it is a genuine win for expensive-to-construct objects (database connections, threads, large buffers) and frequently a net loss for cheap ones in a garbage-collected language. Modern generational GCs allocate by bumping a pointer and collect short-lived objects nearly for free; a pool converts those into long-lived objects that survive into the old generation and must be traced on every major collection. Pool connections, not integers.
On premature pessimization, which is the more common error than premature optimization: choosing an O(n) structure where an O(1) one was equally convenient, copying a large object where a reference would do, or building a string in a loop with +=. None of these are “optimizations” to skip. They are defaults to get right the first time.
22.4 Debugging Data Structure Bugs
- Invariants: Check them during development
- Visualization: Draw the structure
- Testing: Property-based testing (QuickCheck)
- Assertions: Validate preconditions and postconditions
Data structure bugs have a characteristic signature: the structure is silently wrong long before anything visibly fails. A corrupted red-black tree keeps answering queries: it just answers some of them incorrectly, and the crash comes later, somewhere else. This is why the techniques below emphasize detection near the cause rather than debugging at the point of failure.
Write the invariant checker first. For every structure, there is a predicate that must hold after every operation. Write it as code, not as a comment:
def check_bst(node, lo=float('-inf'), hi=float('inf')):
"""Every BST bug this catches would otherwise surface as a wrong query."""
if node is None:
return True
if not (lo < node.key < hi):
return False
return (check_bst(node.left, lo, node.key)
and check_bst(node.right, node.key, hi))
def check_heap(a, i=0):
l, r = 2*i + 1, 2*i + 2
for c in (l, r):
if c < len(a) and (a[i] > a[c] or not check_heap(a, c)):
return False
return True
Note that check_bst must thread bounds down the recursion. The version that only compares each node to its immediate children is the classic wrong answer: it accepts trees that violate the BST property across subtrees.
Then run the checker after every mutation in debug builds:
def insert(self, key):
self._insert(key)
assert self._check_invariants(), f"invariant broken inserting {key}"
This turns a bug that would surface a thousand operations later into one that surfaces on the operation that caused it. For a red-black tree, check all five properties; for a B-tree, check occupancy bounds and uniform leaf depth; for union-find, check that no parent chain cycles.
Property-based testing is the highest-value testing technique for this domain, because data structure correctness is naturally expressible as properties, and random generation finds the edge cases you did not think of: empty, single element, duplicates, exactly-at-capacity:
from hypothesis import given, strategies as st
@given(st.lists(st.integers()))
def test_matches_reference(items):
"""The structure must behave identically to an obviously-correct model."""
mine, reference = MyBST(), set()
for x in items:
mine.insert(x); reference.add(x)
assert sorted(mine.in_order()) == sorted(reference)
@given(st.lists(st.integers()), st.integers())
def test_search_agrees(items, probe):
mine = MyBST()
for x in items:
mine.insert(x)
assert mine.contains(probe) == (probe in items)
That first pattern (model-based testing against a simple, obviously-correct reference implementation)is the most effective single technique for validating a data structure. Your red-black tree should behave exactly like a sorted list; your LRU cache should behave exactly like an ordered dict with manual eviction. The reference can be absurdly slow; it only has to be right.
Hypothesis (Python), QuickCheck (Haskell), proptest (Rust), and jqwik (Java) all shrink failing cases automatically, so a failure on a 500-element list is reported as the 3-element list that actually breaks it.
Visualize when the invariant checker says “broken” but not why. Graphviz output is about ten lines of code and worth every one:
def to_dot(node, out):
if node is None:
return
for child, side in ((node.left, 'L'), (node.right, 'R')):
if child:
out.append(f' "{node.key}" -> "{child.key}" [label="{side}"];')
to_dot(child, out)
For memory bugs (use-after-free, double-free, buffer overruns in hand-written C structures) reach for the sanitizers rather than reasoning: -fsanitize=address and -fsanitize=undefined find in seconds what code review misses for weeks. For concurrent structures, -fsanitize=thread, Java’s JCStress, or Rust’s loom are effectively mandatory; a race that has not manifested in testing is not a race that does not exist.
A checklist for the specific bug classes that recur:
| Symptom | Usual cause |
|---|---|
| Works until it doesn’t, at a suspiciously round size | Resize/rehash logic |
| Wrong answer, no crash | Broken invariant, write the checker |
| Crash far from the real problem | Memory corruption, run ASan |
| Fails only under load | Race, run TSan |
| Fails only on the empty or single-element case | Missing base case; sentinel handling |
| Fails on duplicates | Undefined duplicate policy, decide and document it |
| O(n²) in production, fast in tests | Test data was accidentally random; production data is sorted |
That last row is worth internalizing. Sorted input is the worst case for a naive BST and for quicksort with a fixed pivot, and real-world data arrives sorted far more often than random test data does: by timestamp, by ID, by insertion order. Test with sorted, reverse-sorted, and all-identical inputs deliberately.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
22.1 ★ Use the decision table. For each requirement, pick a structure from the table in 22.1 and give the one-line reason. Say what you would not use.
- A web crawler must skip URLs it has already fetched. It will see about 2 billion URLs, and occasionally skipping a page it has not fetched is acceptable.
- A session store maps random session ids to user records. Nobody ever iterates it in order.
- A trading system must answer “all orders placed between 10:00:00 and 10:05:00” while orders keep arriving.
- A job scheduler repeatedly runs whichever pending job has the earliest deadline.
- A service checks 30 feature flags by name on each request.
Solution
- Bloom filter. Membership only, false positives allowed (a false positive means one skipped page). At about 10 bits per element, 2 billion URLs take about 2.5 GB. A hash set of the URL strings themselves would need well over 100 GB.
- Hash table. Key to value with no ordering requirement is its exact job. A balanced tree would spend O(log n) comparisons and more memory to maintain an order nobody uses.
- Balanced BST or B-tree keyed by timestamp. It is a range query, so the structure must keep keys ordered: find 10:00:00 in O(log n), then walk forward. A hash table cannot answer it without scanning everything.
- Binary heap keyed by deadline. “Repeatedly extract the minimum” with inserts arriving is the heap’s interface. A sorted array pays O(n) per insert.
- An array (or a plain dict), nothing clever. At 30 items, constant factors dominate. A linear scan over 30 short strings is fast and fits in a few cache lines, and the “Under ~100 items” row applies. Either choice is fine; building anything elaborate is not.
22.2 ★ The classic wrong BST checker. 22.4 warns that a checker comparing each node only to its immediate children is wrong. Write that naive version, and give a tree it accepts that check_bst correctly rejects.
Solution
class Node:
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right = key, left, right
def check_bst(node, lo=float('-inf'), hi=float('inf')):
if node is None:
return True
if not (lo < node.key < hi):
return False
return (check_bst(node.left, lo, node.key)
and check_bst(node.right, node.key, hi))
def check_bst_naive(node):
"""WRONG: only compares parents with their own children."""
if node is None:
return True
if node.left and not node.left.key < node.key:
return False
if node.right and not node.right.key > node.key:
return False
return check_bst_naive(node.left) and check_bst_naive(node.right)
# 10
# / \
# 5 20
# / \
# 2 15 <- 15 is in 10's LEFT subtree but larger than 10
tree = Node(10, Node(5, Node(2), Node(15)), Node(20))
assert check_bst_naive(tree) is True
assert check_bst(tree) is False
Every parent-child pair is in order (2 < 5 < 15, 5 < 10 < 20), so the naive check passes. But 15 sits in the left subtree of 10, so a search for 15 goes right at the root and never finds it. The BST property constrains a node against all its ancestors, which is exactly what the lo/hi bounds carry down the recursion. When check_bst reaches 15, its window is (5, 10), and 15 falls outside it.
22.3 ★★ An invariant checker for union-find. 22.4 says that for union-find you should “check that no parent chain cycles”. Write check_union_find(parent) for the array representation (parent[i] == i marks a root) that returns True exactly when every element’s parent chain ends at a root and no parent index is out of range. It must run in O(n) total, not O(n) per element.
Hint
Mark nodes with three states: unvisited, on the walk you are doing right now, and already verified. Meeting a node from your own walk means a cycle; meeting a verified node means you can stop early.
Solution
def check_union_find(parent):
"""True iff every parent chain ends at a root (parent[r] == r). O(n)."""
n = len(parent)
state = [0] * n # 0 = unvisited, 1 = on current walk, 2 = verified
for start in range(n):
walk, x = [], start
while state[x] == 0:
state[x] = 1
walk.append(x)
p = parent[x]
if not 0 <= p < n:
return False # parent points outside the structure
if p == x:
break # reached a root
x = p
else:
if state[x] == 1:
return False # came back to a node on this walk: a cycle
for y in walk:
state[y] = 2
return True
assert check_union_find([0, 0, 1, 3, 3]) # two trees: {0,1,2} and {3,4}
assert check_union_find([])
assert not check_union_find([1, 2, 0, 3]) # 0 -> 1 -> 2 -> 0
assert not check_union_find([0, 2, 1]) # 1 <-> 2, never reaches root 0
assert not check_union_find([0, 5]) # out of range
Each walk stops at a root, at an already verified node, or at a cycle. Every node is marked 1 once and 2 once, and is never walked through again after being verified, so the total work is O(n) even though individual walks can be long. The while ... else clause runs only when the loop ends because it reached an already-visited node (not via break), which is exactly when that node might be on the current walk.
A naive version that walks the full chain from every element is O(n²) in the worst case (a single long chain), which would make “check after every operation” in a debug build painfully slow. If the structure also tracks set sizes for union by size, a natural extension checks that each root’s stored size equals the number of elements whose chain ends there.
22.4 ★★ Read the counters. Two programs are profiled with perf stat as in 22.3:
| instructions | cycles | cache-references | cache-misses | |
|---|---|---|---|---|
| Program P | 3.2 × 10⁹ | 8.0 × 10⁹ | 2.0 × 10⁸ | 1.2 × 10⁸ |
| Program Q | 1.2 × 10¹⁰ | 4.8 × 10⁹ | 5.0 × 10⁷ | 1.0 × 10⁶ |
Compute IPC and the cache-miss rate for each. Which rung of the optimization ladder should each team try first, and what concretely would you look for?
Solution
| IPC | Miss rate | |
|---|---|---|
| P | 3.2 / 8.0 = 0.4 | 1.2 / 2.0 = 60% |
| Q | 12 / 4.8 = 2.5 | 0.1 / 5 = 2% |
P is memory-bound. An IPC of 0.4 means the core retires fewer than one instruction every two cycles, and 60% of cache references miss: the CPU is mostly waiting for data. Rung 2, memory layout. Look for pointer-chasing structures on the hot path (linked lists, a tree with one key per node, a hash table with chaining) and replace them with contiguous ones (arrays, B-tree-style wide nodes, open addressing), or shrink the hot struct so more of it fits per cache line. Tuning arithmetic will not help.
Q is compute-bound. IPC 2.5 with a 2% miss rate means data is arriving on time and the core is busy. Rung 1: look for an algorithmic improvement, such as work repeated inside a loop or a quadratic step that could be O(n log n). If the algorithm is already right, rung 5 (SIMD, branch elimination) is where the remaining speed is.
One caveat applies to both: rung 1 comes first if the algorithm is wrong. A quadratic algorithm can show either profile, and no layout fix will rescue it at large n.
22.5 ★★ Why the tests were fast. Count the comparisons a plain (unbalanced) BST makes when inserting the keys 0 to 999 in sorted order, and in a random order. Then explain why test_matches_reference in 22.4 is unlikely ever to exercise the slow case, and what to add so that it does.
Solution
import random
class Node:
def __init__(self, key):
self.key, self.left, self.right = key, None, None
def count_comparisons(keys):
root, comparisons = None, 0
for k in keys:
if root is None:
root = Node(k)
continue
node = root
while True:
comparisons += 1
if k < node.key:
if node.left is None:
node.left = Node(k)
break
node = node.left
else:
if node.right is None:
node.right = Node(k)
break
node = node.right
return comparisons
n = 1000
assert count_comparisons(range(n)) == n * (n - 1) // 2 # 499,500
shuffled = list(range(n))
random.shuffle(shuffled)
print(count_comparisons(shuffled)) # about 11,000
Sorted: key k walks past all k earlier keys, so the total is 0 + 1 + … + 999 = 499,500. Random: about 11,000 on average (the expected value is 2(n+1)Hₙ − 4n ≈ 10,986, where Hₙ is the n-th harmonic number). Same code, a 45× difference at n = 1000, and the gap grows linearly with n.
st.lists(st.integers()) generates lists of arbitrary integers in arbitrary order. A long list that happens to be sorted is vanishingly rare, so the property test checks correctness on near-random shapes and never builds a deep chain. The test is right to pass (the tree is correct on sorted input, just slow), which is why this bug class shows up only in production.
The fixes are deliberate. Generate the adversarial shapes 22.4 lists: st.lists(st.integers()).map(sorted), the same mapped through sorted(..., reverse=True), and lists of one repeated value. And add a performance property alongside the correctness one: for a structure that claims balance, assert that its height stays within its guaranteed bound (about 2 log₂ n for a red-black tree) after every operation. A height check turns “slow” into “failing”, which a test can catch.
22.6 ★★★ Find an LRU bug with a model-based test. This LRU cache has a bug:
class BuggyLRU:
def __init__(self, capacity):
self.capacity = capacity
self.data = {} # Python dicts keep insertion order
def get(self, key):
return self.data.get(key)
def put(self, key, value):
if key in self.data:
del self.data[key]
elif len(self.data) == self.capacity:
oldest = next(iter(self.data))
del self.data[oldest]
self.data[key] = value
Without reading the code for the bug, write the test 22.4 recommends: an obviously correct model built on collections.OrderedDict, random operation sequences, and a comparison after every get. Add a simple shrinker that removes operations while the failure persists. What minimal failing sequence does it find, what is the bug, and what is the fix?
Hint
Keep keys and capacity tiny (keys 0 to 4, capacity 1 to 3). Bugs in eviction logic need collisions, and a large key space makes them rare.
Solution
import random
from collections import OrderedDict
class ModelLRU:
"""Obviously correct reference: slow is fine, wrong is not."""
def __init__(self, capacity):
self.capacity = capacity
self.d = OrderedDict()
def get(self, key):
if key not in self.d:
return None
self.d.move_to_end(key)
return self.d[key]
def put(self, key, value):
if key in self.d:
self.d.move_to_end(key)
self.d[key] = value
if len(self.d) > self.capacity:
self.d.popitem(last=False)
def fails(make_impl, capacity, ops):
impl, model = make_impl(capacity), ModelLRU(capacity)
for op, key in ops:
if op == "put":
impl.put(key, key)
model.put(key, key)
elif impl.get(key) != model.get(key):
return True
return False
def find_failure(make_impl, trials=10_000, seed=0):
rng = random.Random(seed)
for _ in range(trials):
capacity = rng.randint(1, 3)
ops = [(rng.choice(["get", "put"]), rng.randint(0, 4))
for _ in range(rng.randint(1, 12))]
if fails(make_impl, capacity, ops):
return capacity, ops
return None
def shrink(make_impl, capacity, ops):
"""Greedily drop single operations while the sequence still fails."""
changed = True
while changed:
changed = False
for i in range(len(ops)):
candidate = ops[:i] + ops[i + 1:]
if fails(make_impl, capacity, candidate):
ops, changed = candidate, True
break
return ops
capacity, ops = find_failure(BuggyLRU)
print(capacity, shrink(BuggyLRU, capacity, ops))
With this seed the shrunk failure is, at capacity 2:
put 0, put 3, get 0, put 4, get 0
The model: get 0 makes 0 the most recently used, so put 4 evicts 3, and the final get 0 returns 0. The buggy cache returns None: it evicted 0. get does not refresh recency, so the cache evicts the least recently inserted key, which is FIFO, not LRU. Every test that only ever calls put, or calls get on keys that are never near eviction, passes.
The fix moves the key to the most-recent end on every hit:
class FixedLRU(BuggyLRU):
def get(self, key):
if key not in self.data:
return None
value = self.data.pop(key) # re-insert at the most-recent end
self.data[key] = value
return value
assert find_failure(FixedLRU) is None
assert find_failure(FixedLRU, trials=50_000, seed=7) is None
The model took ten lines and has no cleverness in it, which is the point: it is easy to trust. The shrinker is a crude version of what Hypothesis does automatically, and it turned an 11-operation random failure into 5 operations that explain the bug at a glance.
Where this connects
- Chapter 16: External Memory and Cache-Oblivious Structures. Why the profiler says memory and not arithmetic
- Chapter 25: Complete Selection Guide and Complexity Reference. The selection matrix in reference form
Volume IV: Competitive Programming and Research-Grade Structures
Chapters
- Chapter 23: Advanced Competitive Programming Data Structures
- Chapter 24: Research-Grade Data Structures
- Chapter 25: Complete Selection Guide and Complexity Reference
Competitive-programming resources and the research papers behind these structures are collected in the Bibliography.
A note on numbering: an earlier draft had a Chapter 26 here, an extended bibliography. Its content was folded into the appendices, and the chapter numbers were kept stable so published links do not break. Volume V therefore begins at Chapter 27.
Chapter 23: Advanced Competitive Programming Data Structures
23.1 Introduction to Competitive Programming Data Structures
Competitive programming demands data structures that excel under specific constraints: fast operations, minimal memory, and elegant implementation. While the foundational structures covered earlier serve as building blocks, competitive programming has developed specialized structures optimized for algorithmic challenges.
This chapter covers structures essential for International Olympiad in Informatics (IOI), International Collegiate Programming Contest (ICPC), and Codeforces/Topcoder competitions. These structures often sacrifice generality or worst-case guarantees for practical performance and competitive implementation.
23.2 Segment Trees with Lazy Propagation
Conceptual Foundation
A segment tree is a binary tree that represents an array segment, enabling efficient range queries and updates. Lazy propagation defers updates until necessary, dramatically improving performance for range modifications.
Core Properties:
- Represents array in binary tree form
- Each node stores aggregate of its segment (sum, min, max, etc.)
- Height: O(log n)
- Space: O(n) with 4n safe upper bound
Mechanism: Range Query with Lazy Propagation
class SegmentTree:
def __init__(self, arr):
self.n = len(arr)
self.tree = [0] * (4 * self.n)
self.lazy = [0] * (4 * self.n)
self._build(1, 0, self.n - 1, arr)
def _build(self, node, l, r, arr):
if l == r:
self.tree[node] = arr[l]
else:
mid = (l + r) // 2
self._build(node * 2, l, mid, arr)
self._build(node * 2 + 1, mid + 1, r, arr)
self.tree[node] = self.tree[node * 2] + self.tree[node * 2 + 1]
def _push(self, node, l, r):
"""Push lazy values to children"""
if self.lazy[node] != 0:
mid = (l + r) // 2
# Apply to left child
self.tree[node * 2] += self.lazy[node] * (mid - l + 1)
self.lazy[node * 2] += self.lazy[node]
# Apply to right child
self.tree[node * 2 + 1] += self.lazy[node] * (r - mid)
self.lazy[node * 2 + 1] += self.lazy[node]
self.lazy[node] = 0
def range_update(self, node, l, r, ql, qr, val):
if ql <= l and r <= qr:
self.tree[node] += val * (r - l + 1)
self.lazy[node] += val
return
if r < ql or l > qr:
return
self._push(node, l, r)
mid = (l + r) // 2
self.range_update(node * 2, l, mid, ql, qr, val)
self.range_update(node * 2 + 1, mid + 1, r, ql, qr, val)
self.tree[node] = self.tree[node * 2] + self.tree[node * 2 + 1]
def range_query(self, node, l, r, ql, qr):
if ql <= l and r <= qr:
return self.tree[node]
if r < ql or l > qr:
return 0
self._push(node, l, r)
mid = (l + r) // 2
return (self.range_query(node * 2, l, mid, ql, qr) +
self.range_query(node * 2 + 1, mid + 1, r, ql, qr))
Complexity Analysis
| Operation | Time Complexity | Space |
|---|---|---|
| Build | O(n) | O(n) |
| Range Query | O(log n) | - |
| Range Update | O(log n) | - |
| Point Query | O(log n) | - |
| Point Update | O(log n) | - |
Advanced Variants
Merge Sort Tree: For k-th smallest queries, store sorted vectors at each node.
Segment Tree Beats: For range min/max updates with constraints.
Dynamic Segment Tree: For values outside initial range, create nodes on demand.
23.3 Fenwick Trees (Binary Indexed Trees)
Conceptual Foundation
A Fenwick tree, invented by Boris Ryabko in 1989 and popularized by Peter Fenwick, provides O(log n) prefix operations with minimal memory. It’s simpler than segment trees for prefix-sum based queries.
Key Insight: Use binary representation to represent ranges as sums of power-of-two sized blocks.
Mechanism
class FenwickTree:
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def add(self, idx, delta):
"""Add delta at position idx (1-indexed)"""
while idx <= self.n:
self.bit[idx] += delta
idx += idx & (-idx)
def prefix_sum(self, idx):
"""Sum of [1, idx]"""
result = 0
while idx > 0:
result += self.bit[idx]
idx -= idx & (-idx)
return result
def range_sum(self, l, r):
"""Sum of [l, r]"""
return self.prefix_sum(r) - self.prefix_sum(l - 1)
def find_kth(self, k):
"""Find smallest idx with prefix_sum >= k"""
idx = 0
bit_mask = 1 << (self.n.bit_length() - 1)
while bit_mask:
t_idx = idx + bit_mask
if t_idx <= self.n and self.bit[t_idx] < k:
idx = t_idx
k -= self.bit[t_idx]
bit_mask >>= 1
return idx + 1
2D Fenwick Tree
class BIT2D:
def __init__(self, n, m):
self.n, self.m = n, m
self.bit = [[0] * (m + 1) for _ in range(n + 1)]
def add(self, x, y, delta):
i = x
while i <= self.n:
j = y
while j <= self.m:
self.bit[i][j] += delta
j += j & (-j)
i += i & (-i)
def prefix_sum(self, x, y):
result = 0
i = x
while i > 0:
j = y
while j > 0:
result += self.bit[i][j]
j -= j & (-j)
i -= i & (-i)
return result
23.4 Heavy-Light Decomposition
Conceptual Foundation
Heavy-Light Decomposition (HLD), introduced by Sleator and Tarjan, enables O(log n) path queries on trees by decomposing the tree into chains where heavy edges form continuous segments.
Key Concepts:
- Heavy edge: Edge to child with largest subtree
- Light edge: All other edges
- Heavy path: Path following heavy edges
- Decomposition ensures O(log n) chains per path
Mechanism
class HeavyLightDecomposition:
def __init__(self, n, edges):
self.n = n
self.adj = [[] for _ in range(n)]
for u, v in edges:
self.adj[u].append(v)
self.adj[v].append(u)
self.parent = [-1] * n
self.depth = [0] * n
self.size = [0] * n
self.heavy = [-1] * n
self.head = [0] * n
self.pos = [0] * n
self.cur_pos = 0
self._dfs(0)
self._decompose(0, 0)
def _dfs(self, v):
self.size[v] = 1
max_size = 0
for u in self.adj[v]:
if u != self.parent[v]:
self.parent[u] = v
self.depth[u] = self.depth[v] + 1
self._dfs(u)
self.size[v] += self.size[u]
if self.size[u] > max_size:
max_size = self.size[u]
self.heavy[v] = u
def _decompose(self, v, h):
self.head[v] = h
self.pos[v] = self.cur_pos
self.cur_pos += 1
if self.heavy[v] != -1:
self._decompose(self.heavy[v], h)
for u in self.adj[v]:
if u != self.parent[v] and u != self.heavy[v]:
self._decompose(u, u)
def query_path(self, u, v, segtree):
"""Query on path u-v using segment tree"""
result = 0
while self.head[u] != self.head[v]:
if self.depth[self.head[u]] < self.depth[self.head[v]]:
u, v = v, u
head_u = self.head[u]
result += segtree.range_query(self.pos[head_u], self.pos[u])
u = self.parent[head_u]
# Same head
if self.depth[u] > self.depth[v]:
u, v = v, u
result += segtree.range_query(self.pos[u], self.pos[v])
return result
Applications
| Query Type | Complexity | Example |
|---|---|---|
| Path sum | O(log² n) | Sum of node values on path |
| Path max | O(log² n) | Maximum on path |
| Path update | O(log² n) | Add value to all nodes on path |
| Subtree query | O(log n) | Query entire subtree |
23.5 Link-Cut Trees
Conceptual Foundation
Link-cut trees, invented by Sleator and Tarjan in 1983, support dynamic forest operations: linking trees, cutting edges, and querying aggregates on paths, all in O(log n) amortized time.
Operations:
- link(u, v): Connect u as child of v
- cut(u): Remove edge between u and parent
- evert(u): Make u the root
- path_query(u, v): Aggregate on u-v path
Mechanism
class LinkCutTree:
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
self.rev = False
self.sum = val
def _is_root(self, x):
"""True if x is the root of its splay tree (its parent pointer,
if any, is a path-parent pointer, not a splay-tree edge)."""
return x.parent is None or (x.parent.left is not x and
x.parent.right is not x)
def _push(self, x):
if x and x.rev:
x.left, x.right = x.right, x.left
if x.left: x.left.rev ^= True
if x.right: x.right.rev ^= True
x.rev = False
def _update(self, x):
x.sum = x.val
if x.left: x.sum += x.left.sum
if x.right: x.sum += x.right.sum
def _rotate(self, x):
p = x.parent
g = p.parent
if not self._is_root(p):
if g.left is p:
g.left = x
else:
g.right = x
x.parent = g
if x is p.left:
p.left = x.right
if x.right: x.right.parent = p
x.right = p
else:
p.right = x.left
if x.left: x.left.parent = p
x.left = p
p.parent = x
self._update(p)
self._update(x)
def _splay(self, x):
stack = [x]
y = x
while not self._is_root(y):
y = y.parent
stack.append(y)
while stack:
self._push(stack.pop())
while not self._is_root(x):
p = x.parent
if not self._is_root(p):
g = p.parent
if (g.left is p) == (p.left is x):
self._rotate(p) # zig-zig
else:
self._rotate(x) # zig-zag
self._rotate(x)
def access(self, x):
last = None
while x:
self._splay(x)
x.right = last
self._update(x)
last = x
x = x.parent
return last
def make_root(self, x):
self.access(x)
self._splay(x)
x.rev ^= True
def link(self, x, y):
self.make_root(x)
x.parent = y
def cut(self, x, y):
self.make_root(x)
self.access(y)
self._splay(y)
self._push(x)
if y.left is x and x.right is None:
x.parent = None
y.left = None
self._update(y)
def query_path(self, x, y):
self.make_root(x)
self.access(y)
self._splay(y)
return y.sum
23.6 Mo’s Algorithm
Conceptual Foundation
Mo’s algorithm answers offline range queries in O((n + q)√n) by reordering queries to minimize pointer movement. It’s particularly effective for queries with additive functions.
Key Insight: Sort queries by block of L, then by R for optimal pointer movement.
Mechanism
class MoSolver:
def __init__(self, arr, queries):
self.arr = arr
self.queries = queries
self.block_size = int(len(arr) ** 0.5)
self.answers = [0] * len(queries)
self._process()
def _process(self):
# Sort queries: block by L, then by R (alternating for optimization)
self.queries.sort(key=lambda x: (
x.l // self.block_size,
x.r if (x.l // self.block_size) % 2 == 0 else -x.r
))
cur_l, cur_r = 0, -1
for q in self.queries:
while cur_l > q.l:
cur_l -= 1
self._add(cur_l)
while cur_r < q.r:
cur_r += 1
self._add(cur_r)
while cur_l < q.l:
self._remove(cur_l)
cur_l += 1
while cur_r > q.r:
self._remove(cur_r)
cur_r -= 1
self.answers[q.idx] = self._get_answer()
def _add(self, idx):
# Update frequency and current answer
pass
def _remove(self, idx):
# Update frequency and current answer
pass
def _get_answer(self):
return 0
Variants
Mo’s on Trees: Use Euler tour to flatten tree into array.
3D Mo’s: Add time dimension for updates.
Mo’s with Rollback: For answers that are cheap to extend but hard to shrink (maximum, DSU connectivity): each query rebuilds from its block boundary and rolls the left-side additions back.
23.7 Suffix Automaton
Conceptual Foundation
A suffix automaton (SAM) recognizes all substrings of a string in O(n) construction time, with at most 2n-1 states. It’s a deterministic acyclic finite automaton.
Properties:
- Minimum DFA for all substrings
- Size ≤ 2n - 1
- Links form suffix links (longest proper suffix)
Mechanism
class SuffixAutomaton:
def __init__(self):
self.next = [dict()] # state 0: initial
self.link = [-1]
self.len = [0]
self.last = 0
def extend(self, c):
p = self.last
cur = len(self.next)
self.next.append(dict())
self.len.append(self.len[p] + 1)
self.link.append(0)
while p >= 0 and c not in self.next[p]:
self.next[p][c] = cur
p = self.link[p]
if p == -1:
self.link[cur] = 0
else:
q = self.next[p][c]
if self.len[p] + 1 == self.len[q]:
self.link[cur] = q
else:
clone = len(self.next)
self.next.append(self.next[q].copy())
self.len.append(self.len[p] + 1)
self.link.append(self.link[q])
while p >= 0 and self.next[p].get(c) == q:
self.next[p][c] = clone
p = self.link[p]
self.link[q] = self.link[cur] = clone
self.last = cur
return cur
Applications
| Query | Complexity | Description |
|---|---|---|
| Substring check | O(m) | Follow transitions |
| Distinct substrings | O(n) | Sum(len[v] - len[link[v]]) |
| Longest common substring | O(n log n) | With two SAMs |
| Occurrences | O(m) | Follow + subtree sum |
23.8 Palindromic Tree (Eertree)
Conceptual Foundation
The Palindromic Tree, invented by Mikhail Rubinchik and later popularized, stores all distinct palindromic substrings. It uses two root nodes: odd length (-1) and even length (0).
Properties:
- O(n) construction
- O(n) distinct palindromes maximum
- Each node represents a palindrome
Mechanism
class PalindromicTree:
class Node:
def __init__(self, length, pos):
self.length = length
self.pos = pos # ending position
self.next = {}
self.link = 0
def __init__(self, s):
self.s = s
self.nodes = [self.Node(-1, -1), self.Node(0, -1)]
self.nodes[0].link = 0
self.nodes[1].link = 0
self.last = 1
self.size = 2
self.num_pal = 0
for i, c in enumerate(s):
self._add_char(i, c)
def _add_char(self, pos, c):
cur = self.last
while True:
cur_len = self.nodes[cur].length
if pos - cur_len - 1 >= 0 and self.s[pos - cur_len - 1] == c:
break
cur = self.nodes[cur].link
if c in self.nodes[cur].next:
self.last = self.nodes[cur].next[c]
return
new_node = self.Node(self.nodes[cur].length + 2, pos)
self.nodes.append(new_node)
self.nodes[cur].next[c] = self.size
self.size += 1
if new_node.length == 1:
new_node.link = 1
else:
tmp = self.nodes[cur].link
while True:
if pos - self.nodes[tmp].length - 1 >= 0 and \
self.s[pos - self.nodes[tmp].length - 1] == c:
break
tmp = self.nodes[tmp].link
new_node.link = self.nodes[tmp].next[c]
self.last = self.size - 1
self.num_pal += 1
23.9 Wavelet Trees
Conceptual Foundation
Wavelet trees answer range quantile queries (k-th smallest) in O(log σ) where σ is alphabet size, using only O(n log σ) space. They recursively partition based on the most significant bit.
Key Operation: K-th smallest in subarray [l, r]
Mechanism
class WaveletTree:
def __init__(self, arr, lo, hi):
self.lo = lo
self.hi = hi
self.b = []
if lo >= hi or not arr:
return
mid = (lo + hi + 1) // 2
self.c = lo
left_arr = []
right_arr = []
for x in arr:
if x < mid:
left_arr.append(x)
else:
right_arr.append(x)
self.b.append(len(left_arr))
self.left = WaveletTree(left_arr, lo, mid - 1)
self.right = WaveletTree(right_arr, mid, hi)
def kth(self, l, r, k):
"""k-th smallest (1-indexed) among positions l..r (0-indexed, inclusive)"""
if l > r:
return None
if self.lo == self.hi:
return self.lo
left_before = self.b[l - 1] if l > 0 else 0 # left-goers before l
in_left = self.b[r] - left_before # left-goers in [l, r]
if k <= in_left:
return self.left.kth(left_before, left_before + in_left - 1, k)
else:
right_before = l - left_before
in_right = (r - l + 1) - in_left
return self.right.kth(right_before, right_before + in_right - 1,
k - in_left)
23.10 Li Chao Trees
Conceptual Foundation
Li Chao trees maintain dynamic line sets for point queries in O(log C) where C is coordinate range. They’re ideal for online convex hull trick scenarios.
Operations:
- Add line (insert)
- Query minimum at point
Mechanism
class LiChaoNode:
def __init__(self, line=None):
self.line = line # (m, b) for y = mx + b
self.left = None
self.right = None
class LiChaoTree:
def __init__(self, x_left, x_right):
self.x_left = x_left
self.x_right = x_right
self.root = None
def f(self, line, x):
return line[0] * x + line[1]
def add_line(self, line):
self.root = self._add_line(self.root, self.x_left, self.x_right, line)
def _add_line(self, node, l, r, new_line):
if not node:
return LiChaoNode(new_line)
mid = (l + r) // 2
left_is_better = self.f(new_line, l) < self.f(node.line, l)
mid_is_better = self.f(new_line, mid) < self.f(node.line, mid)
if mid_is_better:
node.line, new_line = new_line, node.line
if r == l:
return node
if left_is_better != mid_is_better:
node.left = self._add_line(node.left, l, mid, new_line)
else:
node.right = self._add_line(node.right, mid + 1, r, new_line)
return node
def query(self, x):
return self._query(self.root, self.x_left, self.x_right, x)
def _query(self, node, l, r, x):
if not node:
return float('inf')
if l == r:
return self.f(node.line, x)
mid = (l + r) // 2
if x <= mid:
return min(self.f(node.line, x),
self._query(node.left, l, mid, x))
else:
return min(self.f(node.line, x),
self._query(node.right, mid + 1, r, x))
23.11 Sparse Tables
Conceptual Foundation
Sparse tables answer static range queries in O(1) after O(n log n) preprocessing, but only for idempotent operations (min, max, gcd).
Limitation: Not for sum (not idempotent).
Mechanism
class SparseTable:
def __init__(self, arr, op=min):
self.op = op
self.n = len(arr)
self.log = [0] * (self.n + 1)
for i in range(2, self.n + 1):
self.log[i] = self.log[i // 2] + 1
self.k = self.log[self.n] + 1
self.st = [[0] * self.n for _ in range(self.k)]
self.st[0] = arr[:]
for k in range(1, self.k):
for i in range(self.n - (1 << k) + 1):
self.st[k][i] = op(self.st[k-1][i],
self.st[k-1][i + (1 << (k-1))])
def query(self, l, r):
j = self.log[r - l + 1]
return self.op(self.st[j][l], self.st[j][r - (1 << j) + 1])
23.12 Cartesian Trees
Conceptual Foundation
A Cartesian tree maintains array order via inorder traversal while enforcing heap property. O(n) construction using monotonic stack.
Properties:
- Inorder traversal gives original array
- Heap property on values
- Unique for given array
Mechanism
def build_cartesian(arr):
n = len(arr)
parent = [-1] * n
left = [-1] * n
right = [-1] * n
stack = []
for i in range(n):
last = -1
while stack and arr[stack[-1]] > arr[i]:
last = stack.pop()
if stack:
right[stack[-1]] = i
parent[i] = stack[-1]
if last != -1:
parent[last] = i
left[i] = last
stack.append(i)
root = stack[0] if stack else -1
return root, parent, left, right
23.13 Sqrt Decomposition
Conceptual Foundation
Sqrt decomposition divides array into blocks of size √n, enabling O(√n) range queries. Simpler than segment trees but slower.
Mechanism
class SqrtDecomposition:
def __init__(self, arr):
self.arr = arr
self.n = len(arr)
self.block_size = int(self.n ** 0.5)
self.n_blocks = (self.n + self.block_size - 1) // self.block_size
self.block_sum = [0] * self.n_blocks
self.block_min = [float('inf')] * self.n_blocks
for i in range(self.n):
b = i // self.block_size
self.block_sum[b] += arr[i]
self.block_min[b] = min(self.block_min[b], arr[i])
def range_query(self, l, r):
result = 0
while l <= r:
if l % self.block_size == 0 and l + self.block_size - 1 <= r:
result += self.block_sum[l // self.block_size]
l += self.block_size
else:
result += self.arr[l]
l += 1
return result
23.14 DSU with Rollback
Conceptual Foundation
DSU with rollback supports undoing union operations, essential for offline queries and divide-and-conquer approaches.
Mechanism
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.changes = []
def find(self, x):
while self.parent[x] != x:
x = self.parent[x]
return x
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
self.changes.append((-1, -1, -1))
return
if self.size[x] < self.size[y]:
x, y = y, x
self.changes.append((y, self.parent[y], self.size[x]))
self.parent[y] = x
self.size[x] += self.size[y]
def snapshot(self):
return len(self.changes)
def rollback(self, state):
while len(self.changes) > state:
y, parent_y, size_x = self.changes.pop()
if y == -1:
continue
x = self.parent[y]
self.size[x] = size_x
self.parent[y] = parent_y
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
23.1 ★ Which cells does a Fenwick tree touch? For the FenwickTree of Section 23.3 with n = 8, list the indices of bit[] that are read or written by each call: (a) add(5, x), (b) add(3, x), (c) prefix_sum(7), (d) prefix_sum(6). Then say which range of the original array bit[6] covers.
Solution
idx & (-idx) isolates the lowest set bit. add climbs by adding it; prefix_sum descends by subtracting it.
| Call | Steps | Indices touched |
|---|---|---|
add(5, x) | 5 (101) → 6 (110) → 8 (1000) → 16 stops | 5, 6, 8 |
add(3, x) | 3 (011) → 4 (100) → 8 → 16 stops | 3, 4, 8 |
prefix_sum(7) | 7 (111) → 6 (110) → 4 (100) → 0 stops | 7, 6, 4 |
prefix_sum(6) | 6 (110) → 4 (100) → 0 stops | 6, 4 |
bit[i] covers the lowbit(i) positions ending at i. lowbit(6) = 2, so bit[6] holds a[5] + a[6] (1-indexed). That is why prefix_sum(7) is bit[7] + bit[6] + bit[4] = a[7] + a[5..6] + a[1..4]: three disjoint power-of-two blocks, one per set bit of 7.
23.2 ★ Build and query a sparse table. Build the SparseTable of Section 23.11 for arr = [5, 2, 4, 7, 1, 3] with op=min. Write out the meaningful entries of st[0], st[1] and st[2], then evaluate query(1, 5) and query(0, 3). Finally, show with these numbers why the same query trick gives a wrong answer if you build the table with addition instead.
Hint
st[k][i] is the minimum of the 2^k elements starting at i. A query covers [l, r] with two windows of length 2^j that may overlap.
Solution
st[0] = [5, 2, 4, 7, 1, 3] windows of length 1
st[1] = [2, 2, 4, 1, 1] min(a[i], a[i+1]), i = 0..4
st[2] = [2, 1, 1] min(st[1][i], st[1][i+2]), i = 0..2
(The code allocates n slots per row; the trailing slots stay 0 and are never read.)
query(1, 5): length 5,j = log[5] = 2. Windows[1..4]and[2..5]:min(st[2][1], st[2][2]) = min(1, 1) = 1.query(0, 3): length 4,j = 2. Both windows are[0..3]:min(st[2][0], st[2][0]) = 2.
With addition, query(1, 5) would return sum(a[1..4]) + sum(a[2..5]) = 14 + 15 = 29, but the true sum is 2 + 4 + 7 + 1 + 3 = 17. Positions 2, 3 and 4 are counted twice. The overlap is harmless for min, max and gcd because op(x, x) = x (idempotence); it is fatal for sum. A sum query on a sparse table must instead use disjoint power-of-two blocks, which costs O(log n), at which point a Fenwick tree is simpler.
23.3 ★★ Trace lazy propagation. Build the SegmentTree of Section 23.2 on [1, 2, 3, 4]. Node 1 is the root covering [0, 3], nodes 2 and 3 cover [0, 1] and [2, 3], and nodes 4 to 7 are the leaves. Give tree[1..7] and lazy[1..7] (a) after the build, (b) after range_update(1, 0, 3, 1, 3, 2) (add 2 to positions 1 to 3), and (c) after range_query(1, 0, 3, 2, 2). What does the query return? Which values in tree[] were stale between (b) and (c), and why is that safe?
Hint
An update stops descending at any node whose segment is fully inside [ql, qr]. Children are only brought up to date when a later operation needs to pass through that node.
Solution
| Node | Segment | (a) tree | (b) tree | (b) lazy | (c) tree | (c) lazy |
|---|---|---|---|---|---|---|
| 1 | [0,3] | 10 | 16 | 0 | 16 | 0 |
| 2 | [0,1] | 3 | 5 | 0 | 5 | 0 |
| 3 | [2,3] | 7 | 11 | 2 | 11 | 0 |
| 4 | [0,0] | 1 | 1 | 0 | 1 | 0 |
| 5 | [1,1] | 2 | 4 | 2 | 4 | 2 |
| 6 | [2,2] | 3 | 3 | 0 | 5 | 2 |
| 7 | [3,3] | 4 | 4 | 0 | 6 | 2 |
All lazy values are 0 after the build.
Update trace: node 1 is partly covered, so it pushes (nothing pending) and recurses. Node 2 is partly covered: node 4 is disjoint, node 5 is fully covered and gets tree += 2·1, lazy += 2. Node 2 recomputes to 1 + 4 = 5. Node 3 is fully covered: tree += 2·2 = 4 gives 11, lazy[3] = 2, and the recursion stops there. Node 1 recomputes to 5 + 11 = 16.
Query trace: node 1 is partial, pushes nothing. Node 3 is partial for [2, 2], so _push(3) adds 2·1 to each child and sets lazy[3] = 0. Node 6 is fully covered and returns 5, which is 3 + 2.
Between (b) and (c), tree[6] and tree[7] were stale (3 and 4 instead of 5 and 6). That is safe because every path to them goes through node 3, and any operation that passes through node 3 calls _push first. Node 3’s own value was correct the whole time. The leftover lazy values on leaves 5, 6 and 7 are never read, since _push is only called on nodes that recurse.
23.4 ★★ Trace a suffix automaton with a clone. Run SuffixAutomaton.extend on "a", "b", "b" in that order. Give the final next, link and len arrays, explain why the third call creates a clone, and use the formula from Section 23.7 to count distinct substrings of "abb".
Hint
The clone happens when walking suffix links finds a transition on c to a state q with len[q] > len[p] + 1: q represents strings that are too long to all be suffixes of the new prefix.
Solution
After "a": state 1 (len 1), next[0] = {a: 1}, link[1] = 0.
After "ab": state 2 (len 2). Walking from last = 1: next[1][b] = 2, then p = 0: next[0][b] = 2, then p = -1, so link[2] = 0.
Third character b: new state 3 with len 3. From p = 2: no b transition, so next[2][b] = 3, p = link[2] = 0. State 0 already has b → 2, so q = 2. Now len[0] + 1 = 1 but len[2] = 2. Before this step, state 2 represented {"b", "ab"}, both ending only at position 2 of "ab". In "abb", "b" now also ends at position 3, while "ab" does not. The two strings no longer share an end-position set, so the state must split. The clone (state 4) gets len 1, link[4] = link[2] = 0, and a copy of state 2’s transitions {b: 3}. The redirect loop changes next[0][b] from 2 to 4 and stops at p = -1. Finally link[2] = link[3] = 4.
| State | len | link | next |
|---|---|---|---|
| 0 | 0 | -1 | {a: 1, b: 4} |
| 1 | 1 | 0 | {b: 2} |
| 2 | 2 | 4 | {b: 3} |
| 3 | 3 | 4 | {} |
| 4 | 1 | 0 | {b: 3} |
Distinct substrings = Σ over states v ≠ 0 of len[v] - len[link[v]] = (1 − 0) + (2 − 1) + (3 − 1) + (1 − 0) = 5, matching {a, b, ab, bb, abb}. Five states for n = 3 is within the 2n − 1 bound.
23.5 ★★ Find the bug: rollback with path compression. A contestant wants faster finds and changes the DSU of Section 23.14 to:
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
Everything else is unchanged. Starting from DSU(4), run union(0, 1), union(2, 3), s = snapshot(), union(1, 3), find(3), rollback(s). What are parent and size at the end, and which connectivity answer is now wrong?
Solution
| Step | parent | size | change logged |
|---|---|---|---|
| start | [0, 1, 2, 3] | [1, 1, 1, 1] | |
| union(0, 1) | [0, 0, 2, 3] | [2, 1, 1, 1] | (1, 1, 1) |
| union(2, 3) | [0, 0, 2, 2] | [2, 1, 2, 1] | (3, 3, 1) |
| union(1, 3) | [0, 0, 0, 2] | [4, 1, 2, 1] | (2, 2, 2) |
| find(3) | [0, 0, 0, 0] | unchanged | none |
| rollback(s) | [0, 0, 2, 0] | [2, 1, 2, 1] |
Rollback restored parent[2] = 2, the one pointer it logged. It knows nothing about parent[3] = 0, which path compression wrote without recording it. Now find(3) = 0 and find(2) = 2: the structure says 3 is connected to 0 and not to 2, the exact opposite of the truth at snapshot s. size[2] = 2 also describes a set that now contains only 2.
The fix is the one the chapter uses: no path compression, so every pointer change is a logged union. Union by size alone keeps trees at depth O(log n), which is why rollback DSU costs O(log n) per operation instead of O(α(n)).
23.6 ★★ Why HLD paths cross few chains. In HeavyLightDecomposition, heavy[v] is the child with the largest subtree. (a) Prove that if (v, c) is a light edge then size[c] < size[v] / 2. (b) Conclude that any path from a node to the root crosses at most ⌊log₂ n⌋ light edges. (c) Use this to justify the O(log² n) bound for query_path. (d) Why must _decompose recurse into heavy[v] before the light children?
Hint
For (a), compare size[c] with size[heavy[v]] and remember both subtrees fit inside v’s. For (b), follow subtree sizes upward from the start node.
Solution
(a) Let h = heavy[v]. Since c is light, size[c] ≤ size[h]. Both subtrees are disjoint parts of v’s subtree, which also contains v, so size[c] + size[h] ≤ size[v] − 1. Then 2·size[c] ≤ size[c] + size[h] ≤ size[v] − 1 < size[v].
(b) Walk from a node u up to the root. Subtree sizes never decrease along the way, and each light edge crossed (from c up to v) more than doubles the size: size[v] > 2·size[c]. Starting from size[u] ≥ 1 and never exceeding n, at most ⌊log₂ n⌋ doublings fit.
(c) Each iteration of the while loop in query_path handles one chain and then jumps from head[u] to its parent, which crosses a light edge. A u-v path is two node-to-LCA paths, so there are O(log n) iterations, and each issues one segment tree query over a contiguous pos range costing O(log n). Total O(log² n).
(d) Recursing into the heavy child first gives it pos[v] + 1, then its heavy child pos[v] + 2, and so on. Every heavy chain therefore occupies a contiguous block of pos, which is what lets range_query(pos[head_u], pos[u]) answer a whole chain segment in one call. Visiting a light child first would interleave its subtree into the middle of the chain.
23.7 ★★★ Choosing Mo’s block size. MoSolver uses block size B = √n. (a) Show that with sorting by (l // B, r), the total pointer movement is O(qB + n²/B). (b) Find the B that minimises this, and the resulting bound. (c) For n = 10^5 and q = 10^3, estimate the pointer moves for B = √n and for your optimal B.
Hint
Bound the right pointer per block of left endpoints, and the left pointer per query.
Solution
(a) There are at most n/B distinct blocks for l. Within one block the queries are sorted by r, so the right pointer moves monotonically and travels at most n per block (plus up to n to reset when the block changes): O(n · n/B) = O(n²/B). The left pointer stays inside one block between consecutive queries of that block, so it moves at most B per query, and at most 2B when crossing into the next block: O(qB + n). Total O(qB + n²/B) add/remove calls. The alternating r order in the chapter’s sort key removes the reset sweep of the right pointer, which roughly halves the constant but does not change the bound.
(b) qB grows with B, n²/B shrinks; they balance when qB = n²/B, i.e. B = n/√q. Then each term is n√q, so the total is O(n√q). With q ≈ n this is B = √n and O(n√n), the chapter’s O((n + q)√n). When q is much smaller than n, B = √n is too small.
(c)
B = √n ≈ 316:qB + n²/B ≈ 3.2·10^5 + 3.2·10^7 ≈ 3.2·10^7.B = n/√q ≈ 3162:qB + n²/B ≈ 3.2·10^6 + 3.2·10^6 ≈ 6.3·10^6.
The tuned block size does about five times less work. Changing one line of __init__ to max(1, int(len(arr) / max(1, len(queries)) ** 0.5)) captures it.
23.8 ★★★ Implement distinct-count with Mo’s algorithm. Subclass MoSolver from Section 23.6 so that answers[i] is the number of distinct values in arr[l..r] (inclusive) for query i. Queries are objects with fields l, r, idx. Then explain why _process performs both expanding loops before both shrinking loops, and what would go wrong with your subclass if it shrank first.
Hint
Keep a count per value and a running number of values whose count is positive. Each _add and _remove must be O(1).
Solution
from collections import namedtuple
Query = namedtuple("Query", "l r idx")
class DistinctMo(MoSolver):
def __init__(self, arr, queries):
self.cnt = {}
self.distinct = 0
super().__init__(arr, queries) # runs _process, so set state first
def _add(self, idx):
x = self.arr[idx]
self.cnt[x] = self.cnt.get(x, 0) + 1
if self.cnt[x] == 1:
self.distinct += 1
def _remove(self, idx):
x = self.arr[idx]
self.cnt[x] -= 1
if self.cnt[x] == 0:
self.distinct -= 1
def _get_answer(self):
return self.distinct
arr = [1, 2, 1, 3, 2, 2, 4]
qs = [Query(0, 2, 0), Query(1, 4, 1), Query(3, 6, 2), Query(0, 6, 3)]
assert DistinctMo(arr, qs).answers == [2, 3, 3, 4]
The state must exist before super().__init__ because the base constructor immediately calls _process, which calls _add.
Expanding first keeps cur_l ≤ cur_r + 1 at every step, so the window never has negative length. If the code shrank first, moving from window [0, 1] to query [5, 6] would advance cur_l past cur_r and call _remove on positions 2, 3, 4 that were never added. cnt[x] would go to −1 (or raise KeyError for an unseen value), distinct would drift, and the later _add calls that bring those positions back would bump the counts from −1 to 0 without incrementing distinct. Every subsequent answer would be off. Expanding first means every _remove undoes a previous _add.
Each query costs O(1) per pointer step, so the whole run is O((n + q)√n) with the chapter’s block size.
Where this connects
- Chapter 21: Algorithm Design Using Data Structures. The paradigms these structures accelerate
- Chapter 25: Complete Selection Guide and Complexity Reference. The selection matrix for picking among them
Chapter 24: Research-Grade Data Structures
24.1 Introduction to Research-Grade Structures
Research-grade data structures push the boundaries of what is theoretically possible. They achieve remarkable space-time tradeoffs, often approaching information-theoretic lower bounds. These structures are essential for large-scale systems, specialized applications, and pushing the frontier of computer science.
24.2 Succinct Data Structures
Conceptual Foundation
Succinct data structures store information in space close to the theoretical minimum while supporting efficient operations. They achieve entropy-compressed space.
Space Bounds (Z = the information-theoretic minimum number of bits for the object):
- Implicit: Z + O(1) bits
- Succinct: Z + o(Z) bits
- Compact: O(Z) bits
- Compressed: close to the data’s empirical entropy (e.g. n·H₀ + o(n) bits), which can be well below Z
Rank and Select
class SuccinctBitVector:
def __init__(self, bits):
self.bits = bits
self.n = len(bits)
self._build_rank()
def _build_rank(self):
self.rank_block = [0] * ((self.n + 63) // 64)
for i in range(self.n):
if self.bits[i]:
self.rank_block[i // 64] += 1
for i in range(1, len(self.rank_block)):
self.rank_block[i] += self.rank_block[i - 1]
def rank(self, i):
"""Count of 1s in [0, i]"""
block = i // 64
before = self.rank_block[block - 1] if block > 0 else 0
return before + sum(self.bits[block * 64: i + 1])
def select(self, k):
"""Position of the k-th 1 (k counts from 0)"""
lo, hi = 0, self.n - 1
while lo < hi:
mid = (lo + hi) // 2
if self.rank(mid) <= k:
lo = mid + 1
else:
hi = mid
return lo
24.3 Succinct Trees (LOUDS, BP, DFUDS)
Balanced Parentheses (BP)
Tree → balanced parentheses string where “(” means enter node, “)” means exit.
def find_close(bp, i):
"""Find matching ')' for '(' at i"""
depth = 1
while depth > 0:
i += 1
depth += 1 if bp[i] == '(' else -1
return i
def find_open(bp, i):
"""Find matching '(' for ')' at i"""
depth = 1
while depth > 0:
i -= 1
depth += 1 if bp[i] == ')' else -1
return i
LOUDS (Level-Order Unary Degree Sequence)
Level-order traversal with unary degree encoding. Each node: (degree times ‘(’) + ‘)’.
| Operation | Complexity |
|---|---|
| Root | O(1) |
| Parent | O(1) with O(1) rank/select |
| Children | O(d) |
| Subtree size | Not supported efficiently (use BP or DFUDS) |
24.4 Wavelet Matrices
Conceptual Foundation
Wavelet matrices extend wavelet trees with better space utilization for large alphabets, using one bitmap per bit level with rank/select.
Improvements over Wavelet Tree:
- No separate child arrays
- Better bit-level packing
- Same query complexity
24.5 FM-Index
Conceptual Foundation
The FM-Index (Ferragina-Manzini) is a compressed self-indexing text index using the Burrows-Wheeler Transform.
Key Components:
- BWT string
- Occurrence counts (compressed)
- Suffix array samples
- LF-mapping
def bwt(s):
"""Burrows-Wheeler Transform"""
s = s + '$'
suffixes = sorted(range(len(s)), key=lambda i: s[i:])
return ''.join(s[i-1] for i in suffixes), suffixes
24.6 Cache-Oblivious Data Structures
Conceptual Foundation
Cache-oblivious structures achieve optimal performance without knowing cache size M or block size B. They work well across all memory hierarchy levels.
Key Idea: Optimal algorithms for all configurations simultaneously.
van Emde Boas Layout
Tree layout recursively:
VEB Layout of a complete binary tree with h levels:
- If h = 1: single node
- If h > 1: cut the tree at half its height into a top tree
of ceil(h/2) levels and about sqrt(N) bottom trees
of floor(h/2) levels; lay out the top tree recursively,
then each bottom tree recursively, left to right
Search Complexity: O(log_B N) I/Os, optimal.
24.7 Integer Data Structures and the Predecessor Problem
The Predecessor Problem on a Word RAM
Maintain a set S of n keys drawn from the universe U = {0, 1, …, u − 1}, under insert and delete, and answer:
- predecessor(x): the largest key in S that is smaller than x;
- successor(x): the smallest key in S that is larger than x.
(Some texts use ≤ and ≥; the difference is one membership test.) This is what an ordered map does for floor, ceiling and iteration, what a priority queue does when it finds the next nonempty priority level, and what an IP router does when it finds which address range a destination falls into.
A balanced BST or B-tree answers these in O(log n), and in the comparison model that is optimal: an algorithm that learns about keys only by comparing them is a binary decision tree, a query has n + 1 possible answers, so some query needs ⌈log₂(n + 1)⌉ comparisons. Integer keys are not opaque, though. On a word RAM with w-bit words (u = 2^w, and w ≥ log₂ n so that a word can hold a pointer), arithmetic, shifts, bitwise operations and reading memory at a computed address each cost O(1), and the decision-tree argument says nothing about algorithms that use them. Radix sort and hashing already escape comparison bounds this way. Hashing alone does not solve predecessor, because a hash table answers “is x in S?” in O(1) but knows nothing about order. The structures in this section answer predecessor queries in O(log log u) = O(log w) time: the recursion depth for 64-bit keys is 6, whatever n is.
van Emde Boas Trees
Peter van Emde Boas (1975) introduced this structure as a priority queue. Split a k-bit key x (u = 2^k) into a high half and a low half:
high(x) = x >> ⌊k/2⌋, low(x) = x mod 2^⌊k/2⌋, x = high(x) · 2^⌊k/2⌋ + low(x).
This cuts the universe into about √u clusters of about √u keys each: high(x) names x’s cluster and low(x) is its position inside. A vEB tree V over a universe of size u holds:
clusters[h]: a vEB tree over the √u-sized universe of low halves, holding low(x) for every key x in cluster h;summary: a vEB tree over the √u cluster numbers, holding h for every nonempty cluster;minandmax. The minimum is stored only here, never in a cluster. The maximum is a cached copy: it is also stored in its cluster.
When k is odd there are 2^⌈k/2⌉ clusters of 2^⌊k/2⌋ keys, so the summary gets the larger half of the bits.
Keeping the minimum out of the clusters is what makes the time bound work. Inserting into an empty vEB tree is O(1): set min = max = x and stop, with no recursion. So when insert finds x’s cluster empty, it makes one recursive call into the summary (to record that the cluster is now nonempty) and an O(1) insert into the empty cluster. When the cluster is already nonempty, the summary does not change and the one recursive call goes into the cluster. Successor has the same shape: if x’s cluster holds something larger than low(x), which the cluster’s cached max tells us in O(1), recurse into the cluster; otherwise recurse into the summary to find the next nonempty cluster and read its min in O(1). Either way the work is one recursive call on a universe of size √u, plus O(1):
T(u) = T(√u) + O(1).
Substitute m = log₂ u, the number of key bits. Each call halves m, so S(m) = S(m/2) + O(1), which is O(log m). Hence T(u) = O(log log u), worst case, for insert, delete, member, successor and predecessor, and O(1) for min and max. For 64-bit keys the bit count goes 64, 32, 16, 8, 4, 2, 1: seven levels. Without the cached min and max, successor would sometimes need two recursive calls, and T(u) = 2T(√u) + O(1) solves to O(log u), no better than a balanced tree (Exercise 24.8).
class VEB:
"""van Emde Boas tree over the universe {0, ..., 2**k - 1}."""
def __init__(self, k):
self.k = k
self.min = None # kept here only, never inside a cluster
self.max = None # cached copy; the max also lives in a cluster
if k > 1:
self.lo_bits = k // 2 # bits of low(x); clusters have universe 2**lo_bits
self.clusters = {} # high(x) -> VEB(lo_bits), nonempty clusters only
self.summary = None # VEB of nonempty cluster numbers, built on demand
def high(self, x):
return x >> self.lo_bits
def low(self, x):
return x & ((1 << self.lo_bits) - 1)
def index(self, h, l):
return (h << self.lo_bits) | l
def member(self, x):
if x == self.min or x == self.max:
return True
if self.k == 1 or self.min is None:
return False
c = self.clusters.get(self.high(x))
return c is not None and c.member(self.low(x))
def insert(self, x):
if self.min is None: # empty: O(1), no recursion
self.min = self.max = x
return
if x == self.min or x == self.max: # already present
return
if x < self.min:
x, self.min = self.min, x # x becomes the min; push the old min down
if self.k > 1:
h, l = self.high(x), self.low(x)
c = self.clusters.get(h)
if c is None: # new cluster: record it in the summary
c = self.clusters[h] = VEB(self.lo_bits)
if self.summary is None:
self.summary = VEB(self.k - self.lo_bits)
self.summary.insert(h) # the one real recursive call
c.insert(l) # O(1) if c was empty, else the real call
if x > self.max:
self.max = x
def successor(self, x):
"""Smallest element greater than x, or None."""
if self.min is not None and x < self.min:
return self.min
if self.k == 1:
return 1 if x == 0 and self.max == 1 else None
h, l = self.high(x), self.low(x)
c = self.clusters.get(h)
if c is not None and l < c.max: # answer is in x's own cluster
return self.index(h, c.successor(l))
if self.summary is None: # only the min is stored, and x >= min
return None
nxt = self.summary.successor(h) # else: the next nonempty cluster
if nxt is None:
return None
return self.index(nxt, self.clusters[nxt].min)
def delete(self, x):
"""Remove x, which must be present."""
if self.min == self.max: # x is the only element
self.min = self.max = None
return
if self.k == 1:
self.min = self.max = 1 - x
return
if x == self.min: # promote the smallest clustered element
h = self.summary.min
x = self.min = self.index(h, self.clusters[h].min)
h, l = self.high(x), self.low(x)
c = self.clusters[h]
c.delete(l)
if c.min is None: # cluster emptied (that delete was O(1))
del self.clusters[h]
self.summary.delete(h)
if self.summary.min is None:
self.summary = None
if x == self.max:
if self.summary is None:
self.max = self.min
else:
h = self.summary.max
self.max = self.index(h, self.clusters[h].max)
Delete follows the same pattern. Deleting the min promotes the smallest clustered key (the min of the summary’s min cluster, found in O(1)) to be the new min, and deletes that key from its cluster instead. If the cluster delete empties the cluster, it was O(1), because the cluster held one key; the one real recursive call then removes the cluster number from the summary. The base case k = 1 is a universe {0, 1} described entirely by min and max. Predecessor is not quite the mirror image of successor, because the minimum lives outside the clusters; Exercise 24.9 works it out.
The class was checked against a sorted Python list on random sequences of insert, delete, member and successor, for universes of 2 to 2^20 keys, comparing min and max after every operation.
Space, and the hashing fix. van Emde Boas’s structure stores the clusters in an array with a slot for every possible cluster, empty or not. Its space satisfies S(u) = (√u + 1) · S(√u) + Θ(√u), which is Θ(u). For 32-bit keys that is billions of words to hold even a handful of keys; for 64-bit keys it cannot be built. The fix is the one the code above already uses: keep only the nonempty clusters, in a hash table keyed by cluster number (the dict), and create a summary only when the first cluster appears. An insert creates at most one new structure per level of recursion (the cluster it found empty), so the space is O(n log log u) words. On random keys the class above uses about 2.6, 3.6 and 4.6 structures per key for 16-, 32- and 64-bit universes (n = 1000): one more per doubling of the word size, as the bound predicts. The price is that the time bounds now rest on hashing: O(log log u) expected for queries, and expected amortized for updates (tables resize). Getting down to O(n) space takes one more idea, bucketing, which is exactly the step from x-fast to y-fast tries below.
Worked example (u = 16). Insert S = {2, 3, 9, 13, 14, 15} into VEB(4). Every key splits into 2 high bits and 2 low bits, so there are four clusters of four keys.
| Structure | Holds | min | max |
|---|---|---|---|
| V (u = 16) | 2 at the top, the other keys in clusters | 2 | 15 |
| summary (u = 4) | cluster numbers 0, 2, 3 | 0 | 3 |
| cluster 0 (u = 4) | low 3 (key 3) | 3 | 3 |
| cluster 1 | not stored | ||
| cluster 2 (u = 4) | low 1 (key 9) | 1 | 1 |
| cluster 3 (u = 4) | lows 1, 2, 3 (keys 13, 14, 15) | 1 | 3 |
Key 2 is not in cluster 0: it is V’s min. The summary and cluster 3 are vEB trees over u = 4 with the same rule. The summary keeps 0 as its min and stores 2 and 3 one level down (both in its cluster 1, since 2 = 10₂ and 3 = 11₂); cluster 3 keeps 1 as its min and stores 2 and 3 one level down.
successor(9): 9 = 10 01₂, so h = 2 and l = 1. Cluster 2’s max is 1, not larger than l, so nothing in cluster 2 follows 9. The summary is asked forsuccessor(2)among the nonempty clusters {0, 2, 3} and answers 3. Cluster 3’s min is 1, so the answer is 3 · 4 + 1 = 13.successor(4): h = 1, and cluster 1 does not exist. The summary’s successor of 1 is 2, and cluster 2’s min is 1, so the answer is 2 · 4 + 1 = 9. The empty cluster was skipped without being looked at.
Inside the summary, each query recursed once more on a universe of size 2 (into the summary’s cluster 1 for successor(2), into the summary’s own summary for successor(1)) and stopped: one call per halving of the key length.
The cache-oblivious layout of Section 24.6 carries van Emde Boas’s name because it applies the same recursion to a tree’s height instead of a key’s bits.
x-Fast Tries
Willard (1983) reached the same O(log log u) query time by a different route, and then fixed the space.
Think of the keys as root-to-leaf paths in a complete binary trie of depth w: the path of x spells out its bits, most significant first, and the node at depth ℓ on that path is x’s ℓ-bit prefix, x >> (w − ℓ). An ordinary binary trie finds where x’s path leaves the set of stored paths by walking down, O(w) steps. The x-fast trie instead keeps, for each depth ℓ = 0, …, w, a hash table of the ℓ-bit prefixes of the keys in S. Presence is monotone: if x’s ℓ-bit prefix is present, so is every shorter prefix. So the length of x’s longest present prefix can be found by binary search over ℓ, one hash lookup per step: O(log w) = O(log log u).
The node p where x’s path stops has one child (if it had both, the path would continue), and x would go into the missing one. If the missing child is on the right, every key below p is smaller than x and the largest of them is x’s predecessor; if it is on the left, every key below p is larger and the smallest is x’s successor. Willard stores a descendant pointer at each node with a missing child, pointing at exactly that leaf, and links the leaves into a sorted doubly linked list, so the other neighbour is one step away. The sketch below keeps the (min, max) of the keys below each node instead, which carries the same information:
def build_xfast(keys, w):
"""levels[l] maps each l-bit prefix of a key to (min, max) of the keys below it."""
levels = [{} for _ in range(w + 1)]
for x in keys:
for l in range(w + 1):
p = x >> (w - l)
lo, hi = levels[l].get(p, (x, x))
levels[l][p] = (min(lo, x), max(hi, x))
srt = sorted(keys)
nxt = dict(zip(srt, srt[1:] + [None])) # the leaves as a sorted linked list
return levels, nxt
def xfast_successor(levels, nxt, w, x):
"""Smallest key greater than x, or None."""
if not levels[0]:
return None
lo, hi = 0, w # invariant: the prefix of length lo is present
while lo < hi: # binary search for the longest present prefix
mid = (lo + hi + 1) // 2
if (x >> (w - mid)) in levels[mid]:
lo = mid
else:
hi = mid - 1
if lo == w: # x itself is a key
return nxt[x]
mn, mx = levels[lo][x >> (w - lo)]
if (x >> (w - lo - 1)) & 1: # x leaves this node to the right of all its keys
return nxt[mx]
return mn # x leaves to the left of all its keys
Example: w = 4 and S = {2, 9, 13} = {0010, 1001, 1101}.
| ℓ | prefixes present (min, max of the keys below) |
|---|---|
| 0 | ε (2, 13) |
| 1 | 0 (2, 2), 1 (9, 13) |
| 2 | 00 (2, 2), 10 (9, 9), 11 (13, 13) |
| 3 | 001, 100, 110 (one key each) |
| 4 | 0010, 1001, 1101 (the keys) |
successor(11), with 11 = 1011: start with lo = 0, hi = 4. Probe ℓ = 2: 10 is present, so lo = 2. Probe ℓ = 3: 101 is absent, so hi = 2. Two lookups locate node 10. The next bit of 11 is 1, so 11 branches off to the right of everything under 10, whose max is 9: 9 is the predecessor, and the next leaf in the list, 13, is the successor. The code was checked against a sorted list on random sets for w from 1 to 32.
Queries cost O(log w) hash lookups, expected. The cost is elsewhere: each key puts a prefix into each of the w + 1 tables, so the space is O(nw) = O(n log u) words, and an insert or delete must update w + 1 tables (and the min, max or descendant pointers along the path), which is O(w) = O(log u) expected.
y-Fast Tries
The y-fast trie, in the same paper, removes the factor of w by bucketing (also called indirection). Split the sorted keys into buckets of between w/2 and 2w consecutive keys, store each bucket in a balanced BST, and give each bucket a representative: a value no larger than the bucket’s smallest key and larger than every key in the previous bucket. Only the representatives go into an x-fast trie. That is Θ(n/w) representatives at O(w) words each, plus O(n) for the BSTs: O(n) space.
- successor(x): find the largest representative ≤ x in the x-fast trie, O(log w). Search that bucket’s BST for the successor of x, O(log w), since the bucket has O(w) keys. If nothing in the bucket is larger, the answer is the smallest key of the next bucket. (If no representative is ≤ x, it is the smallest key of the first bucket.)
- insert / delete: find the bucket the same way and update its BST, O(log w). When a bucket grows past 2w keys, split it and insert a new representative; when it falls below w/2, merge it with a neighbour, splitting the result again if it holds more than 3w/2 keys, and delete a representative. Each restructuring costs O(w), but it leaves every bucket involved with between about 3w/4 and 3w/2 keys, at least w/4 updates away from either limit, so it happens at most once per Ω(w) updates. Updates cost O(log w) = O(log log u) amortized expected.
A representative is a boundary, not a key. Deleting the key equal to its bucket’s representative leaves the representative where it is, so ordinary updates never touch the x-fast trie.
Example, w = 4 (buckets of 2 to 8 keys): S = {1, 2, 3, 5, 8, 9, 12, 13, 14} in buckets {1, 2, 3, 5}, {8, 9, 12}, {13, 14} with representatives 0, 8 and 13. successor(10): the largest representative ≤ 10 is 8, and the bucket {8, 9, 12} gives 12. successor(12): same bucket, nothing larger than 12, so the answer is the first key of the next bucket, 13. Deleting 8 leaves the bucket {9, 12} with 2 = w/2 keys and representative 8, and the x-fast trie does not change.
All queries in x-fast and y-fast tries are expected bounds because of the hash tables. With dynamic perfect hashing, lookups take O(1) worst case, which makes the queries worst-case O(log log u), while updates stay expected amortized.
Fusion Trees and Lower Bounds
Fusion trees (Fredman and Willard, 1990) attack the other parameter. A fusion tree is a B-tree with fan-out B = w^(1/5). Seen as paths in the binary trie, the B keys of one node branch at fewer than B bit positions; keeping only those bits gives each key a short sketch, and all B sketches fit in one word. A constant number of multiplications, masks and subtractions compare a query’s sketch against every sketch in the node at once, and one more constant-time step corrects for the bits the sketch throws away. Each node is searched in O(1), the height is log_B n = O(log n / log w), so a query takes O(log_w n) time, in O(n) space.
Fusion trees win when w is large relative to log n; vEB and y-fast tries win when w is small. Taking whichever is better gives O(min(log_w n, log w)), which is always O(√(log n)): if log w ≥ √(log n) then log_w n = log n / log w ≤ √(log n), and otherwise log w < √(log n). Fredman and Willard used fusion trees to sort n integers in o(n log n) time, beating the comparison bound.
Lower bounds. Is O(log log u) the end of the story? For static sets, Pătraşcu and Thorup (2006) gave the answer: for every combination of n, word size w and space, the optimal query time up to constant factors, as the minimum of four expressions (the first is the fusion-tree bound log_w n), with matching lower bounds in the cell-probe model (which bound every word-RAM algorithm too). The case most often quoted: for a polynomial universe (w = γ log₂ n for a constant γ > 1, so u = n^γ) and near-linear space (n · (log n)^O(1) words), the optimal query time is Θ(log w) = Θ(log log u), so van Emde Boas’s bound cannot be improved there. In the same setting with n^(1+ε) words of space, Beame and Fich’s structure answers in O(log w / log log w), and Pătraşcu and Thorup showed that this gap between near-linear and polynomial space is real. As a function of n alone, the best possible query time with polynomial space is Θ(√(log n / log log n)): Beame and Fich proved the lower bound, and Andersson and Thorup’s exponential search trees match it dynamically, in linear space.
In Practice
| Structure | Predecessor / successor | Insert / delete | Space (words) |
|---|---|---|---|
| Sorted array | O(log n) worst | O(n) worst | n |
| Balanced BST, B-tree | O(log n) worst | O(log n) worst | O(n) |
| vEB tree, arrays | O(log log u) worst | O(log log u) worst | Θ(u) |
| vEB tree, hash tables | O(log log u) expected | O(log log u) expected amortized | O(n log log u) |
| x-fast trie | O(log log u) expected | O(log u) expected amortized | O(n log u) |
| y-fast trie | O(log log u) expected | O(log log u) expected amortized | O(n) |
| Fusion tree | O(log_w n) worst | static as described | O(n) |
Here w = log₂ u is the word size. Min and max are O(1) in a vEB tree.
On paper, O(log log u) = 6 for 64-bit keys against log₂ n ≈ 30 for a billion keys. In memory, the count of operations is the wrong measure. Each level of a hashed vEB tree or x-fast trie is a hash probe at an unpredictable address, which on a large set is a cache miss, and a y-fast query adds a walk down a BST of about 64 keys. A B-tree with 16 to 64 keys per node over 10⁹ keys is 5 to 8 levels deep, each level a few adjacent cache lines that are scanned quickly (Chapter 10); it also gives range scans by walking adjacent memory, works for any ordered key type, and is far simpler. The hashed structures also use more memory: about 39 hash entries per key for an x-fast trie on 10⁶ random 64-bit keys (Exercise 24.10). For a general-purpose ordered map, a well-tuned B-tree, or a sorted array for static data, usually matches or beats them.
They pay off in specific places:
- Small or dense universes. When u is small enough to spend u bits, the vEB idea becomes a hierarchy of bitmaps with fan-out w: each node is one word with a bit per child, and “next set bit” is a shift and a count-trailing-zeros instruction. With 64-bit words, 4 levels cover u = 2^24 in u(1 + 1/63) bits, with no hashing and no pointers. The Linux O(1) scheduler (kernel 2.6.0 until the Completely Fair Scheduler replaced it in 2.6.23) found the highest-priority nonempty run queue with a single-level version: a 140-bit bitmap of priority levels and a find-first-set instruction. Memory allocators and timer implementations use the same multi-level bitmap trick.
- IP routing. Longest-prefix match by binary search over prefix lengths, with one hash table per length (Waldvogel, Varghese, Turner and Plattner, 1997), is the x-fast trie’s idea applied to routing tables.
- Theory. These structures are the basis of integer sorting and integer priority queues that beat comparison bounds, for example in Dijkstra’s algorithm with integer edge weights.
24.8 External Memory Data Structures
External Memory Model
Parameters: N (problem size), B (block size), M (memory size), and in the parallel disk model D (number of disks).
| Structure | I/O Complexity |
|---|---|
| B-Tree | O(log_B N) |
| Buffer Tree | O(1/B log_M/B N) amortized |
| LSM Tree | O(1/B log_M/B N) amortized write |
Log-Structured Merge Trees
LSM trees (LevelDB, RocksDB, Cassandra) achieve write-optimized storage:
Levels: L0, L1, L2, ..., L_k
- Each level T times larger than previous
- Data flows: MemTable → L0 → L1 → ... → Lk
- Compaction merges sorted runs
24.9 Fully Persistent Data Structures
Persistence Types
| Type | Read Old | Write Current | Write Old | Merge |
|---|---|---|---|---|
| Partial | Yes | Yes | No | No |
| Full | Yes | Yes | Yes | No |
| Confluent | Yes | Yes | Yes | Yes |
Fat Nodes
Store modification logs at each node:
class FatNode:
def __init__(self, value):
self.value = value
self.mod_log = [] # (time, field, old, new)
self.left = None
self.right = None
def write(self, field, new_value, time):
self.mod_log.append((time, field, getattr(self, field), new_value))
setattr(self, field, new_value)
24.10 Conflict-Free Replicated Data Types (CRDTs)
Conceptual Foundation
CRDTs achieve eventual consistency in distributed systems without coordination. Operations commute, guaranteeing convergence.
G-Counter (Grow-only)
class GCounter:
def __init__(self, node_id):
self.node_id = node_id
self.counts = {node_id: 0}
def increment(self):
self.counts[self.node_id] += 1
def merge(self, other):
for node, count in other.counts.items():
self.counts[node] = max(self.counts.get(node, 0), count)
def value(self):
return sum(self.counts.values())
Common CRDT Types
| CRDT | Operations | Semantics |
|---|---|---|
| G-Set | Add | Grow-only |
| 2P-Set | Add, Remove | Remove-wins (no re-add) |
| LWW-Register | Assign | Last-write-wins |
| OR-Set | Add with tag, Remove | Tag-based |
24.11 Dynamic Graph Algorithms
Holm-de Lichtenberg-Thorup (HDnT)
Fully dynamic connectivity with O(log² n) amortized updates and O(log n / log log n) queries:
class HDnTConnectivity:
def __init__(self, n):
self.n = n
self.LOG = int(math.log2(n)) + 1
self.levels = [[] for _ in range(self.LOG)]
self.spanning_forests = [None] * self.LOG
Dynamic Shortest Paths
| Type | Best Known |
|---|---|
| Decremental APSP | O(mn) total |
| Fully dynamic | O(n²) per update |
| (1+ε)-approx | Near-linear |
24.12 String B-Trees
B-trees optimized for string keys:
| Operation | I/O Complexity |
|---|---|
| Search | O(log_B n) |
| Prefix search | O(log_B n + output) |
| Range search | O(log_B n + output/B) |
24.13 Fractional Cascading
Accelerate searches in layered structures:
def fractional_cascading_search(layers, query):
"""Search in multiple layers with caching"""
pos = binary_search(layers[0], query)
for i in range(1, len(layers)):
# Use cached bounds from previous level
cached_lower = layers[i-1].get_cached_lower(pos)
pos = bounded_search(layers[i], query, cached_lower)
return pos
Speedup: O(log n + k) vs O(Σ log n_i)
24.14 Melding Data Structures
Combine data structures efficiently:
| Structure | Meld Complexity |
|---|---|
| Fibonacci heap | O(1) |
| Binomial heap | O(log n) |
| Leftist heap | O(log n) |
| Skew heap | O(log n) amortized |
24.15 Research Frontiers
Emerging Areas
| Area | Challenge | State |
|---|---|---|
| Succinct graphs | Space-time tradeoffs | O(n) space |
| Dynamic graph minors | Subgraph isomorphism | Active research |
| Learned indexes | Replace B-trees with neural nets | Emerging |
| Quantum DS | Quantum advantage | Theoretical |
| DNA storage | Extreme longevity | Nanostores |
Open Problems
- Dynamic connectivity in true O(log n)?
- Sub-logarithmic string operations?
- Persistent arrays with O(1) space per version?
- Cache-oblivious sorting optimal?
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
24.1 ★ Rank and select by hand. For the bit vector 1 0 1 1 0 0 1 0 1 1 (positions 0 to 9), compute rank(i) for every i using the definition in SuccinctBitVector (count of 1s in [0, i]), then select(0) and select(3). How many calls to rank does the chapter’s select make on a vector of n bits, and why is this class an illustration of rank/select rather than a succinct structure?
Solution
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| bit | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 |
| rank(i) | 1 | 1 | 2 | 3 | 3 | 3 | 4 | 4 | 5 | 6 |
select(k) (k counts from 0) is the smallest position whose rank exceeds k. select(0) = 0 (first position with rank 1) and select(3) = 6 (first position with rank 4). Rank and select are inverses in this sense: rank(select(k)) = k + 1.
The binary search in select halves [0, n - 1] each step, so it makes about ⌈log₂ n⌉ calls to rank, giving O(log n) select, not O(1).
It is not succinct, for two reasons. The bits are a Python list (one object per bit, not one bit per bit), and rank_block stores a full ⌈log₂ n⌉-bit count per 64 bits, which is Θ(n log n / 64) bits: a small constant for realistic n, but not o(n). And rank scans up to 64 list entries with sum, so it is O(64) work, not a word operation. A real succinct bit vector packs bits into machine words, uses a two-level directory (superblocks of about log² n bits, blocks of about ½ log n bits) so the directory totals o(n) bits, and finishes rank with a popcount instruction or lookup table, for O(1) time. Select needs its own o(n)-bit sampling directory to reach O(1).
24.2 ★ 2P-Set versus OR-Set. Two replicas start empty. Replica A runs add(x) then remove(x). Concurrently, replica B runs add(x). The replicas then merge. Afterwards, A runs add(x) again. Using the table in Section 24.10, say whether x is in the set after the merge and after the re-add, (a) for a 2P-Set and (b) for an OR-Set.
Solution
(a) 2P-Set. It is two G-Sets: added and removed (a tombstone set), and x is present iff it is in added and not in removed. Merge is union of both. After the merge, added = {x}, removed = {x}, so x is absent: B’s concurrent add is overridden. A’s re-add puts x into added, where it already is, and x is still in removed forever, so x stays absent. This is “remove-wins, no re-add”.
(b) OR-Set. Each add creates a unique tag: A’s add makes (x, a1), B’s makes (x, b1). A remove deletes only the tags its replica has observed, so A’s remove tombstones a1 only. After the merge the live tags are {b1}, so x is present: the concurrent add wins. A’s re-add creates (x, a2), and x is present.
The difference is that the OR-Set remove says “remove the adds I have seen”, which leaves concurrent adds alone, while the 2P-Set remove says “remove x”, permanently.
24.3 ★★ Balanced parentheses and LOUDS for the same tree. Take the tree with root R, children A and B (in that order), where A has children C and D and B has child E. (a) Write its BP string (preorder, ( on entry, ) on exit). (b) Using find_close, compute the subtree sizes of R, A and B from their opening positions. (c) Write its LOUDS string following Section 24.3 (level order, each node writes ( once per child, then )). (d) Explain why BP answers subtree size cheaply and LOUDS does not.
Hint
In BP, everything between a node’s ( and its matching ) belongs to its subtree, and each node contributes exactly two characters.
Solution
(a) R( A( C() D() ) B( E() ) ) gives
index: 0 1 2 3 4 5 6 7 8 9 10 11
bp: ( ( ( ) ( ) ) ( ( ) ) )
node: R A C D B E
so bp = "((()())(()))", 2n = 12 characters for n = 6 nodes.
(b) Subtree size of the node opening at i is (find_close(bp, i) - i + 1) / 2:
- R at 0:
find_close = 11, size12 / 2 = 6. - A at 1:
find_close = 6, size6 / 2 = 3(A, C, D). - B at 7:
find_close = 10, size4 / 2 = 2(B, E).
(c) Level order is R, A, B, C, D, E with degrees 2, 2, 1, 0, 0, 0:
R: (() A: (() B: () C: ) D: ) E: )
LOUDS = "(()(()())))" (11 characters = (n − 1) opens + n closes)
Real implementations usually prepend one ( for a virtual super-root so that every node, including the root, is “the child of someone”, which makes the rank/select formulas uniform. That brings the length to 2n.
(d) In BP the subtree of a node is a contiguous substring, so its size is one find_close (O(1) with the standard o(n)-bit range-min directory). In LOUDS, a node’s descendants are spread across every level below it, one contiguous run per level, so counting them means walking level by level. LOUDS is the better choice for fast parent and i-th child with the simplest directories; BP or DFUDS when you need subtree size, depth or level-ancestor.
24.4 ★★ Why the G-Counter converges, and why you cannot just decrement it. (a) Show that the merge of Section 24.10 is commutative, associative and idempotent, and explain why that guarantees all replicas converge no matter how often or in what order they exchange state. (b) A developer adds def decrement(self): self.counts[self.node_id] -= 1. Replica A increments three times, sends its state to B (B merges), then decrements once, then merges B’s state back. What does A report, and what should it report? (c) How do you get a counter that supports decrement?
Hint
Merge is an entry-wise max. Think about what max does to a value that went down.
Solution
(a) Merge sets each entry to max(mine, theirs). Entry-wise max is commutative (max(a, b) = max(b, a)), associative (max(max(a, b), c) = max(a, max(b, c))) and idempotent (max(a, a) = a). So the merged state after any set of exchanges is the entry-wise max over every state any replica has produced, regardless of order, grouping or duplicate deliveries. Once every replica has (directly or transitively) heard from every other, they all hold the same map, so value() agrees. This works because each entry only ever grows and only its owner writes it.
(b) After three increments A has {A: 3}; B merges and holds {B: 0, A: 3}. A decrements to {A: 2}. Merging B back computes max(2, 3) = 3 for entry A. A reports 3; the correct total is 2. The decrement is silently lost, and whether it is lost depends on message timing, which is the bug CRDTs exist to prevent.
(c) Use a PN-Counter: two G-Counters, P for increments and N for decrements. decrement increments this replica’s entry in N; merge merges P and N separately; the value is sum(P) - sum(N). Every entry still only grows, so the convergence argument from (a) still holds.
24.5 ★★ Lay out a tree in van Emde Boas order. Number a complete binary tree with 4 levels in BFS order: root 1, children of i are 2i and 2i + 1, leaves 8 to 15. (a) Using the recursive rule in Section 24.6, write the 15 nodes in vEB order. (b) With blocks of B = 3 nodes, how many blocks does the root-to-leaf path 1, 2, 4, 8 touch in vEB order, and in plain BFS order? (c) Sketch why vEB order gives O(log_B N) blocks per search for every B at once.
Hint
With 4 levels, the top tree has 2 levels and there are four bottom trees of 2 levels each.
Solution
(a) Top tree: nodes 1, 2, 3 (itself laid out as 1, then 2, 3). Bottom trees, left to right: rooted at 4, 5, 6, 7, each with its two children.
vEB order: 1 2 3 | 4 8 9 | 5 10 11 | 6 12 13 | 7 14 15
(b) vEB, B = 3: positions split exactly as the bars above. Path 1, 2, 4, 8 sits in blocks [1 2 3] and [4 8 9]: 2 blocks. BFS order stores node i at position i − 1, so the path is at positions 0, 1, 3, 7, which fall in blocks 0, 0, 1, 2: 3 blocks. Every root-to-leaf path in this tree gives the same counts (2 versus 3). The gap grows with height: BFS order touches roughly one block per level once you are below the first log₂ B levels.
(c) Follow the recursion down until the pieces have between √B and B nodes. Each such piece is stored contiguously, so it straddles at most 2 blocks. A piece of at least √B nodes has height at least ½ log₂ B, so a root-to-leaf path of height log₂ N passes through at most log₂ N / (½ log₂ B) = 2 log_B N pieces, touching at most 4 log_B N blocks. The argument never used the value of B in the layout itself, which is what “cache-oblivious” means: the same array is near-optimal for every level of the memory hierarchy.
24.6 ★★ Read a fat node at a past time. The FatNode of Section 24.9 logs every write as (time, field, old, new), in increasing time order. Write read(node, field, t) that returns the value node.<field> had after all writes with time ≤ t. What is its cost, and which row of the persistence table does this node support?
Hint
You do not need to replay the log forward. Look for the first write to this field after time t.
Solution
The value at time t is the old value recorded by the first write to that field after t. If there is no such write, nothing has changed since t and the current attribute is the answer.
def read(node, field, t):
"""Value of node.<field> as of time t (after every write with time <= t)."""
for time, f, old, new in node.mod_log:
if f == field and time > t:
return old # value just before the first later write
return getattr(node, field) # no write after t: current value is the answer
n = FatNode(10)
n.write('value', 20, 1)
n.write('left', 'L', 2)
n.write('value', 30, 3)
n.write('value', 40, 5)
assert read(n, 'value', 0) == 10
assert read(n, 'value', 2) == 20
assert read(n, 'value', 4) == 30
assert read(n, 'value', 9) == 40
assert read(n, 'left', 1) is None and read(n, 'left', 2) == 'L'
This scan is O(m) for m logged writes. Keeping one log per field, each sorted by time, makes it a binary search: O(log m) per field access, so a root-to-leaf walk in a persistent tree of depth d costs O(d log m). That log factor is what the node-copying method (Driscoll, Sarnak, Sleator and Tarjan) removes.
write always appends at the current time and never branches from an old version, so this is partial persistence: read any version, write only the newest.
24.7 ★★★ Count pattern occurrences with an FM-index. (a) Compute bwt("banana") with the function in Section 24.5. (b) Build C[c] (number of characters in the text smaller than c) and use backward search to count occurrences of "ana" and of "nab", keeping the suffix-array interval [lo, hi) at each step. (c) Implement fm_count(L, pattern) that does the same from the BWT string alone, without the original text.
Hint
Process the pattern from its last character. If the current interval of suffixes starting with P[i+1:] is [lo, hi), then the suffixes starting with c + P[i+1:] form [C[c] + occ(c, lo), C[c] + occ(c, hi)), where occ(c, i) counts c in L[:i].
Solution
(a) The sorted suffixes of "banana$" and the character before each:
| row | suffix | SA | L (preceding char) |
|---|---|---|---|
| 0 | $ | 6 | a |
| 1 | a$ | 5 | n |
| 2 | ana$ | 3 | n |
| 3 | anana$ | 1 | b |
| 4 | banana$ | 0 | $ |
| 5 | na$ | 4 | a |
| 6 | nana$ | 2 | a |
bwt("banana") returns ("annb$aa", [6, 5, 3, 1, 0, 4, 2]).
(b) The first column is $aaabnn, so C[$] = 0, C[a] = 1, C[b] = 4, C[n] = 5.
Pattern "ana", right to left, starting from [0, 7):
| char | lo | hi | rows |
|---|---|---|---|
| a | 1 + occ(a, 0) = 1 | 1 + occ(a, 7) = 4 | a$, ana$, anana$ |
| n | 5 + occ(n, 1) = 5 | 5 + occ(n, 4) = 7 | na$, nana$ |
| a | 1 + occ(a, 5) = 2 | 1 + occ(a, 7) = 4 | ana$, anana$ |
Count = 4 − 2 = 2. The SA entries in rows 2 and 3 (3 and 1) are the positions; a real FM-index stores only a sample of SA and recovers the rest with LF steps.
Pattern "nab": b gives [4, 5); then a gives [1 + occ(a, 4), 1 + occ(a, 5)) = [2, 2), empty, so the count is 0.
(c)
def fm_count(L, pattern):
C, total = {}, 0
for ch in sorted(set(L)):
C[ch] = total
total += L.count(ch)
def occ(ch, i):
return L[:i].count(ch) # a real index answers this in O(1) or O(log sigma)
lo, hi = 0, len(L)
for ch in reversed(pattern):
if ch not in C:
return 0
lo = C[ch] + occ(ch, lo)
hi = C[ch] + occ(ch, hi)
if lo >= hi:
return 0
return hi - lo
L, sa = bwt("banana")
assert L == "annb$aa"
assert fm_count(L, "ana") == 2
assert fm_count(L, "nab") == 0
assert fm_count(L, "a") == 3
Backward search needs only C and occ, never the text, which is why the FM-index is self-indexing. With occ answered by a rank structure over L (a wavelet tree or wavelet matrix for general alphabets, Section 24.4), counting costs O(m) rank queries for a pattern of length m, independent of the text length.
24.8 ★ The vEB recurrences. (a) Solve T(u) = T(√u) + O(1) by substituting m = log₂ u, and count the levels of recursion for u = 2^32 and u = 2^64. (b) Suppose the clusters did not cache their max, so that successor first calls successor on x’s cluster and, only if that returns None, calls successor on the summary. Write the recurrence for the worst case and solve it. (c) Show that the array-based version’s space, S(u) = (√u + 1) · S(√u) + Θ(√u), is Θ(u). Take u = 2^(2^i) so that every square root is exact.
Solution
(a) Let S(m) = T(2^m). Since √(2^m) = 2^(m/2), the recurrence becomes S(m) = S(m/2) + c, which unrolls to c · log₂ m + S(1). So T(u) = O(log m) = O(log log u). For u = 2^32 the key lengths are 32, 16, 8, 4, 2, 1: six levels. For u = 2^64 there are seven.
(b) In the worst case both calls happen: the cluster call runs all the way down and finds nothing, then the summary call runs. T(u) = 2T(√u) + O(1), so S(m) = 2S(m/2) + c, which is Θ(m) (the recursion tree has m leaves). That is T(u) = Θ(log u), no better than a balanced BST. The same thing happens to insert if the min is also stored in its cluster: inserting into an empty cluster would then recurse, so a new cluster would cost a full call on the summary and another on the cluster. The cached max and the “min lives only at the top” rule are each what keep the work to one call per level.
(c) Lower bound: count the base structures (u = 2). L(u) = (√u + 1) · L(√u) ≥ √u · L(√u) with L(2) = 1, so for u = 2^(2^i), L(u) ≥ 2^(2^(i−1)) · 2^(2^(i−2)) ⋯ 2^1 = 2^(2^i − 1) = u/2. Upper bound: write the extra term as at most a√u and let s₀ = S(2). Claim S(u) ≤ cu − b with c = a + s₀ and b = c + a. The base case holds: 2c − b = 2a + 2s₀ − 2a − s₀ = s₀. For the inductive step,
S(u) ≤ (√u + 1)(c√u − b) + a√u = cu − b + (c + a − b)√u ≤ cu − b,
since c + a − b = 0. So S(u) = Θ(u).
24.9 ★★ Predecessor is not a mirror image. Write predecessor(V, x), the largest element of the VEB tree V smaller than x, or None. A natural first attempt mirrors successor: swap min with max, < with >, and successor with predecessor. Run that mirror on the u = 16 example of Section 24.7 for x = 3, 4 and 14, explain what goes wrong, and fix it. What is the running time of the fixed version?
Hint
Where does each structure keep its minimum? Successor never needs to look for a smaller element, so it never notices.
Solution
The mirror image returns None for x = 3 (the answer is 2) and for x = 4 (the answer is 3), and for x = 14 it crashes with a TypeError instead of returning 13.
- x = 3: cluster 0 holds only low 3, so nothing smaller is in it; the summary has no nonempty cluster before 0; the mirror gives up. But V’s min, 2, is in no cluster, so the clusters never mention it.
- x = 4: the summary is asked for its predecessor of 1. The summary’s own min, cluster number 0, lives only at the summary’s top, so the same bug one level down returns
Noneinstead of 0. - x = 14: cluster 3 is asked for its predecessor of 2. Its min, 1, lives only at its top, its inner clusters hold 2 and 3, so the inner call returns
NoneandV.index(3, None)fails.
The fix: when no earlier nonempty cluster exists, the answer is the structure’s own min, if that is smaller than x.
def predecessor(V, x):
"""Largest element less than x, or None."""
if V.max is not None and x > V.max:
return V.max
if V.k == 1:
return 0 if x == 1 and V.min == 0 else None
h, l = V.high(x), V.low(x)
c = V.clusters.get(h)
if c is not None and l > c.min: # answer is in x's own cluster
return V.index(h, predecessor(c, l))
prev = predecessor(V.summary, h) if V.summary is not None else None
if prev is None: # no earlier cluster, but the min
if V.min is not None and x > V.min: # lives outside every cluster
return V.min
return None
return V.index(prev, V.clusters[prev].max)
V = VEB(4)
for key in [2, 3, 9, 13, 14, 15]:
V.insert(key)
assert [predecessor(V, x) for x in (2, 3, 4, 10, 14, 15)] == [None, 2, 3, 9, 13, 14]
The fix adds an O(1) test and no recursive call, so predecessor is still one call on a universe of size √u plus O(1) work: O(log log u). (Checked against a sorted list on random sets for universes up to 2^12.)
24.10 ★★ x-fast and y-fast tries by hand. (a) For w = 4 and S = {3, 4, 10, 12}, list the prefixes stored at each level of the x-fast trie and count the hash-table entries. (b) Find the successor and predecessor of 9 by binary search over prefix lengths. Which prefixes are probed? (c) Estimate the number of hash-table entries for n = 10⁶ random 64-bit keys in an x-fast trie, and in a y-fast trie whose buckets hold 64 keys on average.
Solution
(a) In binary, 3 = 0011, 4 = 0100, 10 = 1010, 12 = 1100.
| ℓ | prefixes |
|---|---|
| 0 | ε |
| 1 | 0, 1 |
| 2 | 00, 01, 10, 11 |
| 3 | 001, 010, 101, 110 |
| 4 | 0011, 0100, 1010, 1100 |
That is 1 + 2 + 4 + 4 + 4 = 15 entries, fewer than n(w + 1) = 20 because keys share prefixes near the root.
(b) 9 = 1001. Start with lo = 0, hi = 4. Probe ℓ = 2: 10 is present, lo = 2. Probe ℓ = 3: 100 is absent, hi = 2. The search stops at node 10 after two probes. Its only child is 101 (key 10), and the next bit of 9 is 0, so 9 branches off to the left of every key under 10: the successor is that subtree’s min, 10, and the predecessor is the leaf before 10 in the linked list, 4.
(c) Level ℓ holds at most min(2^ℓ, n) prefixes. For random keys, the levels down to about ℓ = 20 (2^20 ≈ 10⁶) are nearly full and the deeper ones hold nearly n prefixes each. The expected total is Σ over ℓ = 0..64 of 2^ℓ (1 − (1 − 2^−ℓ)^n) ≈ 39 million entries, about 39 per key. At a prefix plus two words per entry that is close to a kilobyte per key before any hash-table overhead.
The y-fast trie puts only the 10⁶ / 64 ≈ 15,600 representatives in its x-fast trie. The same sum with n = 15,625 gives about 0.7 million entries, plus 10⁶ BST nodes for the buckets: under two stored items per key. Dividing the x-fast trie’s population by w is exactly what turns O(nw) space into O(n).
Where this connects
- Chapter 19: Emerging and Specialized Structures. Where this research is heading next
- Chapter 16: External Memory and Cache-Oblivious Structures. The cache-oblivious model several of these depend on
Chapter 25: Complete Selection Guide and Complexity Reference
This chapter is for the moment you have a problem and need a structure. Section 25.1 maps common needs to choices, split by whether the data is static or changing. Sections 25.2 and 25.3 are the reference tables. Section 25.4 gives a short decision procedure for when no row of the matrix fits exactly, Section 25.5 works through six realistic selection problems end to end, and Section 25.6 lists the mistakes that come up again and again in code review.
25.1 Data Structure Selection Matrix
Most selection questions turn on one distinction first: is the data static (built once, queried many times) or does it change between queries? Static data admits simpler, faster, smaller structures, and that column is often the right answer even when it looks too simple.
| Need | Static data | With updates | Notes |
|---|---|---|---|
| Lookup by exact key | Sorted array + binary search; perfect hashing for a fixed key set | Hash table (Robin Hood or Swiss table, Chapter 12) | A hash table gives up ordering; if you will ever need “next key” or a range, see the next row |
| Ordered map: successor, range scans | Sorted array | Red-black tree or skip list in memory; B+ tree on disk | Sorted arrays win for read-heavy data even with occasional bulk rebuilds |
| Integer keys below u: predecessor | Sorted array | B-tree or radix tree in practice; vEB or y-fast trie in theory (Chapter 24) | The O(log log u) structures rarely beat a cache-friendly B-tree below about 10⁷ keys |
| Repeated minimum or maximum | Sorted array | Binary heap (4-ary is often faster); indexed heap if you need decrease-key; radix heap for monotone integer keys | A balanced BST also works and supports deletion of arbitrary keys |
| Range sum | Prefix sums, O(1) query | Fenwick tree (point updates); segment tree with lazy propagation (range updates) | |
| Range minimum or maximum | Sparse table, O(1) query; Fischer-Heun RMQ in 2n + o(n) bits | Segment tree | Idempotence (min(x, x) = x) is what lets a sparse table use overlapping windows |
| k-th smallest overall, rank of a key | Sorted array | Order-statistic tree; Fenwick tree over compressed values | Redis sorted sets use a skip list with span counts |
| k-th smallest in a subarray a[l..r] | Wavelet tree or wavelet matrix | Offline techniques, or a Fenwick tree of order-statistic trees in O(log² n) | |
| Path or subtree queries on a tree | Heavy-light decomposition + segment tree | Link-cut tree when edges are linked and cut | Euler tour + segment tree handles subtree aggregates |
| Connectivity | Union-find, when edges are only added | Offline with deletions: rollback DSU over a segment tree of time; online: HDT (research) | |
| Find one pattern in a text | KMP, Z-algorithm, or the language’s built-in search | Rabin-Karp when many windows must be compared | |
| Find many patterns in one pass | Aho-Corasick | ||
| Many queries against one fixed text | Suffix array + LCP; FM-index when it must be compressed | Suffix automaton supports appending | |
| Palindromes | Manacher’s algorithm (all maximal palindromes in O(n)) | Palindromic tree (distinct palindromes, append-only) | |
| Approximate membership | Bloom filter; xor filter for a fixed set | Cuckoo filter (supports deletion); quotient filter | |
| Count of distinct items | HyperLogLog | HyperLogLog | Mergeable across machines |
| Item frequencies, heavy hitters | Count-Min sketch; Space-Saving for top-k | Same | |
| Quantiles over a stream | t-digest, KLL | Same | |
| Cache | LRU (hash map + doubly linked list); W-TinyLFU for skewed workloads | Chapter 29 | |
| Text being edited | Piece table or rope; gap buffer for a single cursor | Chapter 13 |
25.2 Complete Complexity Reference
Competitive Programming Structures
| Structure | Build | Query | Update | Space |
|---|---|---|---|---|
| Segment Tree | O(n) | O(log n) | O(log n) | O(n) |
| Fenwick Tree | O(n) | O(log n) | O(log n) | O(n) |
| Heavy-Light Decomp | O(n) | O(log² n) | O(log² n) | O(n) |
| Link-Cut Tree | O(n) | O(log n) amortized | O(log n) amortized | O(n) |
| DSU with rollback | O(n) | O(log n) | O(log n) | O(n) |
| Mo’s Algorithm | n/a | O(√n) amortized per query | n/a | O(n) |
| Sparse Table | O(n log n) | O(1) | Not supported | O(n log n) |
| Wavelet Tree | O(n log σ) | O(log σ) | Static | O(n log σ) |
| Suffix Automaton | O(n) | O(m) | Incremental | O(n), ≤ 2n−1 states |
| Palindromic Tree | O(n) | O(1) amortized | Incremental | O(n) |
| Li Chao Tree | O(n log C) | O(log C) | O(log C) | O(n) |
Two rows are easy to get wrong. DSU with rollback is O(log n), not O(α(n)). Undoing a union requires knowing exactly which parent pointers changed, and path compression rewrites pointers all along the path, so rollback DSU must use union by rank alone. You trade the inverse-Ackermann bound for the ability to undo. And Mo’s algorithm is offline: it answers q queries in O((n + q)√n) total, so the O(√n) is an amortized per-query share, not a bound on any individual query.
Research-Grade Structures
| Structure | Space | Query | Notes |
|---|---|---|---|
| Succinct Bit Vector | n + o(n) bits | O(1) rank and select | Optimal to within lower-order terms |
| FM-Index | n·H_k(T) + o(n log σ) bits | O(m) count | Self-indexing: replaces the text |
| LOUDS Tree | 2n + o(n) bits | O(1) navigation | Needs rank/select support |
| Wavelet Matrix | n log σ + o(n log σ) bits | O(log σ) | Faster constants than a wavelet tree |
| Cache-oblivious BST | O(n) | O(log_B n) I/Os | Optimal without knowing B |
| CRDT G-Counter | O(r) for r replicas | O(1) read, O(r) merge | Converges without coordination |
| Fibonacci Heap | O(n) | O(1) find-min, O(log n)★ delete-min | O(1) insert and O(1)★ decrease-key |
| HDT Dynamic Connectivity | O(n log n) | O(log n / log log n) | O(log² n)★ update (Holm–de Lichtenberg–Thorup) |
★ = amortized. H_k(T) is the k-th order empirical entropy of the text. The FM-index is compressed to the text’s own entropy, which is what “self-indexing” means: you can discard the original text and still reconstruct any substring.
25.3 Algorithm Design Patterns
Each paradigm is defined by a bookkeeping question it must answer repeatedly, and becomes practical when a structure answers that question fast enough. Chapter 21 develops this in full; the summary:
| Paradigm | Question asked repeatedly | Structure that answers it | Examples |
|---|---|---|---|
| Divide and conquer | Where do I resume? | Stack (implicit or explicit) | Quicksort, merge sort, binary search |
| Dynamic programming | Have I computed this state? | Array (dense) or hash map (sparse) | LCS, knapsack, edit distance |
| Greedy | What is the best remaining option? | Priority queue; union-find for connectivity | Huffman, Dijkstra, Prim, Kruskal |
| Backtracking | Can this branch still succeed, and how cheaply do I undo? | Bitmask, DLX, rollback DSU | N-Queens, Sudoku, exact cover |
| Randomized | (Defeat the adversary) | Depends, randomness is the technique | Quicksort, skip lists, treaps, Bloom filters |
The recurring trap: greedy is only correct when the problem has the matroid property or an equivalent exchange argument. Without it, greedy produces plausible wrong answers, which is worse than obviously wrong ones, because they pass casual testing.
25.4 A Decision Procedure
When no row of the matrix fits exactly, five questions, asked in order, usually narrow the choice to one or two candidates.
- What are the operations, and in what proportion? Write them down with rough frequencies: “10⁶ lookups per second, 10³ inserts per second, a range scan per minute”. Most bad choices come from optimising an operation that is rare. A structure that makes the common operation O(1) and the rare one O(n) is often right.
- Is the data static, append-only, or fully dynamic? Static data allows sorted arrays, sparse tables, perfect hashing and succinct structures, all of which are smaller and faster than their dynamic counterparts. Append-only data allows logs, LSM trees and suffix automata.
- Does order matter? If any query mentions “next”, “range”, “smallest”, “top” or “before”, you need an ordered structure (sorted array, balanced tree, B-tree, skip list, heap). If every query is “is this key present, and what is its value”, a hash table is almost always the answer.
- Does it fit in memory, and on one machine? If not, the cost model changes from operations to block transfers (Chapter 16): B+ trees and LSM trees on one machine, partitioned structures across several (Chapter 27).
- Can the answer be approximate? If a small, bounded error is acceptable, a probabilistic structure (Chapter 14) can be thousands of times smaller. If it must be exact and the exact structure fits in memory, use the exact one.
After choosing, check the answer against three practical constraints the asymptotics ignore: memory per element (a Python dict entry costs around 100 bytes once you include the key and value objects, so 50 million entries need about 5 GB), worst-case latency (amortized and expected bounds allow occasional slow operations), and whether a well-tested library already provides it (Chapter 22).
25.5 Worked Selection Problems
Each problem states the workload, the choice, the cost, and why the obvious alternatives lose.
Autocomplete over a fixed vocabulary
Workload. Ten million product names, each with a popularity score, rebuilt nightly. Each keystroke asks for the 10 most popular names starting with the typed prefix, at thousands of queries per second.
Choice. The data is static, so sort the names. All names with a given prefix form one contiguous block of the sorted array, found with two binary searches. Inside the block, the top 10 by popularity come from a sparse table of “index of the maximum score” (Section 23.11) and a heap: take the maximum of the block, split the block around it, push the maximum of each half, and repeat 10 times.
import heapq
from bisect import bisect_left
class Autocomplete:
"""Top-k most popular completions of a prefix, over a fixed vocabulary."""
def __init__(self, words_with_scores):
pairs = sorted(words_with_scores) # sort by word
self.words = [w for w, _ in pairs]
self.score = [s for _, s in pairs]
n = len(pairs)
# Sparse table of argmax over the scores (Chapter 23.11).
self.table = [list(range(n))]
j = 1
while (1 << j) <= n:
prev, half = self.table[-1], 1 << (j - 1)
row = []
for i in range(n - (1 << j) + 1):
a, b = prev[i], prev[i + half]
row.append(a if self.score[a] >= self.score[b] else b)
self.table.append(row)
j += 1
def _argmax(self, lo, hi): # best index in [lo, hi)
j = (hi - lo).bit_length() - 1
a, b = self.table[j][lo], self.table[j][hi - (1 << j)]
return a if self.score[a] >= self.score[b] else b
def complete(self, prefix, k):
lo = bisect_left(self.words, prefix)
hi = bisect_left(self.words, prefix + '') # end of the prefix block
heap, out = [], []
if lo < hi:
i = self._argmax(lo, hi)
heap.append((-self.score[i], i, lo, hi))
while heap and len(out) < k:
_, i, a, b = heapq.heappop(heap)
out.append(self.words[i])
for x, y in ((a, i), (i + 1, b)): # split around the winner
if x < y:
m = self._argmax(x, y)
heapq.heappush(heap, (-self.score[m], m, x, y))
return out
Cost. O(n log n) to build, once a night. Each query is O(log n) for the binary searches plus O(k log k) for the heap, independent of how many names match the prefix. With “car” typed, the block might hold 50,000 names; the query still touches only about 2k of them.
Why not the alternatives? A trie answers the prefix part in O(prefix length) but then must explore every completion to find the most popular, unless each trie node stores its own top 10, which multiplies memory by the average depth. Scanning the block and sorting by popularity costs O(block size) per keystroke, which is fine for long prefixes and fatal for “a”.
A live leaderboard
Workload. 50 million players, each with an integer score between 0 and 10⁶. Scores change constantly. Queries: a player’s rank, and the top 100.
Choice. Two options are both good, and the score range decides. A general order-statistic structure (a skip list with span counts, as in Redis sorted sets, or a size-augmented balanced tree, Chapter 7) gives O(log n) update and rank for any score type. Because scores here are bounded integers, a Fenwick tree indexed by score that counts players per score value is smaller and faster: an update is two point updates (remove the old score, add the new one), and a rank is one prefix sum, each O(log 10⁶), about 20 steps, in a 4 MB array. Ties are broken separately (for example by time reached).
Why not the alternatives? Sorting on every query is O(n log n), seconds per query at 50 million. A hash map from player to score answers “what is my score” but not “what is my rank”.
Has the crawler seen this URL?
Workload. A web crawler has seen 5 billion URLs and checks each newly discovered link before fetching it. The full URL set lives in an on-disk key-value store.
Choice. A Bloom filter in memory in front of the on-disk store. At a 1% false-positive rate it needs about 9.6 bits per URL, which is about 6 GB for 5 billion URLs, with 7 hash functions. A “not present” answer is always correct, so new URLs (the common case for a crawler at the frontier) never touch the disk. A “present” answer is checked against the store, which catches the 1% of false positives.
Why not the alternatives? An exact in-memory hash set of 5 billion URLs at an average of 70 bytes each needs well over 350 GB. Checking the disk store for every link costs a random read per link. The Bloom filter is the classic case of question 5 in Section 25.4: approximate is acceptable because an exact check backs it up.
A rate limiter for an API
Workload. A million API keys, each allowed 100 requests per minute, checked on every request.
Choice. A hash map from API key to a token bucket (two numbers: tokens remaining and last refill time, Chapter 29). Each check is O(1) expected and the whole table is tens of megabytes.
When it changes. If the keys are unbounded (rate limiting by client IP during an attack, say), the map can be made to grow without limit. Then a Count-Min sketch per time window bounds memory regardless of the number of distinct clients. It never undercounts, so it never lets an abuser through; at worst it rate-limits a few legitimate clients early.
Meeting rooms and overlapping intervals
Workload. A calendar service stores bookings as [start, end) intervals per room and must reject any new booking that overlaps an existing one.
Choice. Bookings in one room never overlap one another, so a balanced ordered map keyed by start time is enough: a new interval [s, e) conflicts only with the booking whose start is the floor of s (does it end after s?) or the ceiling of s (does it start before e?). Two O(log n) lookups (Chapter 7, floor and ceiling). An interval tree is needed only when stored intervals may overlap one another, for example when the query is “which of all these events are happening at 3 pm?”
Latency percentiles across a fleet
Workload. A thousand servers each record request latencies; a dashboard shows the fleet-wide p50, p99 and p99.9 every minute.
Choice. A t-digest (or a KLL sketch) per server per minute, a few kilobytes each, merged centrally (Chapter 14). Mergeability is the deciding property: you cannot average per-server p99s to get the fleet p99, but you can merge the sketches and query the merged one.
Why not the alternatives? Shipping every raw latency costs gigabytes per minute. Fixed histogram buckets work if you know the range in advance, and HdrHistogram is a good choice when you do; t-digest needs no such tuning and is most accurate at the extreme percentiles you care about.
25.6 Common Selection Mistakes
- A hash map when the queries need order. The code then sorts the keys on every request. If any query mentions a range or “the next one”, choose an ordered structure up front.
- A linked list for “fast insertion”. Insertion is O(1) only once you hold the node, and finding it is O(n) with a cache miss per step. A dynamic array usually wins even for insertions in the middle (Chapter 22 has the measurements).
- Linear operations hidden in a library call.
x in some_list,list.pop(0)andlist.insert(0, x)in Python are all O(n). Inside a loop they quietly make an algorithm quadratic. - Choosing by asymptotic bounds alone. Fibonacci heaps, van Emde Boas trees and many other theoretical winners lose to simpler structures at realistic sizes because of constant factors and cache behaviour.
- Approximate structures where exact ones fit. A Bloom filter for 10,000 keys saves a few hundred kilobytes and adds false positives to debug. Use probabilistic structures when the exact one does not fit, or when mergeability or a fixed memory budget matters.
- Ignoring worst-case latency. Amortized O(1) includes the occasional O(n) resize, and expected O(1) includes the occasional long probe sequence. For a latency-sensitive path, preallocate, or choose structures with worst-case bounds.
- Distributing too early. A structure that fits on one machine is far simpler and faster than any distributed one. Check the memory arithmetic before reaching for a cluster.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
25.1 ★ Pick from the matrix. For each workload, name the structure you would use from Sections 25.1 and 25.2 and the per-operation cost you get. (a) A static array of 10^6 integers and 10^6 range-minimum queries. (b) An array with interleaved point updates and range-sum queries. (c) An array with interleaved “add v to every element in [l, r]” and “sum of [l, r]”. (d) A static array and queries “the k-th smallest value in a[l..r]”.
Solution
| Workload | Choice | Cost |
|---|---|---|
| (a) static range min | Sparse table | O(n log n) build, O(1) query |
| (b) point update, range sum | Fenwick tree | O(log n) each |
| (c) range add, range sum | Segment tree with lazy propagation | O(log n) each |
| (d) static range k-th smallest | Wavelet tree | O(log σ) query after O(n log σ) build |
(a) has no updates and min is idempotent, so the overlapping-window trick applies and nothing beats O(1). (b) is exactly what a Fenwick tree does, with the smallest code and memory. (c) needs range updates: a plain Fenwick tree only supports point updates, so use the lazy segment tree of Chapter 23 (or the two-Fenwick-tree trick, which is less general). (d) is the wavelet tree’s defining query; a merge sort tree also works but costs O(log² n) or worse per query.
25.2 ★ The greedy trap. Section 25.3 says greedy is only correct with a matroid property or an exchange argument. (a) Disprove: “To make change with the fewest coins, repeatedly take the largest coin that fits.” Use coins {1, 3, 4} and amount 6. (b) Name the structure that the table pairs with greedy, and explain why using it does not rescue (a).
Solution
(a) Greedy takes 4, then 1, then 1: 3 coins. The optimum is 3 + 3: 2 coins. The claim is false. (It happens to hold for coin systems like {1, 5, 10, 25}, which is why it passes casual testing, the exact failure mode the section warns about.)
(b) The table pairs greedy with a priority queue (“what is the best remaining option?”). A priority queue makes each greedy choice fast; it says nothing about whether the choice is correct. Here the “best remaining option” is answered in O(log n) and is still the wrong option. The correct method for arbitrary coin systems is dynamic programming over amounts, which the same table pairs with an array: best[x] = 1 + min(best[x − c]) over coins c, O(amount × coins).
25.3 ★★ Amortized, offline, or worst case? A trading system must answer every request within a fixed latency budget, and requests arrive one at a time. For each of the following rows from Section 25.2, say whether the stated bound protects a single request, and give a concrete situation in which a single operation is much slower than the table entry suggests: (a) Fibonacci heap delete-min, (b) link-cut tree path query, (c) Mo’s algorithm, (d) DSU with rollback.
Hint
The ★ in the table marks amortized bounds. One row is not amortized at all, it is offline.
Solution
(a) Amortized only. After n inserts (each O(1), just a new root in the root list), the first delete-min must consolidate all n roots: Θ(n) for that single call. The amortized O(log n) is paid for by the cheap inserts before it.
(b) Amortized only. Link-cut trees rest on splay trees. A single access can splay through a splay tree of depth Θ(n) (for example after a run of operations that left a path-shaped splay tree), costing Θ(n) once, with the cost recovered over later operations.
(c) Not applicable at all. Mo’s algorithm is offline: it sorts all queries before answering any. With requests arriving one at a time it cannot run. The O(√n) “per query” is a share of an O((n + q)√n) total.
(d) Worst case per operation. With union by size and no path compression, every tree has depth at most log₂ n, so every find and union is O(log n) with no amortization. This is the one structure of the four whose bound you can quote for a single request.
For the latency budget, prefer worst-case structures (binary heap over Fibonacci heap, a red-black or AVL tree over a splay tree) and accept slightly worse averages.
25.4 ★★ Prove the rollback DSU bound. Section 25.2 says rollback DSU uses union by rank (or size) alone and costs O(log n). Using the DSU class of Section 23.14, which links the smaller-size root under the larger, prove that every node has depth at most ⌊log₂ n⌋. Then explain why rollback cannot break the bound.
Hint
Ask what has to happen to the size of a node’s set each time that node’s depth increases by one.
Solution
Pick any node x. Its depth only changes when its root r is linked under another root r' in union, and that increases the depth of every node in r’s tree, including x, by exactly 1. The code links y under x only after swapping so that size[x] ≥ size[y], so size[r'] ≥ size[r]. After the link, x’s set has size size[r] + size[r'] ≥ 2 · size[r]: it at least doubled.
x starts in a set of size 1, and no set exceeds n, so x’s set can double at most ⌊log₂ n⌋ times. Hence depth(x) ≤ ⌊log₂ n⌋, and find, which walks from x to its root, costs O(log n). union is two finds plus O(1).
rollback pops logged changes in reverse order, restoring parent[y] and size[x] exactly. Each state it restores is a state the structure was in earlier, which satisfied the bound when it was built. Path compression is what would break rollback: it rewrites pointers that are never logged (Exercise 23.5), so “restoring” would produce a state that never existed.
25.5 ★★ Sparse table or segment tree at n = 10^6? You have a static array of n = 10^6 integers, q range-minimum queries, and a 64 MB memory limit, with 4-byte integers. (a) How many rows does the SparseTable of Section 23.11 build, and how much memory does it use? (b) How much does an array-based segment tree with 4n slots use? (c) Which do you choose, and how would your answer change if the limit were 256 MB and q = 10^7?
Solution
(a) self.k = log[n] + 1. Since 2^19 = 524,288 ≤ 10^6 < 2^20, log[10^6] = 19 and there are 20 rows. The chapter’s code allocates n slots per row: 20 × 10^6 = 2 × 10^7 integers, 80 MB. (Trimming row k to its n − 2^k + 1 valid entries saves only about 5%: the top rows are shorter, but most rows are nearly full length.)
(b) 4 × 10^6 integers, 16 MB. An iterative bottom-up segment tree needs only 2n, 8 MB.
(c) At 64 MB the sparse table does not fit, so use the segment tree: O(n) build, O(log n) query, about 2 · 20 node visits per query plus pushes. At 256 MB with q = 10^7, the sparse table fits and wins clearly: its build is about 2 × 10^7 op calls, and each query is two lookups, about 2 × 10^7 lookups total, versus several hundred million node visits for the segment tree. The row in Section 25.2 (O(n log n) space, O(1) query) is the whole tradeoff: memory for query time, and only for static data with an idempotent operation.
25.6 ★★★ Offline dynamic connectivity. Section 25.1 lists an offline approach for connectivity when edges can also be removed. You are given the whole sequence of operations in advance: ('add', u, v), ('remove', u, v) and ('query', u, v) (“are u and v connected right now?”). A plain DSU cannot delete edges. Using the rollback DSU of Section 23.14 and a segment tree over time, write offline_connectivity(n, ops) that returns the query answers in order, and state its running time.
Hint
Each edge is alive during one contiguous interval of operation indices. Insert it into the O(log T) segment tree nodes that cover that interval, then walk the tree depth-first: union a node’s edges on entry, answer queries at leaves, and roll back on exit.
Solution
def offline_connectivity(n, ops):
"""ops: list of ('add', u, v), ('remove', u, v) or ('query', u, v).
Returns the answers to the queries, in order."""
T = len(ops)
if T == 0:
return []
seg = [[] for _ in range(4 * T)]
def insert(node, l, r, ql, qr, edge):
if qr < l or r < ql:
return
if ql <= l and r <= qr:
seg[node].append(edge)
return
mid = (l + r) // 2
insert(2 * node, l, mid, ql, qr, edge)
insert(2 * node + 1, mid + 1, r, ql, qr, edge)
start = {} # edge -> time it was added
for t, (kind, u, v) in enumerate(ops):
e = (min(u, v), max(u, v))
if kind == 'add':
start[e] = t
elif kind == 'remove':
insert(1, 0, T - 1, start.pop(e), t - 1, e)
for e, s in start.items(): # never removed: alive to the end
insert(1, 0, T - 1, s, T - 1, e)
dsu = DSU(n)
answers = [None] * T
def solve(node, l, r):
snap = dsu.snapshot()
for u, v in seg[node]:
dsu.union(u, v)
if l == r:
kind, u, v = ops[l]
if kind == 'query':
answers[l] = dsu.find(u) == dsu.find(v)
else:
mid = (l + r) // 2
solve(2 * node, l, mid)
solve(2 * node + 1, mid + 1, r)
dsu.rollback(snap)
solve(1, 0, T - 1)
return [a for a, op in zip(answers, ops) if op[0] == 'query']
ops = [('add', 0, 1), ('add', 1, 2), ('query', 0, 2),
('remove', 0, 1), ('query', 0, 2), ('add', 0, 2), ('query', 0, 1)]
assert offline_connectivity(3, ops) == [True, False, True]
Why it is correct: when the DFS reaches leaf t, the DSU contains exactly the edges stored on the root-to-leaf path, and an edge is stored on that path iff its alive interval contains t. So the DSU is the graph at time t. Rollback on exit restores the state of the parent, which is why path compression is not allowed here (Exercise 25.4).
Cost: each edge lands in O(log T) segment tree nodes, and each of those causes one union and one undo at O(log n). Total O(T log T log n), plus O(T) for the tree. This is the offline alternative to Holm–de Lichtenberg–Thorup: much simpler, no amortization, but it needs every operation up front. If queries must be answered as they arrive, you are back to HDT’s O(log² n) amortized updates.
25.7 ★★ The leaderboard, by hand and in code. Section 25.5 suggests a Fenwick tree indexed by score for a leaderboard with bounded integer scores. (a) Five players have scores 3, 5, 5, 1 and 7, with scores between 0 and 7. A player’s rank is 1 plus the number of players with a strictly higher score. Give the rank of a player with each score 7, 5, 3 and 1, and say which prefix sum computes each. (b) The player with score 1 improves to 6. What changes in the tree, and what are the new ranks? (c) Implement it.
Hint
The number of players with a strictly higher score than s is the total minus the number with score at most s, and “at most s” is a prefix sum over the count array.
Solution
(a) Counts per score: 1 player at 1, 1 at 3, 2 at 5, 1 at 7, total 5. Rank(s) = 1 + 5 − (players with score ≤ s):
| Score | Players ≤ score (prefix sum) | Rank |
|---|---|---|
| 7 | 5 | 1 |
| 5 | 4 | 2 |
| 3 | 2 | 4 |
| 1 | 1 | 5 |
Both players with score 5 share rank 2, and the next rank is 4: standard competition ranking.
(b) Two point updates: subtract 1 at score 1, add 1 at score 6, each O(log 8). Scores are now 3, 5, 5, 6, 7, and the ranks of 7, 6, 5, 3 are 1, 2, 3, 5.
(c)
class ScoreLeaderboard:
"""Rank queries for integer scores in [0, max_score], via a Fenwick tree."""
def __init__(self, max_score):
self.n = max_score + 1
self.tree = [0] * (self.n + 1) # 1-indexed Fenwick tree
self.total = 0
def _add(self, score, delta):
i = score + 1
while i <= self.n:
self.tree[i] += delta
i += i & -i
def _count_at_most(self, score): # players with score <= s
i, s = score + 1, 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add_player(self, score):
self._add(score, 1)
self.total += 1
def change(self, old, new):
self._add(old, -1)
self._add(new, 1)
def rank(self, score):
"""1 + number of players with a strictly higher score."""
return 1 + self.total - self._count_at_most(score)
Every operation is O(log S) for S possible scores, regardless of the number of players, and the memory is S + 1 integers. For scores up to 10⁶ that is about 20 steps per operation in a 4 MB array.
25.8 ★★ Room bookings without an interval tree. Section 25.5 claims that for one room, where stored bookings never overlap, an ordered map keyed by start time is enough to reject overlapping bookings. (a) Explain why a new booking [s, e) can only conflict with the stored booking that starts at or just after s, or the one just before it. (b) Implement can_book with two sorted lists and bisect, and trace the bookings [9, 10), [13, 15), [10, 13), [9, 11), [14, 16), [8, 9) in that order. (c) When does this stop being enough?
Solution
(a) Stored bookings are disjoint, so sorted by start they are also sorted by end. Every booking after the first one starting at or after s starts even later, so if that first one starts at or after e, all later ones do too. Every booking before the one just before s ends no later than that one does, so if it ends at or before s, all earlier ones do too. Checking those two neighbours is enough.
(b)
from bisect import bisect_left
def can_book(starts, ends, s, e):
"""starts is sorted; bookings [starts[i], ends[i]) never overlap."""
i = bisect_left(starts, s) # first booking starting at or after s
if i < len(starts) and starts[i] < e: # it starts before we end
return False
if i > 0 and ends[i - 1] > s: # the one before ends after we start
return False
return True
def book(starts, ends, s, e):
if not can_book(starts, ends, s, e):
return False
i = bisect_left(starts, s)
starts.insert(i, s)
ends.insert(i, e)
return True
Trace, with half-open intervals so that touching is allowed:
| Request | Result | Why |
|---|---|---|
| [9, 10) | booked | empty |
| [13, 15) | booked | no neighbour overlaps |
| [10, 13) | booked | touches [9, 10) and [13, 15) but overlaps neither |
| [9, 11) | rejected | the booking starting at 9 starts before 11 |
| [14, 16) | rejected | [13, 15) ends after 14 |
| [8, 9) | booked | touches [9, 10) |
can_book is O(log n). With Python lists, book is O(n) because of insert; a balanced tree or sortedcontainers.SortedList makes it O(log n).
(c) It relies on stored intervals never overlapping. If they can overlap (several rooms in one structure, or “show every event at 3 pm” over arbitrary events), sorting by start no longer sorts by end, and an interval tree or a segment tree over time is needed.
Where this connects
- Chapter 22: Practical Considerations. The practical version of this decision process
Volume V: Network and System Design Data Structures
The previous volumes established data structures as fundamental building blocks of computation. This volume reveals a profound truth: network topologies and system design patterns are simply data structures applied at scale. When you examine distributed systems, load balancers, CDN architectures, and routing protocols through the lens of data structures, patterns emerge. A routing table is a trie for network paths. Consistent hashing is a modified hash ring. A distributed message queue is a persistent FIFO with durability guarantees. This volume bridges the gap between academic data structures and production system design, showing how foundational structures compose into the complex systems that power the internet.
Chapters
| Chapter | After it you can |
|---|---|
| 27: Distributed Data Structures | Explain DHTs and consistent hashing, order events with Lamport, vector and hybrid logical clocks, build CRDTs including a collaborative-text sequence CRDT, and reason about consensus and quorums |
| 28: Network Topology and Routing Data Structures | Implement longest-prefix match with binary and multibit tries, explain how routers reach one memory access per lookup (DIR-24-8), and balance flows with ECMP and Maglev hashing |
| 29: System Design as Data Structure Composition | Decompose key-value stores, message queues and storage engines into their structures, and choose load-balancing, caching and rate-limiting structures |
| 30: Advanced System Patterns and Case Studies | Explain how a search engine compresses and intersects posting lists, plus vector search, time series storage, event sourcing and sharding |
| 31: Real-World Case Studies | Trace the structures inside Spanner, Dynamo, Kafka, Delta Lake and Cloudflare’s edge cache |
| 32: Synthesis and Future Directions | Place every structure in the book on one spectrum of trade-offs, and read new research with that map in hand |
Before you start. Volume I and the hash table and graph chapters of Volume II. Chapter 14 (probabilistic structures) and Chapter 16 (external memory) are used heavily in Chapters 29 to 31.
Chapter 27: Distributed Data Structures
27.1 The Philosophy of Distributed Data
In single-machine computing, data structures operate on shared memory with uniform access times. Distributed computing shatters this model: data spans machines, networks have latency, and failures are not exceptions but expectations. Every distributed data structure must answer a fundamental question: how do we maintain the illusion of a single coherent data structure across a cluster of unreliable machines?
The CAP Theorem provides the theoretical foundation. In partitioned systems, you must choose between Consistency (all nodes see the same data) and Availability (every request receives a response). You cannot have both during network partitions. This trade-off shapes every distributed data structure.
PACELC extends CAP: if there is a partition (P), the system must choose between Availability (A) and Consistency (C). Else (E), even without partitions, the system must choose between Latency (L) and Consistency (C). A Dynamo-style system chooses L over C; a Bigtable-style system chooses C over L.
27.2 Distributed Hash Tables (DHT)
A DHT extends the hash table concept across a cluster. The key insight: map both data items and nodes onto the same hash space, creating a self-organizing overlay network.
Chord Protocol
Chord assigns each node and key an m-bit identifier using consistent hashing. Each node maintains a finger table of size O(log N), allowing lookups in O(log N) hops.
Identifier calculation:
node_id = hash(node_ip)
key_id = hash(key)
Successor operation:
successor(id) = first node whose id >= id in the identifier circle
Finger table construction: The i-th entry of node n contains the successor of (n + 2^(i-1)) mod 2^m, for i = 1..m. This enables exponential jumps across the identifier space.
Join operation: A new node asks a known node to find its successor, then updates predecessor’s finger table and notifies its successor to adjust.
Stabilization: Periodically, nodes verify their successor’s predecessor and fix finger table entries to maintain correctness despite churn.
Kademlia
Kademlia uses a XOR metric for distance, enabling more efficient lookups. The key properties:
XOR Distance: d(a,b) = a ⊕ b. This distance is symmetric and satisfies the triangle inequality, enabling simpler routing.
Node buckets: Each node maintains one k-bucket (a list of up to k contacts) for each prefix length. Buckets are prioritized by least-recently-seen nodes, ensuring long-lived nodes stay in routing tables.
Lookup algorithm: Start with the closest node from own buckets. Parallel query α closest nodes at each step (typically α = 3). Terminate when no node in the queried set is closer than current best.
Republishing: Keys are republished periodically with longer expiration times. Original publishers become responsible for refreshing, preventing orphaned keys.
Apache Cassandra’s Partitioner
Cassandra uses consistent hashing with virtual nodes (vnodes). Each node owns multiple token ranges, enabling:
- Load balancing: Fine-grained distribution across heterogeneous hardware
- Easier cluster expansion: New nodes claim portions of existing ranges
- Mechanical sympathy: Sequential ranges for sequential access patterns
The Murmur3 partitioner hashes keys to 64-bit tokens. The ring divides this space into contiguous ownership zones.
27.3 Consistent Hashing
Traditional hashing maps N items to K servers with N/K average load. But adding or removing servers requires rehashing almost all items. Consistent hashing minimizes disruption.
Basic Algorithm
- Map both servers and keys to points on a circular hash space (0 to 2^32-1)
- Each key is assigned to the nearest server in the clockwise direction
- Virtual nodes (replicas) distribute load more evenly
Problem: Uneven distribution when nodes join/leave. Solution: introduce virtual nodes (100-200 per physical node), creating finer-grained ownership.
Server placement:
server_i = hash("server_" + i + "_replica_1")
server_i = hash("server_" + i + "_replica_2")
...
server_i = hash("server_" + i + "_replica_v")
Key placement:
key_assigned_to = first_server where server_token > key_token
Consistent Hashing with Bounded Load
Consistent hashing with bounded loads (Mirrokni, Thorup and Zadimoghaddam, 2018; HAProxy exposes it as hash-balance-factor) caps how much any node can receive:
- Pick ε > 0. With m keys (or active requests) on n nodes, each node gets a capacity of ⌈(1+ε)·m/n⌉
- A key hashes to the ring as usual; if its clockwise node is full, it keeps walking clockwise to the first node with spare capacity
- No node ever exceeds (1+ε) times the average load. Smaller ε gives tighter balance but displaces more keys from their natural owner
27.4 Distributed Snapshots and State Machine Replication
Replicating state across machines requires capturing consistent global states despite concurrent operations.
Chandy-Lamport Algorithm
Designed for distributed snapshot collection without process coordination:
- Initiator records its own state, then sends a marker on every outgoing channel
- When a process receives a marker on channel C:
- If it has not yet recorded its state: record local state, record C’s state as empty, send a marker on every outgoing channel, and start recording messages arriving on every other incoming channel
- Otherwise: stop recording C; C’s state is the messages that arrived on C after the process recorded its own state
- When every process has recorded its state and received a marker on every incoming channel, the snapshot is complete
Causality guarantee: With FIFO channels, the algorithm captures a consistent cut: if a message’s receipt is in the snapshot, so is its send. Messages sent before the cut but received after it appear as recorded channel state.
State Machine Replication
A deterministic state machine, combined with replicated logs of identical commands, guarantees consistent replicas. Key requirements:
- Determinism: Same initial state + same operations = same final state
- Atomicity: No partial command execution
- Ordering: Total order across all replicas
Paxos and Raft are consensus protocols that implement replicated logs. Raft’s key innovation: decomposing consensus into leader election, log replication, and safety.
Raft Log Entry:
{
term: number, // When entry was created
index: number, // Position in log
command: object // State machine command
}
27.5 CRDTs in Distributed Systems
Conflict-free Replicated Data Types (CRDTs) enable eventual consistency without coordination. They guarantee convergence regardless of operation order.
State-based Counters and Registers
Both of these are state-based: replicas exchange their whole state and combine it with a merge that is commutative, associative and idempotent (an operation-based CRDT instead broadcasts each operation and relies on the delivery layer to deliver it exactly once):
G-Counter (Grow-only Counter):
class GCounter:
def __init__(self):
self.state = {} # node_id -> count
def increment(self, node_id):
self.state[node_id] = self.state.get(node_id, 0) + 1
def merge(self, other):
for node_id, count in other.state.items():
self.state[node_id] = max(self.state.get(node_id, 0), count)
def value(self):
return sum(self.state.values())
LWW-Register (Last-Write-Wins Register):
class LWWRegister:
def __init__(self):
self.value = None
self.timestamp = 0
def set(self, value, timestamp):
if timestamp > self.timestamp:
self.value = value
self.timestamp = timestamp
def merge(self, other):
if other.timestamp > self.timestamp:
self.value = other.value
self.timestamp = other.timestamp
Timestamps must be unique for this register to converge: if two replicas write different values with the same timestamp, each keeps its own, since neither is strictly greater. Use (time, replica_id) pairs, compared lexicographically. Where the time comes from matters too; §27.8 shows why raw wall-clock time can let an older write beat a newer one.
State-based Sets (Convergent CRDTs)
Operations are applied locally and entire state is merged using join operations:
OR-Set (Observed-Remove Set):
from uuid import uuid4
class ORSet:
def __init__(self):
self.elements = {} # tag -> value
self.tombstones = set() # removed tags
def add(self, value):
tag = uuid4()
self.elements[tag] = value
return (tag, value)
def remove(self, tag):
self.tombstones.add(tag)
self.elements.pop(tag, None)
def merge(self, other):
# Union of elements and of tombstones, then drop removed tags
self.tombstones |= other.tombstones
self.elements.update(other.elements)
self.elements = {
k: v for k, v in self.elements.items()
if k not in self.tombstones
}
27.6 Distributed Consensus Mechanisms
Consensus is the problem of getting distributed nodes to agree on a value. FLP impossibility proves deterministic consensus is impossible with even one faulty process in asynchronous systems. Real systems relax requirements.
Raft Consensus
Raft’s three roles: Leader, Follower, Candidate. Term numbers provide logical clocks.
Leader election:
- Heartbeat timeout triggers follower → candidate transition
- Candidate votes for self, requests votes from others
- If majority votes, become leader
- Election timeout randomized to prevent split votes
Log replication:
- Client sends command to leader
- Leader appends to local log, replicates to followers in parallel
- When majority acknowledge, apply to state machine
- Commit index propagates with AppendEntries
Safety: If log entry has committed in a term, future leaders must contain it.
Multi-Paxos
Optimized Paxos for replicated state machines:
- One leader per term (reduces prepare messages)
- PreparePromise with all accepted entries instead of single value
- Prepare phase (phase 1) can be skipped while the leader is stable: each new command needs only the Accept phase
27.7 Quorum Systems
Quorums define the minimum number of nodes required for read/write operations.
Strict quorum: Read and write quorums must overlap (R + W > N)
Quorum construction:
- Majority quorum: R = W = ⌊N/2⌋ + 1 (tolerates ⌊(N−1)/2⌋ failures)
- Sloppy quorum: Prefer local nodes, fall back to remote on failure
- Hierarchical quorum: Tree structure reduces coordination
Version vectors track object versions across replicas:
class VersionVector:
def __init__(self):
self.versions = {} # node_id -> counter
def increment(self, node_id):
self.versions[node_id] = self.versions.get(node_id, 0) + 1
def merge(self, other):
for node_id, version in other.versions.items():
self.versions[node_id] = max(
self.versions.get(node_id, 0),
version
)
def happens_before(self, other):
# True if all entries in self <= other, and at least one <
keys = self.versions.keys() | other.versions.keys()
return all(
self.versions.get(k, 0) <= other.versions.get(k, 0)
for k in keys
) and any(
self.versions.get(k, 0) < other.versions.get(k, 0)
for k in keys
)
Anti-entropy with Merkle trees
A version vector tells two replicas how their copies of one key relate. It does not tell a replica which of its million keys differ from another replica’s. Read repair fixes keys that happen to be read, and hinted handoff replays writes that a node missed during a short outage, but a key that is never read and whose hint was lost stays divergent forever. Anti-entropy closes that gap. Each replica builds a Merkle tree over a key range: each leaf hashes a bucket of keys, and each internal node hashes its children’s hashes. Two replicas exchange root hashes; if they match (the common case), the ranges are identical and nothing more is sent. If not, they exchange the children of every node that differs and recurse. Each round trip descends one level, so a binary tree over n leaves locates the differing leaves in about log₂ n round trips, and with k differing leaves about 2k·log₂(n/k) hashes cross the network. §31.2 shows how Dynamo uses this, and Exercise 31.4 does the arithmetic.
Cassandra’s nodetool repair is the best-documented production case. Each replica reads its copy of the range and builds a Merkle tree (a validation compaction, which is why repair is I/O-heavy), the trees are compared, and the token ranges under mismatched leaves are streamed between replicas. The tree has a fixed resolution (DataStax documents a depth of 15, about 32,000 leaves), so when a leaf covers many partitions, one damaged partition causes all of its leaf’s partitions to be streamed. Operators reduce this overstreaming by repairing in smaller subranges, which gives each tree a finer resolution.
27.8 Logical Clocks
Several structures in this chapter quietly depend on a notion of time: the LWW-Register compares timestamps, version vectors compare histories, Raft orders leaders by term, and the Chandy-Lamport snapshot must not record a receive without its send. Physical clocks cannot supply that order reliably. Clocks synchronized by NTP typically disagree by milliseconds, and by far more after a bad sync or a VM pause, so a wall-clock timestamp can place an effect before its cause. What these structures actually need is the order of causality, and that can be tracked exactly without reading any clock.
Happens-before
Lamport (1978) defined the happens-before relation → on the events of a distributed system (local steps, sends and receives):
- If a and b are on the same process and a comes first, then a → b.
- If a is the send of a message and b is its receipt, then a → b.
- If a → b and b → c, then a → c.
If neither a → b nor b → a, the events are concurrent, written a ∥ b. Concurrent does not mean simultaneous: it means no chain of messages connects them, so neither could have influenced the other. Happens-before is a partial order, and a logical clock is a way of attaching timestamps to events that respects it.
Lamport clocks
Each process keeps one integer L. Before every local event or send it increments L; a message carries the sender’s L; on receiving a message stamped t, the receiver sets L = max(L, t) + 1.
class LamportClock:
def __init__(self):
self.time = 0
def local(self): # a local event, or a send
self.time += 1
return self.time
send = local
def receive(self, msg_time):
self.time = max(self.time, msg_time) + 1
return self.time
This guarantees the clock condition: a → b implies L(a) < L(b). Each of the three rules makes the timestamp strictly increase along one step of a causal chain, so it increases along the whole chain.
The converse is false: L(a) < L(b) does not imply a → b. Lamport time squashes a partial order into a chain of integers, and in doing so it forgets which pairs were concurrent. In the example below, L(b1) = 1 < L(a2) = 2, but no message reaches A from B before a2, so b1 ∥ a2. What Lamport timestamps do give is a cheap total order consistent with causality: compare (L, process_id) pairs lexicographically. That is how Lamport’s mutual exclusion algorithm orders requests, how the RGA in §27.9 names characters, and the right way to break ties in the LWW-Register of §27.5. Each timestamp is one integer, and each event costs O(1), worst-case.
Vector clocks
To detect concurrency rather than just respect causality, each process keeps one counter per process: a vector clock (Fidge and Mattern, independently, 1988). This is the same structure as the VersionVector of §27.7, with the same merge and the same comparison. The difference is what ticks it. A version vector belongs to a replicated object and increments when a replica updates that object. A vector clock belongs to a process and increments on every event, including sends and receives, and merges on every receive. So we build it on VersionVector rather than writing a second version:
class VectorClock(VersionVector):
"""The VersionVector of §27.7, ticked on every event of one process."""
def __init__(self, node_id):
super().__init__()
self.node_id = node_id
def stamp(self): # an immutable copy to attach to an event
snapshot = VersionVector()
snapshot.versions = dict(self.versions)
return snapshot
def local(self): # a local event, or a send
self.increment(self.node_id)
return self.stamp()
send = local
def receive(self, msg_stamp):
self.merge(msg_stamp) # entry-wise max with the sender's vector
self.increment(self.node_id)
return self.stamp()
def concurrent(x, y):
return (x.versions != y.versions
and not x.happens_before(y)
and not y.happens_before(x))
Entry j of V(e) counts the events of process j in e’s causal past (including e itself, when e is on process j). That gives the strong clock condition: a → b if and only if V(a) < V(b), where < means ≤ in every entry and strictly less in at least one, which is exactly happens_before. If a → b, everything a has seen, b has seen too, plus b itself. Conversely, if a is the k-th event of process i and V(b)[i] ≥ k, then b’s causal past contains a. So two events are concurrent exactly when their vectors are incomparable.
Worked example. Three processes exchange three messages: A sends m1 to B, B sends m2 to C, C sends m3 to A. Vectors are written [A, B, C].
| event | what happens | Lamport L | vector V |
|---|---|---|---|
| a1 | A, local | 1 | [1,0,0] |
| a2 | A sends m1 | 2 | [2,0,0] |
| b1 | B, local | 1 | [0,1,0] |
| b2 | B receives m1 | max(1, 2) + 1 = 3 | max([0,1,0], [2,0,0]) = [2,1,0], tick: [2,2,0] |
| b3 | B sends m2 | 4 | [2,3,0] |
| c1 | C, local | 1 | [0,0,1] |
| c2 | C receives m2 | max(1, 4) + 1 = 5 | [2,3,1], tick: [2,3,2] |
| c3 | C sends m3 | 6 | [2,3,3] |
| a3 | A receives m3 | max(2, 6) + 1 = 7 | [2,3,3], tick: [3,3,3] |
lamport = {p: LamportClock() for p in "ABC"}
vector = {p: VectorClock(p) for p in "ABC"}
L, V = {}, {}
def local(name, p):
L[name], V[name] = lamport[p].local(), vector[p].local()
def send(name, p):
local(name, p) # a send is a local event whose stamp travels
return L[name], V[name]
def receive(name, p, msg):
L[name], V[name] = lamport[p].receive(msg[0]), vector[p].receive(msg[1])
local("a1", "A"); m1 = send("a2", "A")
local("b1", "B"); receive("b2", "B", m1); m2 = send("b3", "B")
local("c1", "C"); receive("c2", "C", m2); m3 = send("c3", "C")
receive("a3", "A", m3)
assert L["b1"] < L["a2"] and concurrent(V["b1"], V["a2"])
assert L["c1"] < L["b3"] and concurrent(V["c1"], V["b3"])
assert V["a1"].happens_before(V["c2"]) # a1 → a2 → b2 → b3 → c2
assert [V["a3"].versions[p] for p in "ABC"] == [3, 3, 3]
c1 has Lamport time 1, tied for the smallest in the run, yet it is concurrent with every event on A and B before a3: nothing C did reached anyone until m3.
Cost. A vector timestamp takes O(n) space for n processes, and comparing or merging two takes O(n), worst-case. This is not a weakness of the encoding: Charron-Bost (1991) proved that characterizing causality with vectors compared entry by entry needs n entries in the worst case. That is why vector clocks are attached to replicated objects with a few writers (Dynamo keeps one per key and truncates it past a size threshold by dropping the oldest entry) and not to every event in a large cluster.
Hybrid logical clocks
A database that assigns a timestamp to every write would like three things at once:
- Causality: if a → b then ts(a) < ts(b), so a write that follows a read of another write sorts after it.
- Constant size: a timestamp on every MVCC version cannot grow with the cluster.
- Closeness to wall-clock time: “read the database as of 10:00:00”, TTLs and log correlation all need timestamps that mean something in seconds.
Physical clocks give 2 and 3 but break 1 under skew. Lamport clocks give 1 and 2 but drift arbitrarily far from real time, since a busy node drives everyone’s counter up and the counter has no units. Vector clocks give 1 but not 2 or 3. Hybrid logical clocks (HLC; Kulkarni, Demirbas, Madappa, Avva and Leone, 2014) give all three. A timestamp is a pair (l, c): l is the largest physical time the node has heard of, from its own clock or from any message, and c is a counter that orders events sharing the same l. Pairs compare lexicographically.
class HybridLogicalClock:
def __init__(self, physical_clock):
self.pt = physical_clock # function returning this node's wall clock
self.l = 0 # largest physical time seen so far
self.c = 0 # orders events that share the same l
def local(self): # a local event, or a send
old = self.l
self.l = max(old, self.pt())
self.c = self.c + 1 if self.l == old else 0
return (self.l, self.c)
send = local
def receive(self, msg):
lm, cm = msg
old = self.l
self.l = max(old, lm, self.pt())
if self.l == old == lm:
self.c = max(self.c, cm) + 1
elif self.l == old:
self.c += 1
elif self.l == lm:
self.c = cm + 1
else: # the local clock is ahead of everything
self.c = 0
return (self.l, self.c)
Three properties follow. Causality: each rule makes (l, c) strictly increase over the previous local value and, on a receive, over the message’s value, so a → b implies hlc(a) < hlc(b). Bounded drift: l is always at least the local physical time, and it is a physical reading taken somewhere in the event’s causal past, so it can be ahead of the local clock by at most ε, the maximum skew between any two clocks. Small counter: c resets to 0 whenever the local physical clock moves past l, so it only grows while a node is behind the largest time it has heard of (the paper proves a bound). Like a Lamport clock, an HLC cannot detect concurrency: hlc(a) < hlc(b) does not imply a → b.
Worked example. A’s clock reads 10 and B’s reads 7: B is 3 units behind. A writes key k and sends the write to B. B reads it and overwrites k.
| event | local wall clock | physical timestamp | HLC |
|---|---|---|---|
| A writes k = 1, sends it | 10 | 10 | (10, 0) |
| B receives the write | 7 | 7 | max(0, 10, 7) = 10 from the message: (10, 0 + 1) = (10, 1) |
| B writes k = 2 | 7 | 7 | l unchanged at 10: (10, 2) |
| B, later, local event | 11 | 11 | clock passed l: (11, 0) |
With physical timestamps, B’s write (7) sorts before A’s (10), so every replica running last-writer-wins keeps k = 1 and silently discards the write that causally came second. With HLC, (10, 2) > (10, 0) and B’s write wins. Once B’s clock passes 10, its timestamps are plain wall time again with c = 0.
wall = {"A": 10, "B": 7} # B's clock is 3 units behind A's
hlc_a = HybridLogicalClock(lambda: wall["A"])
hlc_b = HybridLogicalClock(lambda: wall["B"])
m = hlc_a.send() # A writes k = 1
assert m == (10, 0)
assert hlc_b.receive(m) == (10, 1)
w = hlc_b.local() # B overwrites k = 2
assert w == (10, 2) and w > m # physical time would say 7 < 10
wall["B"] = 11
assert hlc_b.local() == (11, 0) # back to tracking the wall clock
CockroachDB and YugabyteDB both timestamp transactions and MVCC versions with HLCs. CockroachDB’s default maximum clock offset is 500 ms; a node whose clock drifts too far from the rest of the cluster shuts itself down, because the bound on ε is what keeps HLC timestamps meaningful. Compare Spanner’s TrueTime (§31.1), which buys a small ε with GPS and atomic clocks and then waits it out on every commit. HLC accepts ordinary NTP-grade skew and pays for it elsewhere, for example by restarting a read that finds a value whose timestamp falls within its uncertainty window.
| clock | timestamp size | cost per event | a → b ⇒ ts(a) < ts(b) | detects concurrency | close to wall time |
|---|---|---|---|---|---|
| physical | O(1) | O(1) | no | no | yes |
| Lamport | O(1) | O(1) | yes | no | no |
| vector | O(n) | O(n) | yes, and the converse | yes | no |
| hybrid logical | O(1) | O(1) | yes | no | yes, within ε |
All costs are worst-case per event, for n processes.
27.9 Sequence CRDTs for Collaborative Editing
The CRDTs of §27.5 are counters, registers and sets, which have no order. Text does, and users edit it by position. Operations addressed by integer index do not commute. Two replicas hold “cat”. A types “s” at index 3, giving “cats”; concurrently, B types “h” at index 1, giving “chat”. A then applies B’s insert(1, “h”) and gets “chats”. B applies A’s insert(3, “s”) and gets “chast”. The index 3 meant “after the t” on A, but B’s earlier insert shifted the t. Operational transformation (OT) repairs this by rewriting each incoming index against the concurrent operations it missed, which is manageable with a central server ordering everything. A sequence CRDT removes the problem instead: every character gets a unique identifier that never changes, and the document order is defined on identifiers, not indices.
That needs three things. Identifiers must be unique without coordination: a (counter, replica_id) pair does it. They must be ordered between neighbours: a character inserted between x and y must land between x and y on every replica, and concurrent inserts at the same spot need a deterministic tie-break. And deletes must leave tombstones: a concurrent insert may name the deleted character as its neighbour, so the identifier has to stay resolvable after the character disappears from view.
Fractional positions and the interleaving anomaly
The direct approach gives every character a position in a dense ordered space and sorts by (position, replica_id). Logoot (Weiss, Urso and Molli, 2009) uses sequences of digits as positions, so there is always room between two of them; floats make a simpler (if finite) stand-in. Suppose A types “dog” and B types “cat” concurrently into an empty document, each character placed halfway between the previous one and the end:
def fractional_typing(word, replica, lo=0.0, hi=1.0):
out = []
for ch in word:
lo = (lo + hi) / 2 # halfway between the last char and the end
out.append(((lo, replica), ch))
return out
doc = sorted(fractional_typing("dog", "A") + fractional_typing("cat", "B"))
assert "".join(ch for _, ch in doc) == "dcoagt"
Both replicas converge, on garbage. Both users chose positions 0.5, 0.75 and 0.875, and the tie-break on replica ID alternates them. This is the interleaving anomaly: concurrently typed runs at the same place merge character by character. Kleppmann, Gomes, Mulligan and Beresford (2019) found it in Logoot and LSEQ. Convergence is a necessary property of a collaborative editor, not a sufficient one.
RGA: the Replicated Growable Array
RGA (Roh, Jeon, Kim and Lee, 2011) anchors each insert to a character instead of a number. An element is identified by a Lamport timestamp (counter, replica_id) from §27.8; the original paper used a custom timestamp type, and later presentations use Lamport timestamps. An insert operation is (id, ref, char), where ref is the id of the character immediately to the left at the moment of insertion (None for the start). A delete operation marks its target as a tombstone and keeps it in the list.
To apply an insert, find ref, then skip right past every element whose id is greater than the new id, and insert there:
class RGA:
def __init__(self, replica_id):
self.replica_id = replica_id
self.clock = 0 # Lamport counter: ids are (counter, replica_id)
self.elems = [] # [id, char, deleted], in document order
def _visible(self):
return [e for e in self.elems if not e[2]]
def _find(self, elem_id):
for i, e in enumerate(self.elems):
if e[0] == elem_id:
return i
raise KeyError(elem_id)
def text(self):
return "".join(e[1] for e in self._visible())
# Local edits, by visible position; each returns the op to broadcast.
def insert(self, pos, char):
ref = self._visible()[pos - 1][0] if pos > 0 else None
op = ("ins", (self.clock + 1, self.replica_id), ref, char)
self.apply(op)
return op
def delete(self, pos):
op = ("del", self._visible()[pos][0])
self.apply(op)
return op
# Remote and local ops both go through apply.
def apply(self, op):
if op[0] == "del":
self.elems[self._find(op[1])][2] = True # tombstone
return
_, elem_id, ref, char = op
if any(e[0] == elem_id for e in self.elems):
return # duplicate delivery
self.clock = max(self.clock, elem_id[0])
i = 0 if ref is None else self._find(ref) + 1
while i < len(self.elems) and self.elems[i][0] > elem_id:
i += 1 # skip newer inserts
self.elems.insert(i, [elem_id, char, False])
Why the skip rule converges. Picture the elements as a tree: each element’s parent is its ref, siblings are ordered by descending id, and the document is the pre-order traversal. Because an insert’s Lamport timestamp exceeds that of its ref, every element’s id is larger than all of its ancestors’. Starting just after ref, the list holds ref’s child subtrees in descending order. A child with a larger id than the new element is skipped along with its whole subtree, whose ids are larger still. The first element with a smaller id is either a smaller sibling or lies beyond ref’s subtree (the element there is a later sibling of ref or of one of its ancestors, so its id is smaller than that node’s, which is no larger than ref’s, which is smaller than the new element’s). The new element goes exactly there, which is its place in the pre-order traversal. The tree depends only on the set of operations, not on the order they arrived in, so any two replicas that have applied the same operations hold the same list. The only delivery requirement is that an insert arrives after the insert of its ref and a delete after the insert of its target, which causal delivery provides.
Worked trace. A types “ab”, giving ids (1,A) for a and (2,A) for b, and B receives both. Concurrently, A inserts “x” after a, with id (3,A), while B inserts “y” after a, with id (3,B), and then deletes b.
- On A, which holds
a x b: y’s ref is a, at index 0, so start at 1. x’s id (3,A) is less than (3,B): stop. Resulta y x b. - On B, which holds
a y b†(b† is the tombstone): x’s ref is a, start at 1. y’s id (3,B) is greater than (3,A): skip. b’s id (2,A) is less than (3,A): stop. Resulta y x b†. After applying B’s delete, A matches.
Both read “ayx”. The tombstone mattered: had B’s delete arrived first and physically removed b, an insert after b from a third replica would have had nothing to anchor to.
The test below gives three replicas the same starting text, lets them make 30 edits with no syncing at all (every edit is concurrent with the other replicas’ edits), and then applies the full set of operations in 100 different random causal orders to fresh replicas, as well as in log order to the three originals. Every one ends with the same text.
import random
def dependency(op):
return op[2] if op[0] == "ins" else op[1]
def random_causal_order(ops, rng):
"""A delivery order in which every op's ref or target arrives first."""
pending, present, order = list(ops), {None}, []
while pending:
op = rng.choice([o for o in pending if dependency(o) in present])
pending.remove(op)
order.append(op)
if op[0] == "ins":
present.add(op[1])
return order
rng = random.Random(27)
replicas = [RGA(r) for r in "ABC"]
ops = [replicas[0].insert(i, ch) for i, ch in enumerate("cat")]
for r in replicas[1:]:
for op in ops:
r.apply(op)
for _ in range(30): # concurrent edits, no syncing
r = rng.choice(replicas)
if r.text() and rng.random() < 0.3:
ops.append(r.delete(rng.randrange(len(r.text()))))
else:
ops.append(r.insert(rng.randint(0, len(r.text())), rng.choice("xyz")))
results = set()
for _ in range(100):
fresh = RGA("D")
for op in random_causal_order(ops, rng):
fresh.apply(op)
results.add(fresh.text())
for r in replicas: # own ops are skipped as duplicates
for op in ops:
r.apply(op)
results.add(r.text())
assert len(results) == 1
Interleaving in RGA. Text typed left to right stays together: every character after the first is anchored to its predecessor in the same run, so a concurrent run from another user can only go before or after the whole run. In the “dog” and “cat” scenario, RGA produces “catdog” on every replica. But a run typed by repeatedly inserting at the same position (moving the cursor back after each keystroke) anchors every character to the same ref, and those siblings are ordered only by timestamp: A inserting g, o, d at position 0 while B inserts t, a, c at position 0 merges to “cdaotg”. Kleppmann et al. (2019) called this the lesser interleaving anomaly; Fugue (Weidner and Kleppmann, 2023) is a later list CRDT designed specifically to minimize interleaving.
Cost. In this list version every operation is O(n), worst-case, where n counts tombstones too: finding ref, converting a visible position to an element, and the list insert are all linear scans. The skip loop itself only passes over concurrent inserts at the same spot. Production implementations keep elements in a balanced tree whose nodes store the number of visible characters below them (the same weight trick as the rope in §13.7), plus a hash map from id to element, for O(log n) position lookups. They also compress runs: Yjs stores consecutive characters typed by one client as a single item. Space is the real cost. Tombstones are never removed by the algorithm itself, so a document’s metadata grows with every character ever typed. A tombstone can only be discarded once every replica has seen the delete and no operation still in flight can refer to it, which requires knowing who all the replicas are. Yjs, for example, discards a deleted item’s content but keeps a small placeholder recording its length.
In practice. Yjs implements an adaptation of YATA (Nicolaescu et al., 2016), which anchors each insert to both its left and its right neighbour (each item records an origin and a right origin). Automerge documents its list type as an RGA sequence. Both use (client, counter) identifiers and tombstones as above.
Local versus replicated buffers. The gap buffer, rope and piece table of Chapter 13 address text by integer offset, which works because a single writer’s offsets only change through that writer’s own edits. A replicated buffer cannot, as “chast” shows; it must address by identifier. An editor built on a sequence CRDT usually keeps both: an ordinary local buffer for rendering and cursor movement, and the CRDT for merging. Local edits are translated from offset to identifier on the way out, and remote operations from identifier to offset on the way in, which is why the position lookup above has to be fast.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
27.1 ★★ Trace a Chord lookup. Take m = 6 (identifiers 0 to 63) and a ring with nodes at 1, 8, 14, 21, 32, 38, 42, 48, 51 and 56. Using the finger-table rule from §27.2 (entry i of node n is successor((n + 2^(i-1)) mod 2^m)), build the finger table of node 8, then trace a lookup for key 54 that starts at node 8. At each hop the current node forwards to the finger that most closely precedes the key, unless the key falls between the node and its successor.
Hint
Node 8’s fingers point at the successors of 9, 10, 12, 16, 24 and 40. To trace the second hop you will need part of node 42’s finger table too.
Solution
Finger table of node 8:
| i | 8 + 2^(i-1) | successor |
|---|---|---|
| 1 | 9 | 14 |
| 2 | 10 | 14 |
| 3 | 12 | 14 |
| 4 | 16 | 21 |
| 5 | 24 | 32 |
| 6 | 40 | 42 |
Lookup for 54:
- At node 8: its successor is 14 and 54 is not in (8, 14]. The finger closest to 54 without passing it is 42. Forward to 42.
- At node 42: its successor is 48, and 54 is not in (42, 48]. Node 42’s fingers are the successors of 43, 44, 46, 50, 58 and 10 (that is, 74 mod 64), giving 48, 48, 48, 51, 1, 14. The finger that most closely precedes 54 is 51. Forward to 51.
- At node 51: its successor is 56, and 54 is in (51, 56]. Node 56 owns key 54.
Path: 8 → 42 → 51 → 56. Each hop at least halves the remaining clockwise distance to the key (46, then 12, then 3), which is where the O(log N) hop bound comes from.
27.2 ★★ XOR distance and k-buckets. Use 4-bit Kademlia identifiers. Node x = 0110 knows the contacts 0111, 0100, 0101, 0011 and 1110. Compute d(x, y) for each contact and place each one in bucket i, where bucket i holds contacts at distance in [2^i, 2^(i+1)). Then prove that for any fixed x and any distance d there is exactly one identifier y with d(x, y) = d, and say why that matters for lookups.
Hint
Bucket i is the set of nodes that share exactly the first (3 − i) bits with x. For the proof, XOR both sides of x ⊕ y = d with x.
Solution
| contact | x ⊕ y | distance | bucket | shared prefix with 0110 |
|---|---|---|---|---|
| 0111 | 0001 | 1 | 0 | 3 bits |
| 0100 | 0010 | 2 | 1 | 2 bits |
| 0101 | 0011 | 3 | 1 | 2 bits |
| 0011 | 0101 | 5 | 2 | 1 bit |
| 1110 | 1000 | 8 | 3 | 0 bits |
Half the identifier space (everything starting with 1) lands in bucket 3, a quarter in bucket 2, and so on: the node knows a few contacts in each exponentially shrinking region, which is the same shape as a Chord finger table.
Uniqueness: if x ⊕ y = d then XOR both sides with x to get y = x ⊕ d, since x ⊕ x = 0. So y is determined by x and d. This property (unidirectionality) means that lookups for the same key converge along the same path regardless of which node starts them. Caching a value at nodes along that path therefore helps later lookups, because they pass through those same nodes.
27.3 ★ Consistent hashing versus mod-N. A ring runs from 0 to 99 and has nodes at 10, 35, 60 and 85. A key goes to the first node whose position is greater than the key, wrapping around past 99. (a) Assign the keys 5, 12, 33, 40, 59, 61, 90, 99. (b) A node is added at 50. Which keys move? (c) Compare with owner = key mod N going from N = 4 to N = 5: how many of the same eight keys change owner?
Solution
(a) 5 → 10, 12 → 35, 33 → 35, 40 → 60, 59 → 60, 61 → 85, 90 → 10 (wraps), 99 → 10 (wraps).
(b) The new node at 50 takes over the arc (35, 50), which previously belonged to 60. Only key 40 lies in that arc, so one key out of eight moves, and it moves to the new node. No key moves between two old nodes.
(c) Under mod-N:
| key | mod 4 | mod 5 | moved? |
|---|---|---|---|
| 5 | 1 | 0 | yes |
| 12 | 0 | 2 | yes |
| 33 | 1 | 3 | yes |
| 40 | 0 | 0 | no |
| 59 | 3 | 4 | yes |
| 61 | 1 | 1 | no |
| 90 | 2 | 0 | yes |
| 99 | 3 | 4 | yes |
Six of eight move. In general a key keeps its owner only when k mod 4 = k mod 5, which happens for k mod 20 in {0, 1, 2, 3}: one key in five. Mod-N moves about 80% of the data when growing from 4 to 5 nodes; consistent hashing moves about 1/5 (the new node’s fair share) in expectation.
27.4 ★★ Find the bug in a happens-before check. An earlier version of VersionVector.happens_before in §27.7 looped only over the keys of other:
def happens_before(self, other):
return all(
self.versions.get(k, 0) <= v
for k, v in other.versions.items()
) and any(
self.versions.get(k, 0) < v
for k, v in other.versions.items()
)
Find two version vectors for which this returns the wrong answer, and explain what the consequence would be in a Dynamo-style store.
Hint
What happens to an entry that appears in self but not in other?
Solution
Take self = {A: 1, B: 1} and other = {A: 2}. The loop only checks key A: 1 ≤ 2 and 1 < 2, so it returns True. But self has seen an update from B that other has not (B: 1 versus an implicit B: 0), so neither vector dominates: the two versions are concurrent.
The consequence: the store would decide that other supersedes self and silently discard the version containing B’s write. That is exactly the lost update that version vectors exist to prevent. The fix, used in the chapter’s code, compares over the union of both key sets, treating a missing key as 0.
27.5 ★ Quorum arithmetic. For N = 5 replicas, which of these (R, W) pairs are strict quorums: (1, 5), (2, 3), (3, 3), (2, 4), (3, 2)? For each strict one, how many replica failures can reads tolerate, and how many can writes tolerate? How many failures does the majority quorum tolerate for N = 4, 5 and 6?
Solution
A strict quorum needs R + W > N, so every read set intersects every write set.
| (R, W) | R + W | strict? | read failures tolerated (N − R) | write failures tolerated (N − W) |
|---|---|---|---|---|
| (1, 5) | 6 | yes | 4 | 0 |
| (2, 3) | 5 | no | ||
| (3, 3) | 6 | yes | 2 | 2 |
| (2, 4) | 6 | yes | 3 | 1 |
| (3, 2) | 5 | no |
(1, 5) gives the fastest reads but any single failure blocks all writes. (2, 3) and (3, 2) can return stale data: a read of 2 replicas can miss all 3 that took the write.
The majority quorum is ⌊N/2⌋ + 1, so it tolerates N − (⌊N/2⌋ + 1) = ⌊(N−1)/2⌋ failures: 1 for N = 4, 2 for N = 5, 2 for N = 6. An even cluster size buys no extra fault tolerance over the odd size below it, which is why consensus groups are almost always 3, 5 or 7.
27.6 ★★ Why G-Counter merges with max. Three replicas start empty. A increments twice, B increments once, C increments once. Then these merges happen in order: A merges B; C merges A; A merges C; B merges A; B merges A again. Give every replica’s state and value at the end. Then suppose merge added the counts instead of taking the max. Which step gives a wrong answer, and what property of the merge has been broken?
Solution
Before any merge: A = {A: 2}, B = {B: 1}, C = {C: 1}.
| step | result | value |
|---|---|---|
| A merges B | A = {A: 2, B: 1} | 3 |
| C merges A | C = {A: 2, B: 1, C: 1} | 4 |
| A merges C | A = {A: 2, B: 1, C: 1} | 4 |
| B merges A | B = {A: 2, B: 1, C: 1} | 4 |
| B merges A again | unchanged | 4 |
All three converge to 4, the true number of increments.
With addition, the first two merges happen to give the right answer, because the states being combined share no entries. The third step breaks: when A merges C, A adds C’s A: 2 to its own A: 2 and C’s B: 1 to its own B: 1, ending at {A: 4, B: 2, C: 1} with value 7, although only 4 increments happened. Every repeated exchange inflates the count further. The broken property is idempotence: merging the same state twice must change nothing. Gossip protocols deliver the same state many times, so a state-based CRDT’s merge must be idempotent as well as commutative and associative. Each entry only ever grows and is written by one node, so the max of two copies is always the newer one.
27.7 ★★★ A counter that can go down. A G-Counter cannot decrement. (a) Show that keeping one signed entry per node and merging with max does not work, by giving a sequence that loses an update. (b) Implement a PN-Counter from two G-Counters and argue that it converges. Your implementation should satisfy:
a, b = PNCounter(), PNCounter()
a.increment("A"); a.increment("A"); b.decrement("B")
a.merge(b); b.merge(a)
assert a.value() == b.value() == 1
Hint
Max-merge only works on values that never decrease. Find a way to represent decrements as something that only grows.
Solution
(a) Replica A increments: its entry is A: 1. B merges from A and now holds A: 1. A decrements: A: 0. B merges from A again: max(1, 0) = 1. The decrement is gone, and no amount of further gossip will bring it back, because max will always prefer 1. Max-merge is only correct when each entry is monotonically non-decreasing.
(b) Count increments and decrements separately, each in its own G-Counter, so both only grow:
class GCounter:
def __init__(self):
self.state = {}
def increment(self, node_id):
self.state[node_id] = self.state.get(node_id, 0) + 1
def merge(self, other):
for node_id, count in other.state.items():
self.state[node_id] = max(self.state.get(node_id, 0), count)
def value(self):
return sum(self.state.values())
class PNCounter:
def __init__(self):
self.p = GCounter() # increments
self.n = GCounter() # decrements
def increment(self, node_id):
self.p.increment(node_id)
def decrement(self, node_id):
self.n.increment(node_id)
def merge(self, other):
self.p.merge(other.p)
self.n.merge(other.n)
def value(self):
return self.p.value() - self.n.value()
a, b = PNCounter(), PNCounter()
a.increment("A"); a.increment("A"); b.decrement("B")
a.merge(b); b.merge(a)
assert a.value() == b.value() == 1
Convergence: each of P and N is a G-Counter, whose merge (entry-wise max) is commutative, associative and idempotent. Merging a pair of them component-wise keeps all three properties. So once every replica has, directly or through others, merged every other replica’s state, all replicas hold the same P and the same N, and therefore the same value P − N. The value can go below zero; if your application needs a floor (stock that cannot go negative), a PN-Counter cannot enforce it, because enforcing a global bound requires coordination.
27.8 ★★ Lamport and vector timestamps by hand. Three processes run these events, each process in the order listed. A: a1 sends m1 to C, a2 is local, a3 receives m2. B: b1 is local, b2 sends m2 to A, b3 receives m3. C: c1 receives m1, c2 sends m3 to B. (a) Give every event’s Lamport time and vector clock [A, B, C] using the rules of §27.8. (b) Decide whether a1 → b3, whether a2 → b3, and whether b1 → c2. (c) Find every pair of events x, y with L(x) < L(y) that are nevertheless concurrent.
Solution
(a)
| event | L | V |
|---|---|---|
| a1 (send m1) | 1 | [1,0,0] |
| a2 | 2 | [2,0,0] |
| b1 | 1 | [0,1,0] |
| b2 (send m2) | 2 | [0,2,0] |
| c1 (receive m1) | max(0, 1) + 1 = 2 | [1,0,1] |
| c2 (send m3) | 3 | [1,0,2] |
| b3 (receive m3) | max(2, 3) + 1 = 4 | max([0,2,0], [1,0,2]) = [1,2,2], tick: [1,3,2] |
| a3 (receive m2) | max(2, 2) + 1 = 3 | max([2,0,0], [0,2,0]) = [2,2,0], tick: [3,2,0] |
(b) a1 → b3: yes, [1,0,0] ≤ [1,3,2] in every entry, through a1 → c1 → c2 → b3. a2 → b3: no. [2,0,0] has A = 2 > 1, and [1,3,2] has larger B and C entries, so they are concurrent: m1 left A before a2, so a2 never reached C or B. b1 → c2: no, [0,1,0] and [1,0,2] are incomparable; B’s events only reach A.
(c) Comparing the vectors of all pairs, the concurrent pairs with unequal Lamport times are (a1, b2), (b1, a2), (b1, c1), (b1, c2), (a2, c2), (a2, b3), (b2, c2), (c1, a3) and (a3, b3), each listed with the smaller Lamport time first. For example L(a2) = 2 < L(b3) = 4 although a2 ∥ b3, and L(c1) = 2 < L(a3) = 3 although c1 ∥ a3. Lamport order agrees with causality where causality exists and is arbitrary everywhere else.
27.9 ★★ A hybrid clock with a fast neighbour. A’s wall clock reads 100, B’s reads 41 and C’s reads 47. A sends a message to B; B receives it, then sends a message (at wall time 42) to C, which receives it. (a) Give the HLC timestamp of each of the four events. (b) Later B’s wall clock reaches 101 and B performs a local event. What is its timestamp? (c) The bounded-drift property says l is never more than the maximum clock skew ahead of the local clock. Check it here, and explain what goes wrong if A’s clock is not 59 units fast but a full day fast because of a bad sync.
Hint
On each receive, l becomes the largest of the old l, the message’s l, and the local physical time. Which of the three wins on B and on C?
Solution
(a) A’s send: l = max(0, 100) = 100, a new l, so (100, 0). B’s receive: l = max(0, 100, 41) = 100, equal to the message’s l only, so c = 0 + 1: (100, 1). B’s send at wall time 42: l stays 100, so c increments: (100, 2). C’s receive at 47: l = max(0, 100, 47) = 100 from the message, c = 2 + 1: (100, 3). Every timestamp increases along the causal chain even though B’s and C’s clocks are far behind A’s.
(b) At wall time 101, l = max(100, 101) = 101, a new value, so c resets: (101, 0).
(c) The largest skew is 100 − 41 = 59 (between A and B). B’s l − pt is 100 − 41 = 59 and then 100 − 42 = 58; C’s is 100 − 47 = 53. All are within 59. If A’s clock were a day fast, every node that heard from A, directly or indirectly, would carry an l a day in the future, and its timestamps would stay pinned at that l with a growing counter until its own clock caught up a day later. Causality would still hold, but “as of time t” reads, TTLs and anything comparing timestamps to real time would be wrong for a day, and nothing would bring l back down. This is why production systems refuse to run with an unbounded ε: CockroachDB shuts down a node whose clock is too far from the rest of the cluster rather than let its timestamps spread.
27.10 ★★ Why RGA keeps tombstones. Replicas A and B both hold “abc”, with ids (1,A), (2,A), (3,A). Concurrently, A deletes b and B inserts “x” right after b. (a) Give B’s insert operation and the converged text when both replicas apply both operations using the RGA class of §27.9. (b) Suppose apply removed deleted elements from the list instead of marking them. What happens on A when B’s insert arrives, and why can no local rule fix it? (c) When could a replica safely discard the tombstone for b?
Solution
(a) B’s clock is 3 after applying A’s three inserts, so the operation is ("ins", (4, "B"), (2, "A"), "x"). On A, b is a tombstone at index 1, so the scan starts at index 2; c’s id (3,A) is less than (4,B), so x goes before c. Both replicas hold a b† x c and read “axc”.
(b) A’s _find((2, "A")) fails: the element x is anchored to no longer exists, so A has no way to know where x belongs. Any local fallback (drop x, or put it at the end, or at the start) either loses B’s insert or puts it somewhere B did not, and replicas that received the insert before the delete would place it correctly, so the replicas diverge. The anchor carries the position information; deleting it deletes the information.
(c) Only when no operation that could still arrive refers to (2,A): every replica must have seen the delete, and every insert anchored to b that was issued before that point must have been delivered everywhere. Equivalently, the delete must be causally stable, which requires knowing the full set of replicas and hearing from all of them. In a peer-to-peer editor where a replica can go offline for weeks, that may never be known, which is why tombstones accumulate and why Yjs keeps a small placeholder for deleted items even when it discards their content.
Where this connects
- Chapter 19: Emerging and Specialized Structures. CRDTs in the broader context of emerging structures
- Chapter 17: Persistent Data Structures. The persistence ideas that underpin versioned replicas
- Chapter 13: String Data Structures. The single-writer text buffers that a sequence CRDT replicates
- Chapter 31: Real-World Case Studies. Dynamo’s vector clocks and Merkle trees, and Spanner’s TrueTime as the hardware alternative to hybrid logical clocks
Chapter 28: Network Topology and Routing Data Structures
28.1 Graph Representations for Networks
Network topology is fundamentally a graph problem. The choice of graph representation determines routing efficiency, memory usage, and update complexity.
Adjacency Matrix vs Adjacency List
Adjacency matrix (O(V²) space):
Router | A | B | C | D |
-------|---|---|---|---|
A | 0 | 1 | 1 | 0 |
B | 1 | 0 | 0 | 1 |
C | 1 | 0 | 0 | 1 |
D | 0 | 1 | 1 | 0 |
- O(1) edge existence check
- O(V²) space even for sparse graphs
- Good for dense networks
Adjacency list (O(V + E) space):
A: B → 10, C → 5
B: A → 10, D → 3
C: A → 5, D → 7
D: B → 3, C → 7
- O(degree) neighbor enumeration
- Space proportional to actual edges
- Standard for network routing
Compressed Representations for Large Networks
CSR (Compressed Sparse Row): Store edges in three arrays:
offsets: Starting position for each vertex’s edgesedges: Destination vertex IDsweights: Edge weights (optional)
Routing tables can use trie-like compression for hierarchical networks:
Hierarchical trie for routing:
[root]
/ | \
[A] [B] [C]
/ \ / \
[A1][A2] [C1][C2]
28.2 Routing Table Structures
Routing tables map network prefixes to next hops. The data structure must support fast longest prefix match (LPM), the core operation of IP forwarding.
Longest-Prefix Match
A route is a prefix and a next hop: 10.20.0.0/16 → C means “any address whose first 16 bits are those of 10.20.0.0 goes to neighbor C”. Prefixes nest, so one address usually matches several routes, and the rule is that the most specific one (the longest prefix) wins. Take this table:
| prefix | next hop | role |
|---|---|---|
| 0.0.0.0/0 | A | default route: matches every address |
| 10.0.0.0/8 | B | a large block |
| 10.20.0.0/16 | C | one site inside it |
| 10.20.128.0/17 | D | the upper half of that site, routed differently |
| 10.20.200.0/24 | E | one subnet inside the /17 |
| 192.168.0.0/16 | F | an unrelated block |
| address | routes that match | longest | next hop |
|---|---|---|---|
| 10.20.200.7 | /0, /8, /16, /17, /24 | 10.20.200.0/24 | E |
| 10.20.201.7 | /0, /8, /16, /17 | 10.20.128.0/17 | D |
| 10.20.5.5 | /0, /8, /16 | 10.20.0.0/16 | C |
| 10.99.1.1 | /0, /8 | 10.0.0.0/8 | B |
| 192.168.1.1 | /0, 192.168.0.0/16 | 192.168.0.0/16 | F |
| 8.8.8.8 | /0 | 0.0.0.0/0 | A |
10.20.5.5 misses the /17 because its third octet, 5 = 00000101, has a 0 in the bit the /17 fixes to 1. “Longest” is what makes the table composable: the /8 can be announced once for a whole block while a more specific route carves out an exception, without either route knowing about the other. A first-match scan in the order listed would send every one of these addresses to the default route A.
A binary trie does LPM directly. A route of length l is stored at the node reached by following its first l bits from the root, so the root holds the /0 and a node at depth d holds the route (if any) whose prefix is the d-bit string on its path. A lookup follows the address bit by bit and remembers the last route it passed; when the path runs out, the remembered route is the longest match, because every route that matches the address lies on that path and deeper nodes are longer prefixes.
import ipaddress
import random
class TrieNode:
def __init__(self):
self.children = [None, None]
self.next_hop = None # set if a prefix ends here
class RoutingTrie:
def __init__(self):
self.root = TrieNode()
def insert(self, prefix, next_hop):
net = ipaddress.IPv4Network(prefix)
value = int(net.network_address)
node = self.root
for i in range(net.prefixlen):
bit = (value >> (31 - i)) & 1
if node.children[bit] is None:
node.children[bit] = TrieNode()
node = node.children[bit]
node.next_hop = next_hop
def lookup(self, addr):
value = int(ipaddress.IPv4Address(addr))
node, best = self.root, self.root.next_hop
for i in range(32):
node = node.children[(value >> (31 - i)) & 1]
if node is None:
break
if node.next_hop is not None:
best = node.next_hop # longest match so far
return best
def lpm_scan(routes, addr):
"""Reference answer: test every route and keep the longest that matches."""
a = ipaddress.IPv4Address(addr)
best, best_len = None, -1
for prefix, hop in routes:
net = ipaddress.IPv4Network(prefix)
if a in net and net.prefixlen > best_len:
best, best_len = hop, net.prefixlen
return best
table = [("0.0.0.0/0", "A"), ("10.0.0.0/8", "B"), ("10.20.0.0/16", "C"),
("10.20.128.0/17", "D"), ("10.20.200.0/24", "E"), ("192.168.0.0/16", "F")]
t = RoutingTrie()
for prefix, hop in table:
t.insert(prefix, hop)
for addr, want in [("10.20.200.7", "E"), ("10.20.201.7", "D"), ("10.20.5.5", "C"),
("10.99.1.1", "B"), ("192.168.1.1", "F"), ("8.8.8.8", "A")]:
assert t.lookup(addr) == lpm_scan(table, addr) == want
def random_route(rng):
net = ipaddress.IPv4Network((rng.getrandbits(32), rng.randint(0, 32)), strict=False)
return str(net)
rng = random.Random(28)
for _ in range(200):
routes = list({random_route(rng): hop for hop in range(rng.randint(1, 60))}.items())
trie = RoutingTrie()
for prefix, hop in routes:
trie.insert(prefix, hop)
for _ in range(100):
if rng.random() < 0.5: # uniform addresses rarely hit long prefixes,
addr = ipaddress.IPv4Address(rng.getrandbits(32))
else: # so half are drawn from inside a route
net = ipaddress.IPv4Network(rng.choice(routes)[0])
addr = net.network_address + rng.randrange(net.num_addresses)
assert trie.lookup(str(addr)) == lpm_scan(routes, str(addr))
Trace 10.20.201.7: the root gives A, depth 8 gives B, depth 16 gives C and depth 17 gives D. The walk then continues down the path the /24 created, because 201 = 11001001 and 200 = 11001000 agree on their first seven bits, and at depth 23 there is no child for the final 1. Twenty-three nodes visited below the root, answer D.
Cost. Insert and lookup take O(W) time in the worst case, W = 32 for IPv4 and 128 for IPv6, independent of the number of routes N. The trie does not allocate the 2^32 possible addresses: it holds at most 1 + N·W nodes, and the six routes above take 41. Memory is not the problem; speed is. Each step is a dependent memory read, likely a cache miss, and a 100 Gb/s port receiving minimum-size Ethernet frames (64 bytes plus 20 bytes of preamble and inter-frame gap) delivers about 148.8 million packets per second, 6.7 ns per packet. Thirty-two pointer chases do not fit in that. The structures below exist to cut the number of reads: path compression removes nodes that do not branch, and multibit tries (§28.3) read several bits per step.
Radix Tree (Patricia Tree)
Collapse unary nodes (nodes with only one child) to reduce depth:
Standard trie path: 0→1→1→1→1
Radix tree: [01111] - single node representing this path
Example: 192.168.0.0/16, 192.168.1.0/24
[192.168] ← stores the /16 route
|
[.1] ← stores the /24 route (the /16 contains it)
BSD-derived kernels use this structure (Sklower’s radix tree) for their routing tables. Every node either holds a prefix or branches, so N prefixes need fewer than 2N nodes, against up to N·W for the plain binary trie. The depth can still reach W, so path compression helps memory more than worst-case lookup time.
LC-Trie (Level Compressed Trie)
Idea: Path-compress unary chains as a radix tree does, and replace each dense, nearly complete subtree of height k with a single node holding an array of 2^k children.
Level 0-7: Compressed into single node (2^8 children)
Level 8-15: Second level compression
...
Used in the Linux kernel’s IPv4 forwarding table (fib_trie). Few levels means few memory accesses per lookup, with modest memory.
28.3 Multibit Tries and Router Lookups
A binary trie spends one memory read per address bit. A multibit trie reads s bits at a time, the stride: each node is an array of 2^s slots indexed directly by the next s bits, so an IPv4 lookup with strides 8-8-8-8 takes at most four reads, and with 16-8-8 at most three. Each slot can hold a next hop and a pointer to a child node.
Controlled Prefix Expansion
The difficulty is prefixes whose length does not fall on a level boundary. With stride 8, the trie can only store prefixes of length 8, 16, 24 and 32 directly; a /17 ends one bit into the third level. Controlled prefix expansion (Srinivasan and Varghese, 1999) rewrites each prefix as the set of longer prefixes, of the next allowed length, that together cover exactly the same addresses. A prefix of length l that ends inside a level covering bits up to b becomes 2^(b−l) slots in that level’s node. Two rules make it correct:
- Expansion. 10.20.128.0/17 fixes the top bit of the third octet to 1, so in the level-3 node under 10.20 it fills the 2^(24−17) = 128 slots 128 to 255.
- Capture. When expansions of two different prefixes land on the same slot, the longer original prefix wins. 10.20.200.0/24 lands exactly on slot 200, which the /17 also covers, and since 24 > 17 the slot holds E. The slot therefore stores the original length beside the next hop, which also makes the result independent of insertion order.
The figure shows both rules on a toy table of bit strings with 4-bit addresses. For the six-route table of §28.2 with strides 8-8-8-8, the /0 expands into all 256 slots of the root, the /8 sits in root slot 10, the two /16s are aligned and sit in one level-2 slot each (20 under 10, 168 under 192), and the level-3 node under 10.20 holds D in slots 128 to 255 except slot 200, which holds E. Looking up 10.20.201.7 reads root slot 10 (B, follow the child), level-2 slot 20 (C, follow the child) and level-3 slot 201 (D, no child): three reads, against 23 nodes in the binary trie. The price is memory: four nodes of 256 slots, 1,024 slots for six routes, where the binary trie needed 41 nodes of two pointers.
class MultibitTrie:
"""Fixed-stride trie with controlled prefix expansion.
A node is a list of 2**stride slots; a slot is [next_hop, length, child],
where length is the original prefix length that set next_hop.
"""
def __init__(self, strides=(8, 8, 8, 8)):
assert sum(strides) == 32
self.strides = strides
self.root = self._node(0)
def _node(self, level):
return [[None, -1, None] for _ in range(1 << self.strides[level])]
def insert(self, prefix, next_hop):
net = ipaddress.IPv4Network(prefix)
value, plen = int(net.network_address), net.prefixlen
node, start = self.root, 0
for level, stride in enumerate(self.strides):
end = start + stride
index = (value >> (32 - end)) & ((1 << stride) - 1)
if plen <= end: # the prefix ends inside this level: expand it
first = index >> (end - plen) << (end - plen)
for slot in node[first:first + (1 << (end - plen))]:
if slot[1] <= plen: # capture: the longer original prefix wins
slot[0], slot[1] = next_hop, plen
return
if node[index][2] is None:
node[index][2] = self._node(level + 1)
node, start = node[index][2], end
def lookup(self, addr):
value = int(ipaddress.IPv4Address(addr))
node, start, best = self.root, 0, None
for stride in self.strides: # one memory read per level
start += stride
hop, _, child = node[(value >> (32 - start)) & ((1 << stride) - 1)]
if hop is not None:
best = hop
if child is None:
break
node = child
return best
m = MultibitTrie((8, 8, 8, 8))
for prefix, hop in table:
m.insert(prefix, hop)
level3 = m.root[10][2][20][2] # the node under 10.20
assert [level3[i][:2] for i in (127, 128, 200, 201)] == \
[[None, -1], ["D", 17], ["E", 24], ["D", 17]]
for strides in [(8, 8, 8, 8), (16, 8, 8), (4,) * 8, (1,) * 32]:
for _ in range(30):
routes = list({random_route(rng): hop for hop in range(rng.randint(1, 50))}.items())
rng.shuffle(routes) # insertion order must not matter
mt = MultibitTrie(strides)
for prefix, hop in routes:
mt.insert(prefix, hop)
for _ in range(50):
net = ipaddress.IPv4Network(rng.choice(routes)[0])
addr = str(net.network_address + rng.randrange(net.num_addresses))
assert mt.lookup(addr) == lpm_scan(routes, addr)
Like the binary trie, the lookup remembers the best next hop seen on the way down, so an empty slot (slot 5 of the level-3 node for 10.20.5.5) falls back to C from level 2.
Cost. A lookup takes at most k reads for k levels, worst case. Inserting a prefix walks at most k levels and writes up to 2^s slots of one node, so a short prefix in a wide level is expensive: the /0 above writes 256 slots, and in a 16-8-8 trie it would write 65,536. Deletion is harder than insertion, because the slots a deleted prefix captured must revert to the next-longest prefix covering them, and the trie does not record what that was. Implementations keep the original prefixes in a separate table to answer that question.
Choosing the Strides
Bigger strides mean fewer levels and more memory, but how much more depends on the table. A node starting at bit s exists for each distinct s-bit string that begins some route longer than s, so the number of nodes at each possible start position can be counted once from the routes, and the slots of any stride choice are the sum of nodes × 2^stride over its levels. Srinivasan and Varghese observed that the cheapest strides for a given number of levels then follow from a dynamic program over the start positions, O(k·W²) time for k levels:
from functools import lru_cache
def level_nodes(routes):
"""nodes[s]: trie nodes starting at bit s, one per distinct s-bit string
that begins a route longer than s; nodes[0] = 1, the root."""
keys = [(int(n.network_address), n.prefixlen)
for n in (ipaddress.IPv4Network(p) for p, _ in routes)]
return [1] + [len({v >> (32 - s) for v, plen in keys if plen > s})
for s in range(1, 32)]
def expansion_cost(nodes, strides):
"""Slots a fixed-stride trie allocates: sum of nodes[start] * 2**stride."""
total, start = 0, 0
for stride in strides:
total += nodes[start] << stride
start += stride
return total
def best_strides(nodes, levels):
"""Cheapest (slots, strides) using at most `levels` levels."""
@lru_cache(maxsize=None)
def cost(start, left):
if start == 32:
return 0, ()
if left == 0:
return float("inf"), ()
return min((c + (nodes[start] << (end - start)), (end - start,) + rest)
for end in range(start + 1, 33)
for c, rest in [cost(end, left - 1)])
return cost(0, levels)
assert expansion_cost(level_nodes(table), (8, 8, 8, 8)) == 1024 # the four nodes above
def synthetic_table(seed=2024, n=50_000):
"""BGP-like length mix (60% /24s), clustered in 3,000 random /16 blocks."""
r = random.Random(seed)
mix = {8: 0.1, 12: 0.2, 14: 0.4, 15: 0.4, 16: 2.5, 17: 1, 18: 1.5, 19: 3,
20: 4, 21: 5, 22: 11, 23: 9, 24: 60, 25: 0.4, 26: 0.4, 27: 0.3,
28: 0.3, 29: 0.3, 30: 0.2, 32: 0.1}
blocks = [r.randrange(1 << 8, 224 << 8) for _ in range(3000)]
routes = {}
while len(routes) < n:
plen = r.choices(list(mix), list(mix.values()))[0]
value = (r.choice(blocks) << 16) | r.getrandbits(16)
routes[str(ipaddress.IPv4Network((value, plen), strict=False))] = len(routes)
return list(routes.items())
nodes = level_nodes(synthetic_table())
for strides in [(1,) * 32, (4,) * 8, (8, 8, 8, 8), (16, 8, 8), (24, 8), (16, 16)]:
print(strides, expansion_cost(nodes, strides))
print(best_strides(nodes, 3), best_strides(nodes, 4))
On this synthetic 50,000-route table (real tables differ, but the shape of the trade-off is typical):
| strides | worst-case reads | slots |
|---|---|---|
| 1 × 32 (binary trie) | 32 | 366,042 |
| 4 × 8 | 8 | 562,832 |
| 8-8-8-8 | 4 | 1,076,736 |
| 16-8-8 | 3 | 1,084,928 |
| 24-8 | 2 | 17,048,320 |
| 16-16 | 2 | 191,627,264 |
The binary trie is the smallest and the slowest. Going from 32 reads to 4 costs about three times the memory, and going from 4 to 3 costs almost nothing here, because the 65,536-slot root of 16-8-8 replaces the first two levels of 8-8-8-8, which already used 224 nodes and 57,344 slots. Going to 2 levels costs another factor of 16, and the wrong two levels are worse again: 16-16 needs 11 times the memory of 24-8, because it allocates a 65,536-slot node for each of the 2,923 /16 blocks that contain a longer route. The program confirms that 16-8-8 is the cheapest three-level choice and finds 16-6-3-7 (627,928 slots) for four levels. Letting each subtree pick its own strides, which the same paper also optimizes by dynamic programming, does better still.
DIR-24-8: Usually One Read
Gupta, Lin and McKeown (INFOCOM 1998) took the 24-8 row of that table seriously. Their observation was that on a backbone table of the time (MAE-EAST, January 1998), 99.93% of prefixes were 24 bits or shorter, and that 2^24 entries of DRAM was cheap. Their DIR-24-8-BASIC scheme is a two-level multibit trie with strides 24 and 8, laid out as two flat arrays:
- TBL24 has 2^24 entries of 2 bytes, 32 MB, indexed by the top 24 bits of the address. An entry whose first bit is 0 holds a next hop in its other 15 bits. An entry whose first bit is 1 holds a 15-bit index into the second table.
- TBLlong is made of 256-entry blocks of 1-byte next hops, one block for each /24 that contains a route longer than /24, indexed by the last 8 bits of the address.
A lookup reads TBL24; only if the flag is set does it make a second read. Instead of remembering the best match on the way down, the scheme pushes it down: when a /24’s block is allocated, all 256 entries are first filled with whatever the /24 entry held, so each entry is a complete answer by itself. The paper’s example uses 10.54.0.0/16, 10.54.34.0/24 and 10.54.34.192/26:
from array import array
EXT = 1 << 31 # flag bit: the low bits index a tbl8 group, not a next hop
def build_dir_24_8(routes):
"""Static build. routes: (prefix, hop), hop an int >= 1; 0 means no route."""
tbl24 = array("I", [0]) * (1 << 24)
tbl8 = array("I")
nets = sorted(((ipaddress.IPv4Network(p), h) for p, h in routes),
key=lambda r: r[0].prefixlen) # shorter first; longer overwrite
for net, hop in nets:
lo, n = int(net.network_address), net.num_addresses
if net.prefixlen <= 24:
tbl24[lo >> 8:(lo + n) >> 8] = array("I", [hop]) * (n >> 8)
continue
entry = tbl24[lo >> 8]
if not entry & EXT: # first long route under this /24: allocate a group
group = len(tbl8) >> 8
tbl8.extend(array("I", [entry]) * 256) # push the /24's answer down
entry = tbl24[lo >> 8] = EXT | group
base = ((entry & ~EXT) << 8) | (lo & 0xFF)
tbl8[base:base + n] = array("I", [hop]) * n
return tbl24, tbl8
def lookup_dir_24_8(tbl24, tbl8, addr):
a = int(ipaddress.IPv4Address(addr))
entry = tbl24[a >> 8] # read 1
if entry & EXT:
entry = tbl8[((entry & ~EXT) << 8) | (a & 0xFF)] # read 2, rarely
return entry
tbl24, tbl8 = build_dir_24_8([("10.54.0.0/16", 1), ("10.54.34.0/24", 2),
("10.54.34.192/26", 3)])
assert lookup_dir_24_8(tbl24, tbl8, "10.54.22.147") == 1 # one read
assert lookup_dir_24_8(tbl24, tbl8, "10.54.34.14") == 2 # two reads
assert lookup_dir_24_8(tbl24, tbl8, "10.54.34.194") == 3 # two reads
assert len(tbl8) == 256 # one group, for 10.54.34
The /16 fills the 256 TBL24 entries 10.54.0 to 10.54.255. The /24 overwrites entry 10.54.34, and the /26 then turns that entry into a pointer to group 0, whose entries 0 to 191 hold the /24’s next hop and 192 to 255 the /26’s. (The code uses 32-bit entries with the flag in the top bit, as DPDK does, rather than the paper’s 16.)
Lookup is at most two reads, worst case, and one read for any address whose /24 has no longer route, which is nearly all of them: most networks do not accept routes longer than /24 from the global table. Because the reads are to fixed locations with no pointer chasing beyond the second, a hardware pipeline can complete one lookup per memory access; the paper estimated 20 million lookups per second with the 50 ns DRAM of the day. The costs are on the other side. TBL24 is 32 MB however small the table is. The 15-bit pointer limits TBLlong to 32,768 blocks; the paper suggested 1 MB of it, 4,096 blocks. And updates are slow: adding a /8 rewrites 65,536 TBL24 entries, a default route all 16.7 million, and a later insertion must not overwrite entries that a longer prefix already set. Exercise 28.7 works through what that requires.
In production. DPDK’s rte_lpm library, used by software routers built on it, is DIR-24-8: a tbl24 of 2^24 four-byte entries (64 MB) and 256-entry tbl8 groups whose number is fixed when the table is created. Each entry packs a 24-bit next hop (or group index), a valid bit, a valid_group bit that marks an extended entry, and a 6-bit depth, the length of the prefix that wrote it; the depth is what lets insertion and deletion run incrementally. Poptrie (Asai and Ohara, SIGCOMM 2015) goes the other way and makes the table small enough to stay in CPU cache: a directly indexed first level of 16 or 18 bits, then 64-way nodes (stride 6) that store only their non-empty children contiguously, with a 64-bit bitmap per node; the index of a child is the population count (popcnt) of the bitmap bits below it. Both trade update cost for a lookup with few, predictable reads, which is the right trade for a forwarding table that sees millions of lookups per update.
28.4 ECMP and Maglev Hashing
The lookup of §28.3 often returns not one next hop but a group of them. In a data-center fabric built as a Clos network, a leaf switch has the same route to every remote rack through each of its spine switches, all at equal cost. Equal-cost multipath (ECMP) forwarding spreads traffic across the group, and the data structure question becomes: which packet goes to which member?
Per-Flow Hashing
Sending successive packets to successive members (per-packet spraying) balances perfectly and breaks TCP. The paths have different queueing delays, so the packets of one connection arrive out of order; the receiver acknowledges each out-of-order segment with a duplicate ACK, and the sender treats three duplicate ACKs as a loss, retransmits and halves its congestion window. So routers hash per flow: the flow’s 5-tuple (source and destination address, source and destination port, protocol) is hashed, and every packet of the flow takes member group[hash(5-tuple) mod k]. One flow stays on one path, in order. Balance is then over flows, not bytes: two large flows that hash to the same member share it while another member idles.
The Remapping Problem
hash mod k fails badly when the group changes. If one of k next hops fails, the flows on it must move, 1/k of all flows. But the survivors are renumbered and every flow is now taken mod k − 1, and a flow stays put only if its member under mod k is the same as under mod k − 1. Exactly 1/k of flows stay, whichever member failed (Exercise 28.9), so (k − 1)/k of flows move: 75% with 4 next hops, 99% with 100. For a router the cost is a burst of reordering. For a load balancer that spreads connections over servers by the same hashing, it is worse: a connection moved to a server without its TCP state is reset.
The fix is a level of indirection: a table of M buckets, M much larger than k, filled with members, and each flow goes to table[hash mod M]. When a member fails, only its buckets are reassigned. Many switches and Linux’s resilient next-hop groups work this way. The ring of consistent hashing (§27.3) is the same idea with buckets placed by hashing: it guarantees that only the failed member’s keys move, but the arcs are uneven. For 100 backends with v points each on the ring, measured below, the most-loaded backend owns 5.67 times its fair share of the ring with v = 1, 2.09 times with v = 10 and 1.21 times with v = 100. Every backend must be provisioned for the most-loaded one.
Maglev Hashing
Maglev is Google’s software network load balancer (Eisenbud et al., NSDI 2016). Its hashing builds the bucket table to be balanced first and stable second. Each backend i gets a preference list over the M table positions, a permutation built from two hashes of its name:
offset = h1(name) mod M
skip = h2(name) mod (M − 1) + 1
permutation[i][j] = (offset + j × skip) mod M
M is prime, so every skip in 1..M−1 is coprime to M and the list visits every position exactly once. The backends then take turns: each in round-robin order claims the first position on its list that is still empty, until the table is full. A lookup is one hash and one array read.
Worked example. This is the paper’s own: M = 7 and three backends with (offset, skip) = (3, 4), (0, 2) and (3, 1).
| backend | preference list |
|---|---|
| B1 | 3, 0, 4, 1, 5, 2, 6 |
| B2 | 0, 2, 4, 6, 1, 3, 5 |
| B3 | 3, 4, 5, 6, 0, 1, 2 |
Round 1: B1 takes 3, B2 takes 0, B3 finds 3 taken and takes 4. Round 2: B1 skips 0 and 4 and takes 1, B2 takes 2, B3 takes 5. Round 3: B1 skips 5 and 2 and takes 6, and the table is full: [B2, B1, B2, B1, B3, B3, B1], three entries for B1 and two for each of the others. Remove B2 and rebuild: B1 takes 3, 0, 1 and 2, B3 takes 4, 5 and 6, giving [B1, B1, B1, B1, B3, B3, B3]. Positions 0 and 2 had to change because B2 owned them. Position 6 changed too: without B2 taking turns, B3 reached 6 on its list before B1 did. That is the one extra disruption.
import hashlib
from collections import Counter
def h64(text):
return int.from_bytes(hashlib.blake2b(text.encode(), digest_size=8).digest(), "big")
def populate(prefs, M):
"""Maglev's table fill. prefs[i] = (offset, skip) for backend i; M prime."""
nxt = [0] * len(prefs) # next index into each backend's preference list
entry = [-1] * M
filled = 0
while True:
for i, (offset, skip) in enumerate(prefs):
c = (offset + nxt[i] * skip) % M
while entry[c] >= 0: # walk i's preference list to a free slot
nxt[i] += 1
c = (offset + nxt[i] * skip) % M
entry[c] = i
nxt[i] += 1
filled += 1
if filled == M:
return entry
def maglev_table(backends, M=65537):
prefs = [(h64("offset:" + b) % M, h64("skip:" + b) % (M - 1) + 1) for b in backends]
return [backends[i] for i in populate(prefs, M)]
assert populate([(3, 4), (0, 2), (3, 1)], 7) == [1, 0, 1, 0, 2, 2, 0] # B2 B1 B2 B1 B3 B3 B1
assert populate([(3, 4), (3, 1)], 7) == [0, 0, 0, 0, 1, 1, 1] # B1 x4, B3 x3
backends = [f"backend-{i}" for i in range(100)]
for M in (65537, 655373):
before = maglev_table(backends, M)
after = maglev_table([b for b in backends if b != "backend-37"], M)
counts = Counter(before)
forced = counts["backend-37"]
moved = sum(x != y for x, y in zip(before, after))
print(M, min(counts.values()), max(counts.values()), forced, moved)
def ring_shares(backends, vnodes):
"""Chapter 27's ring: each point owns the arc back to the previous point."""
points = sorted((h64(f"{b}#{j}"), b) for b in backends for j in range(vnodes))
share = Counter()
for k, (p, b) in enumerate(points):
share[b] += (p - points[k - 1][0]) % (1 << 64)
return share
for v in (1, 10, 100):
print(v, max(ring_shares(backends, v).values()) / ((1 << 64) / len(backends)))
The hashes are deterministic, so the output is reproducible:
| table size M | entries per backend | entries of backend-37 | entries changed on removing it | extra |
|---|---|---|---|---|
| 65,537 | 655 or 656 | 655 | 1,009 | 354 (0.54% of the table) |
| 655,373 | 6,553 or 6,554 | 6,554 | 7,572 | 1,018 (0.16%) |
Balance. Because the backends take strict turns and the fill stops when the table is full, every backend owns ⌊M/N⌋ or ⌈M/N⌉ entries, a guarantee rather than an expectation; the paper picks M > 100·N so that this rounding is under 1% of a backend’s share. Against the ring’s 1.21 with 100 points per backend, Maglev’s most-loaded backend here carries 1.001 times its fair share.
Disruption. It is not minimal. Removing one backend of 100 reassigns its 655 entries plus 354 others, so about 1.5% of flows move where 1% must. The extras come from the turn order shifting, as in the worked example, and they shrink as a fraction of the table when M grows, which matches the paper’s measurements. Maglev accepts this trade deliberately: over-provisioning every backend for an imbalanced hash costs capacity all the time, while extra moves happen only when backends change, and Maglev also keeps a per-machine connection-tracking table so that packets of an established connection keep going to their backend. The paper reports that, with 1,000 backends and a 65,537-entry table, Karger’s ring and rendezvous hashing would have needed backends over-provisioned by 29.7% and 49.5% to absorb their imbalance.
Cost. Lookup is O(1). Building the table takes O(M log M) expected time: when n of M positions are full, a backend expects M/(M − n) tries to find an empty one, and the sum of those terms is M·H_M. The worst case is O(M²), when the backends have nearly identical preference lists and N approaches M, which choosing M ≫ N avoids. The paper reports 1.8 ms to build a 65,537-entry table and 22.9 ms for 655,373, which is why the default is the smaller one.
28.5 BGP Routing Data Structures
Border Gateway Protocol (BGP) routes between Autonomous Systems (AS). BGP routing tables are massive (~900K IPv4 prefixes as of 2024).
BGPRIB (Routing Information Base)
BGP stores paths in a multi-attributed structure:
Prefix: 10.0.0.0/8
└─ AS_PATH: [1239, 701, 80]
└─ NEXT_HOP: 192.0.2.1
└─ LOCAL_PREF: 100
└─ MED: 50
└─ ORIGIN: IGP
Selection criteria (in order):
- Highest LOCAL_PREF
- Shortest AS_PATH
- Lowest ORIGIN (IGP < EGP < Incomplete)
- Lowest MED
- eBGP over iBGP
- Lowest IGP metric to NEXT_HOP
- Lowest router ID
Path Vector Storage
AS_PATH is a sequence, not a set. Multiple paths to same destination create branching structures:
Per-prefix best-path selection (BGP is path-vector; it runs no Dijkstra):
- Adj-RIB-In: every path learned from each neighbor
- Decision process: compare candidate paths by the criteria above
- Loc-RIB: the winner for each prefix; only the winner is advertised (Adj-RIB-Out)
- On UPDATE or WITHDRAW: re-run selection for the affected prefix only
28.6 Software-Defined Networking (SDN) Tables
OpenFlow switch tables store flow entries with wildcard matching:
TCAM (Ternary Content-Addressable Memory)
Hardware structure for wildcard matching:
- 0 = match bit exactly
- 1 = match bit exactly
-
- = don’t care (wildcard)
Priority: All entries are compared in parallel and the first matching entry in TCAM order wins, so entries are kept sorted by priority (for IP routing, by prefix length, so the longest match comes first).
Flow entry structure:
{
match: {
src_ip: 10.0.*.*,
dst_ip: *.168.1.*,
protocol: TCP,
src_port: *,
dst_port: 443
},
action: OUTPUT(port=3),
priority: 100,
stats: { packets: 1000, bytes: 50000 }
}
Wildcard Compression
Multiple rules can be merged if they differ only on don’t-care fields:
Rule 1: 10.0.0.0/8 with action A
Rule 2: 10.0.0.0/16 with action B
→ Cannot merge (Rule 2 is more specific)
28.7 Network Measurement Data Structures
Count-Min Sketch
Estimate traffic flow frequencies:
class CountMinSketch:
def __init__(self, width, depth):
self.width = width
self.depth = depth
self.table = [[0] * width for _ in range(depth)]
self.hash_functions = [generate_hash() for _ in range(depth)]
def add(self, item, count=1):
for i, h in enumerate(self.hash_functions):
self.table[i][h(item) % self.width] += count
def estimate(self, item):
return min(
self.table[i][h(item) % self.width]
for i, h in enumerate(self.hash_functions)
)
Accuracy: With width w and depth d, error ≤ ε·N with probability 1-δ where w = e/ε, d = ln(1/δ).
Heavy Hitter Detection
Identify flows exceeding threshold T:
import heapq
class SpaceSaving:
def __init__(self, k):
self.k = k
self.counters = {} # flow_id -> count
self.min_heap = [] # (count, flow_id); may hold stale entries
def add(self, item):
if item in self.counters:
self.counters[item] += 1
heapq.heappush(self.min_heap, (self.counters[item], item))
elif len(self.counters) < self.k:
self.counters[item] = 1
heapq.heappush(self.min_heap, (1, item))
else:
# Evict the true minimum, skipping stale heap entries
while True:
min_count, evict_item = heapq.heappop(self.min_heap)
if self.counters.get(evict_item) == min_count:
break
del self.counters[evict_item]
self.counters[item] = min_count + 1
heapq.heappush(self.min_heap, (min_count + 1, item))
def top_k(self):
return sorted(self.counters.items(), key=lambda x: -x[1])[:self.k]
28.8 Gossip Protocol Data Structures
Gossip-based systems use epidemic algorithms for dissemination. Each node periodically exchanges state with random peers.
Anti-entropy
Periodic comparison and reconciliation:
def anti_entropy(node, peer):
# Exchange digests (summary of owned data)
local_digest = node.compute_digest()
remote_digest = peer.compute_digest()
# Find differences
differences = compare_digests(local_digest, remote_digest)
# Synchronize
for key, version in differences:
if local_version < remote_version:
node.request(key, peer)
elif local_version > remote_version:
peer.request(key, node)
Convergence time: O(log N) rounds for O(N log N) messages total.
Broadcast Trees
Gossip can be organized into spanning trees for efficiency:
Root node creates spanning tree across cluster
Messages flow down tree (log N depth)
Negative acknowledgments flow up for reliability
Swim protocol for failure detection: Incremental membership updates with suspicion mechanism.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
28.1 ★ Build the CSR arrays. Convert the weighted adjacency list from §28.1 (A: B→10, C→5; B: A→10, D→3; C: A→5, D→7; D: B→3, C→7) into CSR form, numbering A = 0, B = 1, C = 2, D = 3. Then estimate the memory for an AS-level graph with 75,000 nodes and 500,000 undirected links stored (a) as an adjacency matrix with one bit per cell and (b) in CSR with 4-byte integers and no weights.
Solution
Each vertex’s edges are stored contiguously, and offsets[v] to offsets[v+1] is the slice belonging to v:
offsets = [0, 2, 4, 6, 8]
edges = [1, 2, 0, 3, 0, 3, 1, 2]
weights = [10, 5, 10, 3, 5, 7, 3, 7]
The neighbors of C (vertex 2) are edges[4:6] = [0, 3], that is A and D, with weights 5 and 7.
(a) Matrix: 75,000² = 5.625 × 10⁹ bits, about 703 MB, almost all zeros.
(b) CSR: an undirected link is stored once in each direction, so edges holds 1,000,000 entries × 4 B = 4 MB, plus offsets with 75,001 × 4 B ≈ 0.3 MB. About 4.3 MB in total, roughly 160 times smaller, and neighbor enumeration is a sequential scan of one contiguous slice.
28.2 ★★ Longest prefix match on a binary trie. A router has these routes: 0.0.0.0/0 → D, 10.0.0.0/8 → A, 10.1.0.0/16 → B, 10.1.2.0/24 → C. (a) Give the next hop for 10.1.2.3, 10.1.3.4, 10.2.0.1 and 11.0.0.1. (b) Add a delete(prefix) method to the RoutingTrie of §28.2 that removes a route and frees the nodes that no longer lead to any route. After deleting 10.1.2.0/24, what does 10.1.2.3 return, and how many nodes are left below the root? (c) How many trie nodes does the lookup for 10.1.3.4 visit below the root before it stops?
Hint
During lookup, remember the last next hop you passed. The answer is that remembered value when you run out of trie, not the value at the node where you stop.
Solution
(a) 10.1.2.3 → C (matches /24). 10.1.3.4 → B (the third octet 3 differs from 2, so the /24 does not match, but the /16 does). 10.2.0.1 → A. 11.0.0.1 → D (only the default route matches).
(b) Record the path on the way down, clear the route, then walk back up unlinking every node that now holds no route and has no children. Stop at the first node that still holds a route or still has a child: everything above it is needed.
def delete(self, prefix):
net = ipaddress.IPv4Network(prefix)
value = int(net.network_address)
path = [self.root]
for i in range(net.prefixlen):
child = path[-1].children[(value >> (31 - i)) & 1]
if child is None:
return False # no such route
path.append(child)
if path[-1].next_hop is None:
return False
path[-1].next_hop = None
for i in range(net.prefixlen - 1, -1, -1): # path[i + 1] hangs off path[i]
node = path[i + 1]
if node.next_hop is not None or node.children != [None, None]:
break
path[i].children[(value >> (31 - i)) & 1] = None
return True
RoutingTrie.delete = delete
t = RoutingTrie()
for prefix, hop in [("0.0.0.0/0", "D"), ("10.0.0.0/8", "A"),
("10.1.0.0/16", "B"), ("10.1.2.0/24", "C")]:
t.insert(prefix, hop)
assert t.delete("10.1.2.0/24") and not t.delete("10.1.2.0/24")
assert t.lookup("10.1.2.3") == "B"
10.1.2.3 now falls back to the /16, B. Before the delete there were 24 nodes below the root, one per bit of the longest route. The /24’s nodes at depths 17 to 24 lead to no other route, so all eight are unlinked, and the walk stops at depth 16 because that node holds B. Sixteen nodes remain. Deletion is O(W) in the worst case, like insertion. Nothing has to be rewritten to make the fallback work, because the shorter routes are still on the path; the expanded tables of §28.3 lose exactly that property.
(c) 10.1.3.4 and 10.1.2.0 agree on their first 23 bits (they differ in the last bit of the third octet). The lookup walks 23 nodes along the /24’s path, picking up A at depth 8 and B at depth 16, then finds no child for bit 24 and returns B. That is 23 dependent memory reads for one packet, which is the reason routers do not use a plain binary trie.
28.3 ★★ Prefix expansion in a multi-bit trie. A 16-8-8 multi-bit trie indexes its first level by the top 16 bits of the address, then uses 8 bits at each of two lower levels. Routes: 10.0.0.0/12 → X, 10.4.0.0/14 → Y, 10.5.128.0/17 → Z. Show which first-level slots hold what, and what the second-level table under 10.5 contains. How many memory accesses do lookups for 10.6.1.1, 10.5.1.1 and 10.5.200.1 take, and what do they return?
Hint
A prefix shorter than a level boundary is expanded into every slot it covers. When two expanded prefixes land on the same slot, the longer original prefix wins.
Solution
The /12 fixes the first 12 bits: 10 and the top four bits of the second octet are 0000, so it covers second octets 0 to 15, which is 2^(16−12) = 16 first-level slots. The /14 fixes the top six bits of the second octet as 000001, covering 4 to 7, which is 4 slots. Being longer, Y overrides X on those four:
| first-level slot | contents |
|---|---|
| 10.0 to 10.3 | X |
| 10.4 | Y |
| 10.5 | pointer to a level-2 table |
| 10.6, 10.7 | Y |
| 10.8 to 10.15 | X |
The /17 does not end on the 16-bit boundary, so slot 10.5 becomes a pointer to a 256-entry table indexed by the third octet. The /17 fixes the top bit of the third octet as 1: entries 128 to 255 hold Z. Entries 0 to 127 must still hold Y, because the /14 covers them. This is called pushing the shorter prefix down.
Lookups: 10.6.1.1 reads slot 10.6 and returns Y in one access. 10.5.1.1 reads slot 10.5, follows the pointer, reads entry 1, returns Y: two accesses. 10.5.200.1 does the same and reads entry 200: Z, two accesses. The worst case is three accesses for any IPv4 address, at the cost of a 65,536-entry first level and duplicated entries wherever a short prefix is expanded.
28.4 ★ Apply BGP best-path selection. A router has four paths to 203.0.113.0/24. Using the selection order in §28.5, which one wins, and at which step is each loser eliminated?
| path | LOCAL_PREF | AS_PATH | ORIGIN | MED | learned via |
|---|---|---|---|---|---|
| P1 | 100 | 701 80 | IGP | 50 | eBGP |
| P2 | 100 | 701 80 | IGP | 10 | eBGP |
| P3 | 90 | 80 | IGP | 0 | eBGP |
| P4 | 100 | 3356 174 80 | IGP | 0 | eBGP |
Solution
Step 1, highest LOCAL_PREF: P3 has 90, the others 100. P3 is out, even though it has the shortest AS_PATH. Local policy beats path length; this is how an operator prefers a cheaper transit provider.
Step 2, shortest AS_PATH among P1, P2, P4: P1 and P2 have length 2, P4 has 3. P4 is out.
Step 3, lowest ORIGIN: P1 and P2 are both IGP. Tie.
Step 4, lowest MED: P2 has 10, P1 has 50. P2 wins.
One real-world detail: routers compare MED by default only between paths received from the same neighboring AS, because MED is a hint from that neighbor about which of its entry points it prefers. Here P1 and P2 both come from AS 701, so the comparison applies.
28.5 ★★ Trace a Count-Min sketch. Use width w = 4 and depth d = 2 with h1(x) = x mod 4 and h2(x) = ⌊x/4⌋ mod 4. Insert the flow IDs 1, 5, 2, 1, 9, 3, 1, 6 (count 1 each). Give the final table and the estimates for 1, 5, 9 and 7. Then size a sketch for ε = 0.001 and δ = 0.01 using the formulas in §28.7.
Solution
Bucket of each ID in (row 1, row 2): 1 → (1, 0), 5 → (1, 1), 2 → (2, 0), 9 → (1, 2), 3 → (3, 0), 6 → (2, 1).
Final table:
row 1: [0, 5, 2, 1]
row 2: [5, 2, 1, 0]
Row 1, bucket 1 received 1, 5, 1, 9, 1. Row 2, bucket 0 received 1, 2, 1, 3, 1.
| ID | row 1 | row 2 | estimate | true |
|---|---|---|---|---|
| 1 | 5 | 5 | 5 | 3 |
| 5 | 5 | 2 | 2 | 1 |
| 9 | 5 | 1 | 1 | 1 |
| 7 | 1 | 2 | 1 | 0 |
Every estimate is at least the true count, because a counter only ever receives additions from its own item and from colliding ones. The minimum picks the row with the fewest collisions: 9 is exact because row 2 isolates it, while 1 collides in both rows and is over by 2. Flow 7 was never seen but gets 1, so a Count-Min sketch can report traffic for a flow that does not exist; it cannot report zero for one that does.
Sizing: w = ⌈e/ε⌉ = ⌈2718.3⌉ = 2,719 and d = ⌈ln(1/δ)⌉ = ⌈4.61⌉ = 5. That is 13,595 counters, about 54 KB with 4-byte counters, for an error of at most 0.1% of total traffic with 99% probability, regardless of how many distinct flows there are.
28.6 ★★★ Space-Saving: trace and guarantee. (a) Trace the SpaceSaving class from §28.7 with k = 2 on the stream a, a, b, c, c, c, a, giving the counters after each item, and compare with the true counts. (b) The add method pushes a fresh heap entry on every increment and, when evicting, pops until it finds an entry whose count matches the current counter. What would go wrong without that check? (c) Prove that after N items, any item that occurred more than N/k times is in the summary.
Hint
For (c), show three facts: the counters always sum to N; a monitored item’s counter never underestimates its true count; and an unmonitored item’s true count never exceeds the current minimum counter.
Solution
(a)
| item | counters | note |
|---|---|---|
| a | {a: 1} | |
| a | {a: 2} | |
| b | {a: 2, b: 1} | summary now full |
| c | {a: 2, c: 2} | evict b (min 1), c gets 1 + 1 |
| c | {a: 2, c: 3} | |
| c | {a: 2, c: 4} | |
| a | {a: 3, c: 4} |
True counts: a = 3, b = 1, c = 3. The counter for c is 1 too high: it inherited b’s count when it took b’s slot. The error of any counter is at most the minimum it replaced.
(b) The heap is not updated in place when a counter is incremented, so it holds old entries such as (1, a) after a’s counter has become 2. Without the check, k = 1 on the stream a, a, b would pop (1, a) and give b the count 1 + 1 = 2, though the true minimum was 2 and b should get 3. Worse, a popped entry might name an item that was already evicted. The check counters.get(evict_item) == min_count discards such stale entries. It never discards the live entry, because an item’s count only grows while it is monitored, and when it is evicted and later re-added its new count exceeds every count it had before (the minimum never decreases, as shown below), so an old entry can never match.
(c) Let m be the smallest counter.
- The counters sum to N. Each
addraises the total by exactly 1: an increment adds 1, a new item with a free slot adds 1, and an eviction removes m and inserts m + 1. - m never decreases. Counters only increase, and an eviction replaces the minimum with something larger.
- A monitored item’s counter is at least its true count, and an unmonitored item’s true count f is at most m. By induction: when x is evicted, its counter equalled the minimum at that moment and was at least f, so f ≤ m then and, by fact 2, forever after until x reappears. When x reappears and evicts the minimum m, its new counter is m + 1 ≥ f + 1, which is its new true count.
With k counters summing to N, the minimum satisfies m ≤ N/k. If x occurred more than N/k times, then f > N/k ≥ m, so by fact 3 x cannot be unmonitored. The summary therefore contains every heavy hitter, using only k counters, though some items it contains may not be heavy (b’s slot went to c with an inflated count). A second pass, or the bound count − m ≤ true count ≤ count, tells which candidates are real.
28.7 ★★ Updating a DIR-24-8 table. Start from the table built in §28.3: 10.54.0.0/16 → 1, 10.54.34.0/24 → 2, 10.54.34.192/26 → 3. (a) The route 10.0.0.0/8 → 4 arrives. Which TBL24 entries must it write, which must it leave alone, and why can’t build_dir_24_8’s rule (sort by length, later writes overwrite) be applied to a single insertion? (b) Then 10.54.34.0/24 is withdrawn. What must group 0’s entries hold afterwards, and what information do the two tables lack to work that out? (c) Show how storing in every entry the length of the prefix that wrote it (its depth, as DPDK does) makes both updates local.
Solution
(a) The /8 covers TBL24 entries 10.0.0 to 10.255.255, 2^16 = 65,536 of them. The 256 entries 10.54.0 to 10.54.255 were written by longer prefixes (the /16, and at 10.54.34 the /24 and then the /26’s group pointer), so they must keep their values; the /8 writes the other 65,280. The static build gets this right only because it processes every shorter prefix before any longer one. A single insertion arrives after the longer routes are in place, and an entry holding 1 looks the same whether a /16 or an /8 wrote it, so a blind write of the range would erase the /16.
(b) Entries 0 to 191 held 2, the /24’s answer pushed down when the group was created. They must now hold 1, from 10.54.0.0/16, the longest remaining route covering them. Entries 192 to 255 keep 3, and TBL24 entry 10.54.34 stays a pointer because the /26 still needs the group. The tables store only next hops: nothing in them says that 2 came from a /24, or that a /16 covers it. The router has to find the replacement in a separate list of the routes themselves, which is why DPDK keeps one beside the tables.
(c) Give each entry a (next hop, depth) pair. To insert a prefix of length d, write each entry in its range only if the entry is empty or its depth is at most d; when the entry is a group pointer, apply the same test to the group’s 256 entries. In (a), the 10.54.x entries have depth 16 or are pointers into a group whose entries have depth 24 and 26, so the /8 (depth 8) skips them all. To delete a prefix P of length d, look up its replacement R, the longest remaining route that covers P, and rewrite only the entries in P’s range whose depth equals d, with R’s next hop and depth (or empty if there is no R). Entries with greater depth belong to longer routes and are left alone. In (b), the 192 entries with depth 24 become (1, 16) and the 64 with depth 26 are untouched. When every entry of a group ends up with depth 24 or less and the same next hop, the group can be folded back into its TBL24 entry and freed; DPDK’s delete does this check.
28.8 ★★ Maglev by hand. Add a fourth backend B4 with (offset, skip) = (5, 3) to the worked example of §28.4 (M = 7). (a) Write B4’s preference list and build the table. (b) How many entries differ from the three-backend table [B2, B1, B2, B1, B3, B3, B1], and what is the fewest any scheme could change while keeping every backend within one entry of the others? (c) Why must M be prime? Show what goes wrong with M = 8 and a backend whose skip is 2.
Solution
(a) B4’s list is (5 + 3j) mod 7 for j = 0 to 6: 5, 1, 4, 0, 3, 6, 2. Round 1: B1 takes 3, B2 takes 0, B3 finds 3 taken and takes 4, B4 takes 5. Round 2: B1 skips 0 and 4 and takes 1, B2 takes 2, B3 skips 5 and takes 6. That is 7 entries, so the fill stops before B4’s second turn: [B2, B1, B2, B1, B3, B4, B3], with 2, 2, 2 and 1 entries.
(b) Two entries changed: position 5 (B3 to B4) and position 6 (B1 to B3). The minimum is one: B4 must get at least ⌊7/4⌋ = 1 entry, and taking one of B1’s three gives the balanced 2, 2, 2, 1 with a single change. Maglev spent an extra change because B4 claimed position 5, which B3 used to take in round 2, so B3 went further down its list to 6, which B1 used to take in round 3. The extra moves are the price of building the table from the current backend set alone, with no memory of the previous table.
(c) The list (offset + j·skip) mod M visits every position exactly when gcd(skip, M) = 1. With M = 8, skip = 2 and offset 0 the list is 0, 2, 4, 6, 0, 2, …, so the backend can only ever claim even positions. Once those are full, its while entry[c] >= 0 loop never finds an empty slot and the build never finishes. With M prime, every skip from 1 to M − 1 is coprime to M, so the simple formula is always safe.
28.9 ★★ Why hash mod k moves almost every flow. An ECMP group has next hops h_0, …, h_(k−1), and a flow with hash x uses h_(x mod k). Hop h_v fails; the survivors keep their order, are renumbered 0 to k − 2, and flows now use x mod (k − 1). (a) Prove that, over a full period of x, exactly 1/k of flows keep their next hop, whatever v is. (b) A simpler repair keeps k slots and puts some survivor into the dead hop’s slot. What fraction of flows move, and what does it cost? (c) How does a table of M ≫ k buckets avoid both problems, and why does Maglev rebuild its table from scratch instead of patching it?
Solution
(a) Take x over k(k − 1) consecutive values. Because gcd(k, k − 1) = 1, the Chinese remainder theorem says each pair (a, b) = (x mod k, x mod (k − 1)) occurs exactly once. A flow keeps its next hop when a ≠ v and b is the new index of h_a: b = a if a < v, b = a − 1 if a > v. That is exactly one b for each of the k − 1 surviving values of a, so k − 1 of the k(k − 1) pairs, a fraction 1/k. The other (k − 1)/k of flows move, although only the 1/k that were on h_v had to.
(b) Only the flows of the dead hop move, 1/k, the minimum. But they all land on the one survivor put in the slot, which now carries 2/k of the traffic, twice its share, and a second failure can make it worse.
(c) With table[x mod M] and roughly M/k buckets per hop, the dead hop’s buckets can be handed out one at a time across all survivors: only its flows move, and each survivor’s share grows by about 1/(k(k − 1)), staying within one bucket (1/M of traffic) of the others. Maglev rebuilds rather than patches because many load-balancer machines must map the same flow to the same backend without talking to each other. A table that depends only on the current set of backends, not on the order in which failures happened, is one every machine computes identically. The cost is the small extra disruption measured in §28.4.
Where this connects
- Chapter 11: Graphs—Modeling Relationships. The graph fundamentals underneath routing
- Chapter 13: String Data Structures. The tries that routing tables actually are
- Chapter 27: Distributed Data Structures. Ring-based consistent hashing, the minimal-disruption but less balanced alternative to Maglev’s table
Chapter 29: System Design as Data Structure Composition
29.1 The Unifying Theory
System design is the art of composing data structures and algorithms to solve real-world problems at scale. Every complex system reduces to foundational building blocks.
The System Design Equation:
System = Data Structures + Concurrency Control + Replication + Consistency + APIs
Where:
- Data Structures: How information is organized
- Concurrency Control: Managing simultaneous access
- Replication: Duplicating data for reliability
- Consistency: Maintaining truth across copies
- APIs: The interface to the outside world
29.2 Key-Value Stores
Key-value stores are the simplest non-trivial data structure composition: a hash table extended with persistence and replication.
Memcached Architecture
In-memory hash table with LRU eviction:
Client request:
1. Hash key → server selection (consistent hash)
2. Connect to server (TCP)
3. Send GET/SET command
4. Parse response
5. Return to client
Server internal:
- Hash table: O(1) lookup
- LRU chain: O(1) insertion/deletion
- Slab allocator: Reduce fragmentation
Slab allocation: Pre-allocate size classes (64B, 128B, …, 1MB). Items assigned to smallest sufficient class. Reduces fragmentation but may waste space.
Redis Data Structures
Redis implements rich data types on top of key-value:
- String: Binary-safe value (bitmap operations available)
- List: Linked list, O(1) push/pop at both ends
- Hash: Field-value map, O(1) field operations
- Set: Hash set (no duplicates), O(1) membership
- Sorted Set: Score-ordered, O(log N) insert, O(log N + M) to return a range of M items
Persistence: RDB (point-in-time snapshots) + AOF (append-only log). Trade-off: performance vs durability.
29.3 Message Queues as Persistent Queues
Message queues are persistent FIFO structures with durability and ordering guarantees.
Apache Kafka Architecture
Log-structured storage with consumer groups:
Topic: ordered, immutable sequence of records
↓ (partitioned)
Partition: sequential log on disk
↓ (replicated)
Leader + Followers (ISR - In-Sync Replicas)
Producer: batch writes to partition leader
Consumer: offset-based consumption, committed to disk
Offset management: Consumer tracks position in partition. Enables:
- At-least-once: Commit offset after processing
- At-most-once: Commit offset before processing
- Exactly-once: Transactional commits (Kafka transactions)
Segment files: Logs split into segments (~1GB). Index file maps offset → position. Enables efficient seeking.
RabbitMQ
Queue-based with exchange routing:
Exchange (topic/direct/fanout)
→ Binding
→ Queue
→ Consumer
Persistence levels:
- Queue durable: Survive broker restart
- Message persistent: Written to disk
- Publisher confirms: Wait for replication acknowledgment
29.4 Database Storage Engines
Storage engines choose data structures for disk efficiency.
B-Tree Storage (InnoDB, PostgreSQL)
B-trees optimized for disk with large block sizes:
Page structure (16KB typical):
- Page header (metadata, checksum)
- User data area
- Free space
- Slot directory (pointers to entries)
B-tree optimizations:
- Page directory for 2-level index
- Leaf page chaining for range scans
- Write-ahead log (WAL) for durability
- Buffer pool for caching
Double-write buffer: InnoDB writes to temporary area before final location. Prevents torn writes on crash.
LSM-Tree Storage (LevelDB, RocksDB, Cassandra)
Log-Structured Merge trees optimize write throughput:
Write path:
1. Write to WAL (durability)
2. Insert into memtable (in-memory skip list)
3. When memtable fills, sort and write to L0 SSTable
Compaction:
- L0 → L1: Sort by key, merge files
- L1 → L2: Key range partitioned, merge
- Classic: Size-tiered (Cassandra)
- Modern: Level-based (RocksDB)
Trade-offs vs B-trees:
- Writes: 3-10x faster (sequential writes)
- Reads: Slower (check multiple structures)
- Space: Higher (stale versions persist until compaction removes them)
29.5 Load Balancing Algorithms
Load balancers distribute requests across backend servers. Each algorithm uses different data structures for state tracking.
Round Robin
Simple rotation with no state:
Server list: [A, B, C]
Request 1 → A
Request 2 → B
Request 3 → C
Request 4 → A (wrap)
Weighted round robin: Servers with higher weight receive more requests.
Least Connections
Track active connections per server:
class LeastConnections:
def __init__(self, servers):
self.connections = {s: 0 for s in servers} # server -> count
def select(self):
return min(self.connections, key=self.connections.get)
def add_request(self, server):
self.connections[server] += 1
def remove_request(self, server):
self.connections[server] -= 1
Problem: Treats every connection as equal cost. Two connections to a slow or overloaded server count the same as two to a fast one, and select is an O(S) scan over S servers.
Least Loaded with Load Scoring
Multi-metric scoring:
def score_server(server):
cpu_score = server.cpu_usage / 100
mem_score = server.memory_usage / 100
conn_score = server.active_connections / server.max_connections
# Weighted combination
return (0.4 * cpu_score + 0.3 * mem_score + 0.3 * conn_score)
Power of Two Choices
Least connections answers “which server is least loaded?” exactly, by looking at every server. The power of two choices asks a cheaper question: pick two servers uniformly at random and send the request to the less loaded of the two. On top of the LeastConnections bookkeeping above, only select changes:
import random
class PowerOfTwoChoices(LeastConnections):
def __init__(self, servers, rng=random):
super().__init__(servers)
self.servers = list(servers)
self.rng = rng
def select(self):
a, b = self.rng.sample(self.servers, 2) # two distinct servers
return a if self.connections[a] <= self.connections[b] else b
select now reads two counters instead of S, so it is O(1) worst case, and it needs no ordering structure over the servers at all: no heap, no buckets.
The result. The clean model is balls into bins: n balls (requests) are placed one at a time into n bins (servers), and none leave. If each ball goes to one bin chosen at random, the fullest bin ends up with (1 + o(1)) ln n / ln ln n balls with high probability, which is Θ(log n / log log n). If each ball looks at d ≥ 2 random bins and joins the least loaded, the maximum drops to ln ln n / ln d + Θ(1), which is Θ(log log n) (Azar, Broder, Karlin and Upfal, 1994). Going from one choice to two is an exponential improvement. Going from two to three only divides the leading term by ln 3 / ln 2 ≈ 1.58.
The reason is squaring. Let βᵢ be the fraction of bins with load at least i. A ball can raise a bin to load i + 1 only if both of its choices already have load at least i, which happens with probability about βᵢ². So, heuristically, βᵢ₊₁ ≈ βᵢ². There are only n balls, so at most half the bins can hold two or more: β₂ ≤ 1/2, and the sequence is at most 1/2, 1/4, 1/16, 1/256, 1/65,536, and so on. The exponent doubles at every level, so after about log₂ log₂ n levels the expected number of bins that high falls below one. With one choice, the load of a bin is roughly Poisson with mean 1, and the fraction of bins with load at least k is about 1/(e·k!), which shrinks only factorially. (The real proof is a layered induction that makes this heuristic rigorous by bounding the deviation at every level.)
A seeded simulation shows the difference:
import random
def throw(n_bins, n_balls, d, seed=1):
"""Each ball goes to the least loaded of d bins chosen at random."""
rng = random.Random(seed)
load = [0] * n_bins
for _ in range(n_balls):
best = min((rng.randrange(n_bins) for _ in range(d)), key=load.__getitem__)
load[best] += 1
return load
for n in (10**3, 10**4, 10**5, 10**6):
print(n, [max(throw(n, n, d)) for d in (1, 2, 3)])
for d in (1, 2): # how many of 10**6 bins reach load >= k, for k = 1..8
load = throw(10**6, 10**6, d)
print(d, [sum(x >= k for x in load) for k in range(1, 9)])
for m in (10**4, 10**5, 10**6): # 1,000 bins, m balls: excess over the mean
print(m, [max(throw(1000, m, d)) - m // 1000 for d in (1, 2)])
It prints the following (the code takes a few seconds):
| n = number of balls = number of bins | 1,000 | 10,000 | 100,000 | 1,000,000 |
|---|---|---|---|---|
| max load, one choice | 5 | 6 | 7 | 8 |
| max load, two choices | 3 | 3 | 4 | 4 |
| max load, three choices | 2 | 3 | 3 | 3 |
| bins with load ≥ k (n = 10⁶) | k = 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|
| one choice | 264,128 | 80,618 | 19,032 | 3,702 | 562 | 84 | 8 |
| two choices | 229,701 | 9,014 | 6 | 0 | 0 | 0 | 0 |
The second table is the squaring argument in action: with one choice each level holds only about k times fewer bins than the level below it (the factorial at work), and with two choices the count collapses from 9,014 to 6 in one step. The absolute numbers in the first table are small because both bounds grow slowly, but a load balancer cares about a different regime, where there are far more requests than servers. There the gap widens:
| 1,000 bins, m balls: max load minus the mean m/n | m = 10⁴ | 10⁵ | 10⁶ |
|---|---|---|---|
| one choice | 11 | 42 | 105 |
| two choices | 2 | 2 | 3 |
With one choice the excess grows like √(m log n / n). With two choices it stays at ln ln n / ln 2 + O(1) no matter how many balls are thrown (Berenbrink, Czumaj, Steger and Vöcking, 2000): the fullest server is never more than a few requests above average.
Why not just pick the least loaded? With exact, instantly updated load and a single balancer, least loaded is better than two choices. Real balancers have neither. Load figures arrive by periodic health checks or load reports, and a fleet of independent balancers (or worker processes inside one) cannot see each other’s decisions between updates. Every one of them sees the same server as least loaded and sends it everything until the next update arrives: the server that looked idle is buried, and the next update moves the herd to a different victim. Two random choices cannot herd like this, because any given server is one of the two candidates for only about 2/S of the requests, so it receives at most about twice its fair share no matter how attractive its stale load looks. Mitzenmacher (“How Useful Is Old Information?”, 2000) analysed exactly this. A small queueing simulation reproduces it: 100 servers, 90 new jobs per tick, each busy server finishing a job with probability 0.95 per tick (so the servers are about 95% utilised), and the balancer sees a load snapshot refreshed every period ticks.
import random
def mean_queue(policy, period, n=100, arrivals=90, p_serve=0.95, ticks=10_000, seed=1):
"""Average jobs queued per server when the balancer sees loads refreshed every `period` ticks."""
rng = random.Random(seed)
queue = [0] * n
total = 0
for t in range(ticks):
if t % period == 0:
seen = queue[:] # the stale view
low = min(seen)
lowest = [i for i in range(n) if seen[i] == low]
for _ in range(arrivals):
if policy == "random":
s = rng.randrange(n)
elif policy == "least loaded":
s = rng.choice(lowest) # ties broken at random
else: # "two choices"
a, b = rng.randrange(n), rng.randrange(n)
s = a if seen[a] <= seen[b] else b
queue[s] += 1
for i in range(n):
if queue[i] and rng.random() < p_serve:
queue[i] -= 1
total += sum(queue)
return total / (ticks * n)
for period in (1, 5, 20, 50):
print(period, [round(mean_queue(p, period), 2)
for p in ("random", "least loaded", "two choices")])
| snapshot refreshed every | random | least loaded | two choices |
|---|---|---|---|
| 1 tick | 8.61 | 1.03 | 1.28 |
| 5 ticks | 8.61 | 16.93 | 2.30 |
| 20 ticks | 8.61 | 130.30 | 5.38 |
| 50 ticks | 8.61 | 702.69 | 10.99 |
Even at a period of one tick the balancer routes 90 jobs on the same snapshot; least loaded still wins there because, with queues this short, many servers tie at the minimum and the random tie-break spreads the batch. At five ticks it is already twice as bad as ignoring load entirely, and at 50 ticks the queues grow without bound: the system is unstable. Two choices degrades gracefully. With very stale information it ends up slightly worse than random, which is also what Mitzenmacher found: old data is still mildly misleading, but it can no longer cause a stampede.
Where it is used. NGINX’s random two directive (since 1.15.1) picks two servers at random, honouring weights, and sends the request to the one with fewer active connections. HAProxy’s balance random(<draws>) defaults to 2 draws and its documentation names the technique. Envoy’s least request balancer, when all hosts have equal weight, samples a configurable number of hosts (2 by default) and picks the one with the fewest active requests; it calls this P2C. The same idea appears outside load balancing: Redis evicts by sampling a few keys and dropping the best candidate among them (see the eviction policies in §29.6), and two-choice hashing places each key in the emptier of two buckets.
Consistent Hash for Load Balancing
Ensure session affinity without sticky sessions:
Key space: 0 to 2^32-1
Nodes placed at hash(node_ip) positions
Virtual nodes at hash(node_ip + ":replica" + i)
Request routed to first node clockwise from hash(request_id)
29.6 CDN and Caching Hierarchies
CDNs create multi-level caching hierarchies for content distribution.
Cache Invalidation Strategies
TTL-based expiration:
def is_valid(cached_item, max_age):
return time.time() - cached_item.timestamp < max_age
Active invalidation: Purge signals propagate through cache hierarchy.
Probabilistic early expiration: Reduce cache stampedes:
def should_revalidate(item, beta=1.0):
# XFetch (Vattani et al.): item.delta is how long the last
# recomputation took; beta > 1 favors earlier refreshes.
# -log(u) is exponentially distributed, so a rare request refreshes
# early, more often as expiry nears, instead of all at once after it.
u = 1.0 - random.random() # in (0, 1], avoids log(0)
return time.time() - item.delta * beta * math.log(u) >= item.expires
Eviction Policies as Data Structures
A cache with a size limit needs a rule for which entry to drop when a new one arrives. Each rule is a data structure: what it records per entry and what it must touch on every hit decide its cost as much as its hit rate does. All the policies below keep a hash map from key to entry (expected O(1)); what differs is the structure beside it.
LRU evicts the entry whose last use is oldest. A hash map points into a doubly linked list kept in recency order: a hit unlinks the node and pushes it to the front, and eviction removes the tail, both in O(1). Chapter 12 builds it in Exercise 12.6, and memcached’s “LRU chain” in §29.2 is this list. LRU has two weaknesses, and both come from the list. Every hit is a write: the node moves, so a cache shared by many threads must take a lock on the list even to serve a read. And LRU remembers only recency: one scan over more distinct keys than the cache holds (a backup, a full table scan, a crawler) evicts every hot entry, and each of them must miss once to come back.
LFU in O(1), and Making It Forget
LFU evicts the entry with the fewest accesses. The obvious structure is a min-heap keyed by count, at O(log n) per hit, because every hit changes a key. But counts only ever change by +1 and a new entry always starts at 1, so the heap can be replaced by buckets: a map from each count to the keys that have it, kept in recency order to break ties, plus the current minimum count (Shah, Mitra and Matani, 2010; the same trick as Exercise 29.7). A hit moves a key from bucket f to bucket f + 1. If bucket f was the minimum and is now empty, the new minimum is f + 1, because no count lies in between. An insertion sets the minimum back to 1. Eviction pops the oldest key from the minimum bucket.
from collections import OrderedDict, defaultdict
class LFUCache:
"""O(1) LFU: keys grouped by frequency; ties go to the least recently used."""
def __init__(self, capacity):
self.capacity = capacity
self.entry = {} # key -> [value, freq]
self.by_freq = defaultdict(OrderedDict) # freq -> keys, oldest first
self.min_freq = 0
def _bump(self, key):
e = self.entry[key]
f = e[1]
del self.by_freq[f][key]
if not self.by_freq[f]:
del self.by_freq[f]
if self.min_freq == f:
self.min_freq = f + 1 # nothing lies between f and f + 1
e[1] = f + 1
self.by_freq[f + 1][key] = None
def get(self, key):
if key not in self.entry:
return None
self._bump(key)
return self.entry[key][0]
def put(self, key, value):
if key in self.entry:
self.entry[key][0] = value
self._bump(key)
return
if len(self.entry) == self.capacity:
bucket = self.by_freq[self.min_freq]
victim, _ = bucket.popitem(last=False)
if not bucket:
del self.by_freq[self.min_freq]
del self.entry[victim]
self.entry[key] = [value, 1]
self.by_freq[1][key] = None
self.min_freq = 1
Every operation is a constant number of dictionary operations: O(1) expected. The original paper uses a doubly linked list of frequency nodes, each holding a linked list of keys; OrderedDict is that inner list.
LFU resists scans by construction: scanned keys enter with count 1 and evict each other, never the hot keys with large counts. Its failure is the opposite one: it never forgets. A key that was hot yesterday keeps its count, while a key that is hot today enters at 1 and is the first to go. Two fixes are common. Decay periodically halves every count, as W-TinyLFU’s sketch does below (Redis’s LFU mode also decays its small per-key counters as time passes). Dynamic aging (LFU-DA) keeps one cache-wide value L, sets it to the priority of each entry it evicts, and gives an entry priority L + count whenever it is inserted or hit. A newcomer starts at L + 1, just above the last victim, so an entry whose count has stopped growing is eventually overtaken. Squid offers this as heap LFUDA, after work at HP Labs on web proxy caches in the late 1990s. Priorities now jump by more than one, so the buckets no longer apply and LFU-DA needs a heap: O(log n) per access. Exercise 29.10 builds it.
CLOCK (Second Chance)
CLOCK approximates LRU without moving anything on a hit. Entries sit in a fixed circular array of slots, each with one reference bit, and a “hand” points at one slot. A hit sets the entry’s bit. To evict, the hand sweeps forward: a slot with its bit set gets a second chance (the bit is cleared and the hand moves on), and the first slot found with its bit clear is the victim.
class ClockCache:
"""CLOCK (second chance): slots in a circle, one reference bit per slot."""
def __init__(self, capacity):
self.capacity = capacity
self.keys = [None] * capacity
self.values = [None] * capacity
self.ref = [False] * capacity
self.slot = {} # key -> slot index
self.hand = 0
def get(self, key):
i = self.slot.get(key)
if i is None:
return None
self.ref[i] = True # a hit only sets a bit: nothing moves
return self.values[i]
def put(self, key, value):
i = self.slot.get(key)
if i is None:
i = self._victim()
if self.keys[i] is not None:
del self.slot[self.keys[i]]
self.keys[i] = key
self.slot[key] = i
self.values[i] = value
self.ref[i] = True
def _victim(self):
while True:
i = self.hand
self.hand = (i + 1) % self.capacity
if self.keys[i] is None or not self.ref[i]:
return i
self.ref[i] = False # second chance: clear the bit, move on
c = ClockCache(3)
for k in "abc":
c.put(k, k.upper())
c.put("d", "D") # every bit set: sweep clears all, evicts a
assert c.keys == ["d", "b", "c"] and c.ref == [True, False, False] and c.hand == 1
c.get("b") # b's bit set again
c.put("e", "E") # b gets a second chance, c is evicted
assert c.keys == ["d", "b", "e"] and c.ref == [True, False, True] and c.hand == 0
The trace: a, b and c fill slots 0 to 2 with their bits set. Inserting d sends the hand all the way round, clearing a, b and c, and back to slot 0, where a’s bit is now clear: a is evicted and d takes its slot, with the hand left at slot 1. The hit on b sets its bit. Inserting e finds b’s bit set at slot 1 (cleared, second chance) and c’s bit clear at slot 2, so c is evicted. LRU would have evicted a and then c as well. The two differ when every bit is set: then the sweep clears them all and CLOCK evicts in slot order, which is FIFO (Exercise 29.9).
A hit is O(1) worst case and writes one bit. One eviction can sweep all c slots, but it is amortized O(1): each step of the hand either finds the victim or clears a bit, and each bit was set by an earlier access, so the total movement of the hand is at most the number of accesses plus the number of evictions.
This is why operating systems and databases use CLOCK-style approximations instead of true LRU. In a virtual memory system, the MMU sets an “accessed” bit in the page table entry on every memory reference; the kernel cannot run code on every load and store to relink a list, so all it can do is read and clear those bits later, which is exactly what the clock hand does. Linux keeps active and inactive page lists and moves pages between them using the same bits. PostgreSQL’s shared buffer pool is used concurrently by many backend processes, and a true LRU list would put a lock on every buffer hit. PostgreSQL 8.0 shipped ARC (below), replaced it with the simpler 2Q in a later 8.0.x release because of IBM’s pending patent on ARC, and moved to a clock sweep in 8.1 (2005), largely to remove that contention. Each buffer carries a small usage count instead of one bit: a hit increments it (capped at 5), the sweep decrements it, and a buffer is evicted when the sweep finds it at zero, so a buffer used often survives several passes. Redis goes further and keeps no eviction structure at all: in its LRU modes it samples a few keys (5 by default) and evicts the one idle longest, the eviction-side cousin of the power of two choices.
ARC
ARC, the Adaptive Replacement Cache (Megiddo and Modha, IBM, 2003), balances recency against frequency and tunes the balance itself. It keeps two LRU lists of cached entries: T1 for keys seen once recently, T2 for keys seen at least twice. It also keeps two ghost lists, B1 and B2, which hold only the keys (no values) of entries recently evicted from T1 and T2. A target size p splits the c slots between T1 and T2. A miss that finds its key in B1 means T1 was too small (a recency-only entry would have hit), so p grows; a miss that finds its key in B2 means T2 was too small, so p shrinks. Every step is a constant number of hash and list operations, O(1), and the metadata is about twice LRU’s, since the ghost lists track up to c evicted keys. A scan only passes through T1, so the frequently used entries in T2 survive it. ZFS’s in-memory cache is an ARC and is named after it.
W-TinyLFU
W-TinyLFU (Einziger, Friedman and Manes) separates two questions that LRU and LFU answer together: which entry to evict, and whether a new key deserves a place at all. Its structure, as used by Caffeine, the standard Java caching library:
- A small window, an LRU holding 1% of capacity at first, where every new key lands.
- A main region, a segmented LRU holding the rest: 20% probation and 80% protected. A hit in probation promotes the entry to protected; protected’s overflow is demoted back to probation.
- An admission filter: a Count-Min sketch that counts every access, hits and misses alike, including keys not in the cache.
When the window overflows, its LRU victim becomes a candidate for the main region and competes with the main region’s own victim, the LRU entry of probation. The sketch estimates both frequencies, and the candidate gets in only if its estimate is higher; otherwise the candidate is the one dropped. The sketch is what makes this cheap: it remembers frequencies for keys the cache no longer holds, in a few bits per key. Caffeine’s has four 4-bit counters per key (so a count saturates at 15) and halves every counter after a number of increments equal to ten times the cache’s maximum size, so old popularity fades. It costs about 8 bytes per cache entry, and Caffeine resizes the window at run time by hill climbing on the observed hit rate. A scanned key has an estimated count near 1, loses every admission contest, and never displaces anything in the main region, while the window still gives a burst of new keys a short LRU life.
Comparing Eviction Policies
Costs below are on top of the expected-O(1) hash lookup that every policy does.
| policy | per-access cost | metadata per entry | scan resistance |
|---|---|---|---|
| LRU | O(1); every hit relinks a shared list | 2 pointers | none: a scan larger than the cache flushes it |
| CLOCK | hit O(1), sets one bit; eviction amortized O(1), worst case O(c) sweep | 1 bit (PostgreSQL: a small usage count) | none, same as LRU |
| LFU (count buckets) | O(1); a hit moves the key to the next bucket | a count + 2 pointers | strong, but never forgets old popularity |
| LFU-DA | O(log n) heap update | a count + a priority + heap position | strong; aging lets new keys in |
| ARC | O(1) | 2 pointers, plus ghost keys for up to c evicted entries | yes: scans pass through T1 only |
| W-TinyLFU | O(1): a few sketch counters + an SLRU relink | 2 pointers + about 8 bytes of sketch (Caffeine) | strong: one-hit keys fail admission |
To see the differences in hit rates, the next simulation runs a cache of 1,000 entries over 200,000 requests to 10,000 keys with Zipf-like popularity (key of rank r requested with probability proportional to 1/r^0.9). It compares three workloads: the Zipf requests alone; the same requests with a scan of 3,000 never-repeated keys after every 2,000 requests; and a shift halfway through, after which a different set of keys is hot. Hit rates count only the Zipf requests, since a scan can never hit. LRU here is an OrderedDict, which has the same eviction behaviour as Chapter 12’s hand-built version; ClockCache and LFUCache are the classes above.
import itertools
import random
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity, self.d = capacity, OrderedDict()
def get(self, key):
if key not in self.d:
return None
self.d.move_to_end(key)
return self.d[key]
def put(self, key, value):
self.d[key] = value
self.d.move_to_end(key)
if len(self.d) > self.capacity:
self.d.popitem(last=False)
N = 10_000 # keys 0..N-1 follow Zipf; keys >= N are scan keys
def workload(scan_len=0, shift=False, s=0.9, length=200_000, burst=2_000, seed=1):
rng = random.Random(seed)
cum = list(itertools.accumulate(1 / (r + 1) ** s for r in range(N)))
scan_keys = itertools.count(N) # a scan key is never requested again
trace = []
while len(trace) < length:
offset = N // 2 if shift and len(trace) >= length // 2 else 0
ranks = rng.choices(range(N), cum_weights=cum, k=burst)
trace += [(r + offset) % N for r in ranks] # the offset changes which keys are hot
trace += [next(scan_keys) for _ in range(scan_len)]
return trace
def hit_rate(cache, trace):
hits = 0
for key in trace:
if cache.get(key) is not None:
hits += key < N
else:
cache.put(key, True)
return hits / sum(key < N for key in trace)
for label, trace in [("Zipf only", workload()),
("Zipf + scans", workload(scan_len=3_000)),
("hot set shifts", workload(shift=True))]:
print(label, [round(hit_rate(c(1_000), trace), 3)
for c in (LRUCache, ClockCache, LFUCache)])
| workload | LRU | CLOCK | LFU |
|---|---|---|---|
| Zipf only | 0.554 | 0.541 | 0.627 |
| Zipf + scans | 0.454 | 0.453 | 0.615 |
| hot set shifts | 0.553 | 0.541 | 0.434 |
Three things show. CLOCK gives up about one point of hit rate against LRU, which is the price of the approximation, and in return a hit writes one bit instead of relinking a shared list. When popularity is fixed, LFU wins clearly: with independent requests from fixed probabilities, the best a cache can do is hold the most probable keys, and LFU’s counts estimate exactly those probabilities. The scans take ten points off LRU and CLOCK and barely touch LFU. But when the hot set moves, LFU loses 19 points and finishes last, because the old hot keys keep their large counts and the new ones are evicted on arrival. No policy in this table wins all three rows, which is the case for adaptive designs: ARC and W-TinyLFU both aim for LFU’s first two rows and LRU’s third.
29.7 Rate Limiting Data Structures
Rate limiting controls request throughput.
Token Bucket
class TokenBucket:
def __init__(self, rate, capacity):
self.rate = rate
self.capacity = capacity
self.tokens = capacity
self.last_update = time.time()
def allow(self, tokens=1):
now = time.time()
elapsed = now - self.last_update
self.tokens = min(
self.capacity,
self.tokens + elapsed * self.rate
)
self.last_update = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
Token bucket vs Leaky bucket: Token bucket allows burstiness up to capacity; leaky bucket outputs at constant rate.
Sliding Window Log
More accurate rate limiting:
class SlidingWindowLog:
def __init__(self, window_size, max_requests):
self.window_size = window_size
self.max_requests = max_requests
self.requests = [] # Timestamps of requests
def allow(self):
now = time.time()
# Remove old entries
self.requests = [
t for t in self.requests
if now - t < self.window_size
]
if len(self.requests) < self.max_requests:
self.requests.append(now)
return True
return False
Fixed window vs Sliding window vs Sliding log: Trade-offs between accuracy, memory, and implementation complexity.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
29.1 ★ Slab waste. Memcached’s slab allocator in §29.2 uses size classes that double: 64 B, 128 B, 256 B, and so on up to 1 MB. Items of 65 B, 129 B, 300 B and 1,000 B arrive. Which class does each go into, and how many bytes does each waste? What is the worst-case fraction of a slot that can be wasted with doubling classes, and what happens to it if the classes grow by a factor of 1.25 instead?
Solution
| item | class | wasted | wasted fraction |
|---|---|---|---|
| 65 B | 128 B | 63 B | 49% |
| 129 B | 256 B | 127 B | 50% |
| 300 B | 512 B | 212 B | 41% |
| 1,000 B | 1,024 B | 24 B | 2% |
The worst case is an item one byte larger than a class boundary, which lands in a slot twice its size: just under 50% waste. With growth factor f the worst case is just under 1 − 1/f, so f = 1.25 caps waste at about 20%. The price is more classes (about 3 times as many between 64 B and 1 MB), and memory assigned to one class’s slabs cannot easily serve another, so a workload whose item sizes shift over time can strand memory in classes it no longer uses. Memcached’s default growth factor is in fact 1.25.
29.2 ★ When to commit the offset. A Kafka consumer fetches offsets 100 to 109 from a partition, processes 100 to 104, and crashes. After restart it resumes from its last committed offset. What gets processed twice, and what never gets processed, if it (a) commits after processing the whole batch, or (b) commits 110 as soon as it fetches the batch?
Solution
(a) At-least-once. The last committed offset is still 100, so the restarted consumer re-reads 100 to 109. Records 100 to 104 are processed twice; nothing is lost. Processing must be idempotent (or deduplicated by offset) for the duplicates to be harmless.
(b) At-most-once. The committed offset is already 110, so the restarted consumer starts at 110. Records 105 to 109 are never processed; nothing is duplicated.
The offset is a single integer per partition per consumer group, so both behaviors come down to whether that integer is written before or after the side effects. Exactly-once requires the side effects and the offset commit to happen atomically, which is what Kafka transactions provide when the output also goes to Kafka.
29.3 ★★ Trace a token bucket. The TokenBucket in §29.7 is created at t = 0 with rate = 2 tokens per second and capacity = 5. Requests (one token each) arrive at t = 0 (five of them), t = 0.2, t = 1.0 (two), and t = 4.0 (six). Which are allowed? Give the token count after each time step.
Hint
Refill happens lazily, at the start of each allow call, and is capped at capacity. A denied request still updates last_update.
Solution
| time | tokens after refill | requests | allowed | tokens after |
|---|---|---|---|---|
| 0 | 5 | 5 | all 5 | 0 |
| 0.2 | 0 + 0.2 × 2 = 0.4 | 1 | denied | 0.4 |
| 1.0 | 0.4 + 0.8 × 2 = 2.0 | 2 | both | 0 |
| 4.0 | min(5, 0 + 3 × 2) = 5 | 6 | first 5, sixth denied | 0 |
At t = 4.0 the bucket would have earned 6 tokens but the cap keeps it at 5. That cap is the burst size: after any idle period, at most 5 requests go through at once, and after that the sustained rate is 2 per second. A leaky bucket with the same rate would have spread the t = 0 burst out over 2.5 seconds instead of admitting it.
29.4 ★★ A faster sliding window log. The SlidingWindowLog in §29.7 rebuilds its whole list on every call. What does allow cost per call? Rewrite it so that each call is amortized O(1), and check it against this trace: window 60 s, limit 3, requests at t = 0, 10, 20, 30, 60, 61, 70, 80 should give allowed, allowed, allowed, denied, allowed, denied, allowed, allowed.
Hint
Timestamps are appended in increasing order, so expired entries are always at the front.
Solution
The list comprehension scans every stored timestamp and allocates a new list, so each call costs O(L) for a limit of L requests per window, even when nothing has expired.
Because timestamps arrive in order, the expired ones form a prefix. A deque lets us drop them from the left in O(1) each. Each timestamp is appended once and popped at most once, so the total work over n calls is O(n): amortized O(1) per call.
from collections import deque
class SlidingWindowLog:
def __init__(self, window_size, max_requests, clock):
self.window_size = window_size
self.max_requests = max_requests
self.clock = clock
self.requests = deque() # timestamps, oldest on the left
def allow(self):
now = self.clock()
while self.requests and now - self.requests[0] >= self.window_size:
self.requests.popleft()
if len(self.requests) < self.max_requests:
self.requests.append(now)
return True
return False
t = [0.0]
lim = SlidingWindowLog(window_size=60, max_requests=3, clock=lambda: t[0])
results = []
for now in [0, 10, 20, 30, 60, 61, 70, 80]:
t[0] = now
results.append(lim.allow())
assert results == [True, True, True, False, True, False, True, True]
assert len(lim.requests) == 3
The clock is passed in so the trace can be tested deterministically. At t = 30 the window holds 0, 10, 20 and the request is denied. At t = 60, timestamp 0 is exactly 60 s old and drops out, so the request is allowed. At t = 70, timestamp 10 drops out.
Memory is still O(L) per client, which is the real cost of the sliding log (see the next exercise).
29.5 ★★ Probabilistic early expiration. The should_revalidate function in §29.6 refreshes an item early when now − delta × beta × ln(u) ≥ expires, where u is uniform on (0, 1]. Take delta = 1 s (the recomputation takes one second), beta = 1, and an item that expires at t = 100. What is the probability that a single request refreshes early at t = 97, at t = 99, and at t = 99.5? If 1,000 requests per second hit the key, roughly when will the first early refresh happen, and why does this prevent a stampede?
Solution
Let g = expires − now, the time remaining. A refresh happens when −delta × beta × ln(u) ≥ g, that is ln(u) ≤ −g/(delta × beta), that is u ≤ e^(−g/(delta × beta)). With delta = beta = 1:
| now | g | P(refresh) = e^(−g) |
|---|---|---|
| 97 | 3 | 0.050 |
| 99 | 1 | 0.368 |
| 99.5 | 0.5 | 0.607 |
At 1,000 requests per second, refreshes happen at a rate of about 1,000 × e^(−g) per second when g seconds remain. Integrating, the expected number of early refreshes before the remaining time falls to g is about 1,000 × e^(−g). That equals 1 at g = ln 1000 ≈ 6.9 s, and the first refresh has a median of about 7.3 s before expiry (where the expected count is ln 2). So in practice one request, around seven seconds early, does the refresh.
Without early expiration, every request arriving in the second after t = 100 misses, and all of them recompute at once: up to 1,000 concurrent recomputations of a value that takes a second to build. With it, one request refreshes well before expiry and resets expires, and everyone else keeps getting hits. Scaling by delta means expensive values start refreshing earlier, which is what you want, because a stampede on an expensive value hurts more.
29.6 ★★ Rate limiter memory at scale. You must limit 10 million users to 100 requests per minute each. Estimate the memory for (a) a sliding window log with 8-byte timestamps, (b) a token bucket storing two 8-byte numbers, (c) a fixed window counter. Fixed windows have a known flaw: give a request pattern that gets 200 requests through within about one second while never exceeding 100 in any single window.
Solution
(a) Sliding log: up to 100 timestamps × 8 B = 800 B per active user, so up to 8 GB for 10 million users, before any per-object or per-key overhead.
(b) Token bucket: tokens and last-update time, 16 B per user, 160 MB.
(c) Fixed window: a counter and a window start, also about 16 B per user, 160 MB.
The flaw: windows are aligned to clock minutes. A client sends 100 requests at 12:00:59.5, all admitted because the 12:00 window has room, and 100 more at 12:01:00.0, all admitted because the 12:01 window just started. That is 200 requests in half a second.
The sliding log is exact but costs 50 times the memory. The common compromise is the sliding window counter: keep the counts for the current and previous fixed windows and estimate the sliding count as current + previous × (fraction of the previous window still inside the sliding window). That is O(1) memory per user, like the fixed window, and removes most of the boundary burst, at the cost of assuming requests in the previous window were evenly spread. The token bucket is also O(1) and allows bursts only up to its capacity, which you choose.
29.7 ★★★ O(1) least connections. The LeastConnections balancer in §29.5 makes select an O(S) scan over S servers, and a min-heap would make updates O(log S). Use the fact that connection counts only change by ±1 to make select, add_request and remove_request all O(1). Implement it and test it against a brute-force minimum.
Hint
Group servers by their current count, as an O(1) LFU cache groups keys by frequency. When the minimum count changes, it can only move by one.
Solution
Keep a map from count to the set of servers with that count, plus the current minimum count. Incrementing moves a server from bucket c to bucket c + 1. If it was the last server in the minimum bucket, the new minimum is c + 1, because no server has a count between c and c + 1. Decrementing moves a server to c − 1, which becomes the minimum if it is below the old one. Every step is a constant number of hash-set operations.
class LeastConnections:
def __init__(self, servers):
self.count = {s: 0 for s in servers}
self.buckets = {0: set(servers)} # connection count -> servers
self.min_count = 0
def _move(self, server, old, new):
self.buckets[old].discard(server)
if not self.buckets[old]:
del self.buckets[old]
self.buckets.setdefault(new, set()).add(server)
self.count[server] = new
def select(self):
return next(iter(self.buckets[self.min_count]))
def add_request(self, server):
c = self.count[server]
self._move(server, c, c + 1)
if c == self.min_count and self.min_count not in self.buckets:
self.min_count = c + 1
def remove_request(self, server):
c = self.count[server]
self._move(server, c, c - 1)
if c - 1 < self.min_count:
self.min_count = c - 1
import random
lb = LeastConnections(["a", "b", "c", "d"])
active = []
for _ in range(10000):
if active and random.random() < 0.45:
lb.remove_request(active.pop(random.randrange(len(active))))
else:
s = lb.select()
assert lb.count[s] == min(lb.count.values())
lb.add_request(s)
active.append(s)
assert lb.min_count == min(lb.count.values())
Each operation does O(1) expected work (hash-set insert and delete), and the randomized test checks after every step that select returns a true minimum and that min_count matches a brute-force scan. This is the same trick that makes an LFU cache O(1): when keys change priority by exactly one step, a list of buckets replaces a heap.
29.8 ★★ Counting levels. §29.5 argues that with two choices the fraction βᵢ of bins with load at least i roughly squares at each level, starting from β₂ ≤ 1/2, while with one choice the fraction with load at least k is about 1/(e·k!). Use these to estimate the maximum load (the highest level whose expected number of bins is at least about 1) for n = 10⁶ and n = 10¹² balls in as many bins, with one choice and with two. How much does multiplying n by a million add in each case? The simulation measured a maximum of 4 for two choices at n = 10⁶; why does the estimate come out higher?
Hint
Write βᵢ as a power of two: β₂ = 2⁻¹, and squaring doubles the exponent. 10⁶ ≈ 2²⁰ and 10¹² ≈ 2⁴⁰.
Solution
Two choices: β₂ = 2⁻¹, β₃ = 2⁻², β₄ = 2⁻⁴, β₅ = 2⁻⁸, β₆ = 2⁻¹⁶, β₇ = 2⁻³², β₈ = 2⁻⁶⁴.
| n | n·β₆ | n·β₇ | n·β₈ | estimated max |
|---|---|---|---|---|
| 10⁶ | 15.3 | 0.0002 | 6 | |
| 10¹² | 1.5 × 10⁷ | 233 | 5 × 10⁻⁸ | 7 |
One choice: the expected number of bins with load at least k is about n/(e·k!).
| n | k = 9 | k = 10 | k = 14 | k = 15 | estimated max |
|---|---|---|---|---|---|
| 10⁶ | 1.01 | 0.10 | 9 | ||
| 10¹² | 4.2 | 0.28 | 14 |
Multiplying n by a million adds five levels with one choice and one level with two. That is the gap between log n / log log n and log log n: squaring n (10⁶ to 10¹²) adds one to log₂ log₂ n, while it multiplies ln n / ln ln n by about 1.6 (from 5.3 to 8.3).
The estimate for two choices is loose because β₂ = 1/2 is the worst case allowed by counting. In the simulation only 229,701 of 10⁶ bins (β₂ ≈ 0.23) reached load 2, and that is the value at the end; during most of the run β₂ was smaller still, and a ball reaches level 3 only if both of its choices were at level 2 at that moment. Starting the recurrence from the observed β₃ ≈ 0.009 gives n·β₃² ≈ 81 bins at level 4 (6 were observed) and n·β₄² far below 1 at level 5, which matches the measured maximum of 4. The one-choice estimate is accurate because the Poisson approximation is accurate: the simulation’s 562, 84 and 8 bins at loads of at least 6, 7 and 8 compare with 594, 83 and 10 predicted.
29.9 ★ When CLOCK becomes FIFO. A ClockCache(3) from §29.6 receives put a, put b, put c, get c, get b, get a, put d. Which key does it evict, and which would LRU evict? What does this say about how much recency information CLOCK keeps, and why do systems accept it?
Solution
After the three puts, a, b and c sit in slots 0, 1 and 2 with their bits set, and the hand is at slot 0. The three gets set bits that are already set. To insert d, the hand finds a’s bit set (clears it), then b’s (clears it), then c’s (clears it), returns to slot 0, finds a’s bit clear, and evicts a. LRU’s recency order after the gets is c (oldest), b, a (newest), so LRU evicts c. CLOCK evicted the most recently used key.
The reference bit records only “used since the hand last passed”, not when. When every entry has been used since the last sweep, the bits carry no information, and the sweep falls back to slot order, which is insertion order: FIFO. CLOCK’s recency resolution is one revolution of the hand.
Systems accept this because the hit path is what they optimise. Under memory pressure the hand moves often, so the bits are a fair proxy for “used recently”, and the occasional wrong choice costs one extra miss. True LRU would cost a list relink under a lock on every hit, which in an OS is not even possible (the hardware sets the accessed bit; no code runs on a hit). PostgreSQL’s usage count, incremented on each use up to 5 and decremented by each pass of the hand, partly restores the missing information by letting often-used buffers survive several passes.
29.10 ★★★ Make LFU forget. Implement LFUDACache(capacity) with the same get and put as LFUCache in §29.6, using dynamic aging: a cache-wide value L, initially 0, set to the priority of each evicted entry; an entry’s priority is L + count, recomputed with the current L whenever it is inserted or hit; ties go to the entry whose priority was set earliest. Make every operation O(log n) and keep memory O(n). Then trace a capacity-2 cache in which key a is put once and hit 9 times, followed by puts of new keys k1, k2, …: how many newcomers does it take to evict a? What would plain LFU do?
Hint
Use heapq and do not try to update entries inside the heap. Push a new item whenever a priority changes and skip stale items when popping. To keep memory O(n), rebuild the heap from the live items when it grows past a constant multiple of the capacity.
Solution
import heapq
import itertools
class LFUDACache:
"""LFU with dynamic aging: priority = L + count, L = priority of the last victim."""
def __init__(self, capacity):
self.capacity = capacity
self.L = 0
self.entry = {} # key -> [value, count, stamp of its live heap item]
self.heap = [] # (priority, stamp, key); stale items are skipped
self.stamps = itertools.count()
def _push(self, key):
e = self.entry[key]
e[2] = next(self.stamps)
heapq.heappush(self.heap, (self.L + e[1], e[2], key))
if len(self.heap) > 2 * self.capacity + 16: # drop stale items
self.heap = [item for item in self.heap
if item[2] in self.entry and self.entry[item[2]][2] == item[1]]
heapq.heapify(self.heap)
def get(self, key):
e = self.entry.get(key)
if e is None:
return None
e[1] += 1
self._push(key)
return e[0]
def put(self, key, value):
if key in self.entry:
self.entry[key][0] = value
self.get(key)
return
if len(self.entry) == self.capacity:
while True:
priority, stamp, victim = heapq.heappop(self.heap)
if victim in self.entry and self.entry[victim][2] == stamp:
break
self.L = priority # newcomers now start at L + 1
del self.entry[victim]
self.entry[key] = [value, 1, None]
self._push(key)
c = LFUDACache(2)
c.put("a", 1)
for _ in range(9):
c.get("a") # count 10, priority 10
n = 0
while "a" in c.entry:
n += 1
c.put(f"k{n}", n)
assert n == 11 and c.L == 10
Each item carries a stamp, and an item is live only if its stamp matches the one stored in the entry, so stale items left by earlier hits are recognised and skipped. The stamp also breaks priority ties in favour of the item pushed earliest. A push is O(log n). The rebuild costs O(n), but it runs only after the heap has gained about n + 16 items since the last rebuild, so its amortized cost per push is O(1). Each pop is O(log n), and each item is popped at most once, so the skipping is paid for by the pushes. All operations are therefore O(log n) amortized, and the heap never holds more than 2n + 17 items.
The trace: a has priority 10. k1 fills the free slot with priority 0 + 1 = 1. k2 evicts k1, so L = 1 and k2 gets 2; in general k_j evicts k_(j−1), sets L = j − 1 and enters with priority j. k10 enters with priority 10, tied with a. k11 must evict one of them, the tie goes to a, whose priority was set earlier, and a is gone after 11 newcomers. Plain LFU never evicts a in this trace: every newcomer has count 1 and is always the minimum, so a, hit 10 times long ago, stays forever.
Run through the simulation in §29.6, LFU-DA scores 0.607, 0.502 and 0.582 on the three workloads, against LFU’s 0.627, 0.615 and 0.434. Aging buys back most of the loss when the hot set shifts and costs some of LFU’s scan resistance, because each eviction of a scan key raises L and lets newer scan keys outrank hot keys whose counts have not grown lately. A brute-force reference that recomputes the minimum (priority, time set) by scanning all entries agrees with this class on random operation sequences.
Where this connects
- Chapter 10: Multiway Search Trees and B-Trees. The B-trees inside every storage engine described here
- Chapter 12: Hash Tables. The hash map plus linked list that every LRU cache in §29.6 is built from
- Chapter 14: Probabilistic Data Structures. The probabilistic structures these systems rely on
Chapter 30: Advanced System Patterns and Case Studies
30.1 Search Infrastructure: Inverted Index
Full-text search engines use inverted indexes for efficient keyword lookups.
Inverted Index Structure
Document collection:
Doc1: "data structures are fundamental"
Doc2: "data structures enable efficient algorithms"
Forward index (doc → terms):
Doc1 → ["data", "structures", "are", "fundamental"]
Doc2 → ["data", "structures", "enable", "efficient", "algorithms"]
Inverted index (term → docs):
"data" → [Doc1, Doc2]
"structures"→ [Doc1, Doc2]
"are" → [Doc1]
"fundamental" → [Doc1]
"enable" → [Doc2]
"efficient" → [Doc2]
"algorithms"→ [Doc2]
Posting list: Each term points to a sorted list of document IDs.
Real postings carry more than the ID: the term frequency in that document (BM25 needs it, below) and often the positions of each occurrence (for phrase queries). The ID part is the hard part to make small and fast, and the rest of this section is about it: how the lists are compressed, how two of them are intersected, how the best k documents are found without scoring every match, and how an index made of immutable compressed lists absorbs inserts and deletes.
Compressing Posting Lists
A common term in a large index has a posting list of hundreds of millions of doc IDs, and a query reads every posting it touches. Stored as 32-bit integers, most of those bits are wasted, because the list is sorted: the information is in the distance from one ID to the next.
Step 1: d-gaps (delta encoding). Replace each ID by its difference from the previous one, keeping the first as it is. The gaps of a list sum to its last ID, so a term that appears in a fraction f of the documents has an average gap of about 1/f: a term in 10% of documents has gaps around 10, which fit in 4 bits. Rare terms have large gaps, but their lists are short, so they cost little either way. Decoding is a running sum, which means a list can only be decoded forward from a known starting point (its beginning, or a block boundary recorded in the skip data below).
Step 2: variable-byte (varint) encoding. Write each gap 7 bits at a time, lowest-order group first, and use the top bit of each byte as a continuation flag: 1 means another byte of this number follows, 0 means this is the last. Values below 128 take one byte, below 16,384 two, below 2,097,152 three. This is the layout of Lucene’s VInt, the varint of Protocol Buffers, and LEB128 in DWARF and WebAssembly. (The variable-byte code in Manning, Raghavan and Schütze’s Introduction to Information Retrieval puts the flag on the last byte instead and writes the high-order group first; the idea and the sizes are the same.)
The worked example in the figure: the term “data” occurs in documents 70000, 70003, 70010, 70130 and 90000. The gaps are 70000, 3, 7, 120 and 19870. The first gap is 17 bits, 100 0100010 1110000 in binary, so it splits into three 7-bit groups; emitted lowest first with the flag prepended, they are 1·1110000 = F0, 1·0100010 = A2 and 0·0000100 = 04. The gaps 3, 7 and 120 are below 128 and take one byte each (03, 07, 78), and 19870 takes three (9E 9B 01). Total: 9 bytes, against 20 as 32-bit integers and 15 as varints of the raw IDs, since every raw ID here is at least 16,384.
from itertools import accumulate
def delta_encode(doc_ids, base=0):
"""Sorted doc IDs -> d-gaps. The first gap is measured from `base`."""
return [d - p for p, d in zip([base] + doc_ids, doc_ids)]
def delta_decode(gaps, base=0):
return list(accumulate(gaps, initial=base))[1:]
def varint_encode(numbers):
"""7 data bits per byte, low-order group first; a set high bit means 'more bytes follow'."""
out = bytearray()
for n in numbers:
while n >= 0x80:
out.append((n & 0x7F) | 0x80)
n >>= 7
out.append(n)
return bytes(out)
def varint_decode(data):
numbers, n, shift = [], 0, 0
for byte in data:
n |= (byte & 0x7F) << shift
if byte & 0x80:
shift += 7
else:
numbers.append(n)
n, shift = 0, 0
return numbers
postings = [70000, 70003, 70010, 70130, 90000]
gaps = delta_encode(postings)
assert gaps == [70000, 3, 7, 120, 19870]
encoded = varint_encode(gaps)
assert encoded.hex(" ") == "f0 a2 04 03 07 78 9e 9b 01"
assert len(encoded) == 9 and len(varint_encode(postings)) == 15 # vs 20 bytes as int32
assert delta_decode(varint_decode(encoded)) == postings
Encoding and decoding are O(total bytes), linear in the list. A 32-bit gap takes at most 5 bytes.
Bit-packing in blocks. Varint has two weaknesses: it cannot use less than a byte (a gap of 3 still takes 8 bits), and its decoder takes a data-dependent branch on every byte, which the CPU mispredicts often when gap sizes vary. Modern engines instead cut the gap sequence into fixed-size blocks and pack each block at one bit width b, the width of the block’s largest gap. A block of 128 gaps then takes exactly 16b bytes, and unpacking it is straight-line shifts and masks with no branches, which compilers unroll and vectorize with SIMD instructions. This is frame-of-reference (FOR) coding: each value is stored as a fixed-width offset from a per-block reference value; for d-gaps the reference is 0 and the choice of b is the whole scheme. Its weakness is outliers: one large gap forces every value in the block to the wide width. PForDelta (“patched” FOR, Zukowski, Héman, Nes and Boncz, 2006) picks b so that most of the block fits, say 90%, and stores the few values that do not fit as exceptions that are patched in after the fast unpacking pass. Lucene’s postings format packs doc-ID gaps in blocks of 128 at one bit width per block, uses patched FOR for the term frequencies, and writes the final partial block of fewer than 128 entries as VInts.
def for_pack(block):
"""Frame of reference: every value in the block is stored in the same b bits."""
b = max(block).bit_length()
packed = 0
for i, v in enumerate(block):
packed |= v << (i * b)
return b, packed.to_bytes((len(block) * b + 7) // 8, "little")
def for_unpack(b, data, count):
packed, mask = int.from_bytes(data, "little"), (1 << b) - 1
return [(packed >> (i * b)) & mask for i in range(count)]
block = [3, 7, 1, 12, 5, 2, 9, 4] * 16 # 128 small gaps
b, data = for_pack(block)
assert (b, len(data)) == (4, 64) # 4 bits each: 64 bytes
assert for_unpack(b, data, len(block)) == block
b, data = for_pack(block[:-1] + [19870]) # one outlier...
assert (b, len(data)) == (15, 240) # ...and all 128 values pay 15 bits
The Python uses one arbitrary-precision integer as the bit buffer to stay short; real implementations shift values into 64-bit words, and Lucene generates a specialized unpacking routine for each width b.
Why compression makes queries faster, not only smaller. Intersecting or scoring a posting list does a few instructions per doc ID, so a scan over uncompressed IDs is limited by how fast bytes arrive from memory or disk, not by the CPU. Compression spends a few cheap instructions per ID to move several times fewer bytes, and lets more of the index stay in the CPU caches and in RAM (the operating system’s page cache, for an index on disk). Block bit-packing decoders run at billions of integers per second per core (Lemire and Boytsov, “Decoding billions of integers per second through vectorization”, 2015), so decoding costs less than the memory traffic it saves, and the smaller list is also the faster one. This is the memory-hierarchy argument of Chapter 16 applied to lists of integers.
Intersecting Posting Lists
An AND query (“fibonacci AND heap”) needs the doc IDs that appear in every query term’s list. Exercise 30.1 builds the linear merge: two pointers walk both sorted lists, always advancing the one at the smaller ID, for O(m + n) comparisons in the worst case. That is the right algorithm when the lists have similar lengths and the wrong one when they do not: for “fibonacci AND the”, with m = 1,000 and n = 10,000,000 postings, the merge reads the entire long list to find at most 1,000 matches.
Galloping (exponential) search. Walk the short list, and for each element x, search the long list forward from where the previous search stopped: probe positions lo, lo + 1, lo + 3, lo + 7, …, doubling the step, until a probe reaches a value ≥ x, then binary-search the last interval (Bentley and Yao, 1976, proposed this doubling search for unbounded lists).
from bisect import bisect_left
def gallop_to(arr, target, lo=0):
"""Smallest i >= lo with arr[i] >= target, or len(arr).
Probes lo, lo+1, lo+3, lo+7, ... then binary-searches the last gap."""
hi, step = lo, 1
while hi < len(arr) and arr[hi] < target:
lo = hi + 1 # everything before lo is < target
hi += step
step *= 2
return bisect_left(arr, target, lo, min(hi, len(arr)))
def intersect_gallop(short, long):
"""Each element of `short` gallops forward from where the last one stopped."""
out, pos = [], 0
for x in short:
pos = gallop_to(long, x, pos)
if pos == len(long):
break
if long[pos] == x:
out.append(x)
return out
def intersect_all(lists):
"""AND query: start from the rarest term; the candidate set only shrinks."""
lists = sorted(lists, key=len)
result = lists[0]
for other in lists[1:]:
if not result:
break
result = intersect_gallop(result, other)
return result
long = [2, 5, 9, 12, 17, 21, 30, 44, 51, 63, 70, 88, 95, 120]
assert gallop_to(long, 63) == 9 # probes 0, 1, 3, 7 (15 is past the end), then bisects [8, 14)
assert intersect_all([long, [9, 63, 64], list(range(0, 100, 3))]) == [9, 63]
In the test, searching for 63 probes indices 0, 1, 3 and 7 (values 2, 5, 12, 44, all below 63), the next probe 15 is past the end, so it binary-searches indices 8 to 13 and stops at index 9.
Cost. Say the search for the i-th element of the short list moves the long-list position forward by g_i. Doubling reaches past that distance in about log₂ g_i probes, and the binary search over the last interval, of length below g_i, takes about log₂ g_i more, so the search costs O(1 + log g_i). The g_i sum to at most n, and since log is concave, a sum of m logarithms with a fixed total is largest when all the terms are equal, at n/m. The total is O(m log(n/m) + m) comparisons in the worst case. For m = 1,000 and n = 10⁷ that is about 1,000 × 2 × log₂(10⁴) ≈ 27,000 comparisons instead of 10⁷. When m ≈ n the gaps are tiny, each search is a probe or two, and galloping costs O(n), within a small constant factor of the merge, so it never loses badly.
Shortest list first. With more than two terms, intersect_all sorts the lists by length and folds the result through them. The running result can never be longer than the shortest list, so every step is a short list galloping through a longer one. The lengths are free: the term dictionary stores each term’s document frequency, because BM25 needs it as n.
Skip pointers. Galloping assumes random access, and a compressed list does not have it: varints have variable length, and d-gaps decode only as a running sum from a known starting point. The fix is skip data: for every block of B postings, record the block’s last doc ID and the byte offset where the block starts. To advance to a target x, search the small, uncompressed array of skip entries, jump to the one block that can contain x, and decode only that block. Blocks with no candidate are never decoded at all. Moffat and Zobel (1996) placed skips every √n postings or so; in block-packed formats the skip interval is simply the block size, and Lucene interleaves skip data with its 128-posting blocks, with a second, coarser level above it.
from bisect import bisect_left
class CompressedPostings:
"""Doc IDs as varint d-gaps in blocks of `block`, plus one skip entry per
block: the block's last doc ID and the byte offset where it starts."""
def __init__(self, doc_ids, block=128):
self.data, self.last_docs, self.offsets = bytearray(), [], []
prev = 0
for i in range(0, len(doc_ids), block):
chunk = doc_ids[i:i + block]
self.offsets.append(len(self.data))
self.data += varint_encode(delta_encode(chunk, base=prev))
prev = chunk[-1]
self.last_docs.append(prev)
self.offsets.append(len(self.data))
self.blocks_decoded = 0
def decode_block(self, k):
self.blocks_decoded += 1
base = self.last_docs[k - 1] if k else 0
raw = self.data[self.offsets[k]:self.offsets[k + 1]]
return delta_decode(varint_decode(raw), base)
def intersect(self, short):
"""Decode only the blocks that could hold an element of `short`."""
out, k, block_no, docs = [], 0, -1, []
for x in short:
k = bisect_left(self.last_docs, x, k) # skip whole blocks
if k == len(self.last_docs):
break
if k != block_no:
block_no, docs = k, self.decode_block(k)
i = bisect_left(docs, x)
if docs[i] == x:
out.append(x)
return out
common = list(range(0, 1_000_000, 3)) # in a third of all documents
rare = [7, 300_000, 300_003, 999_999] # in four documents
pl = CompressedPostings(common)
assert pl.intersect(rare) == [300_000, 300_003, 999_999]
assert len(pl.data) == 333_334 # 1 byte per gap, vs 1,333,336 as int32
assert len(pl.last_docs) == 2605 and pl.blocks_decoded == 3
The rare term’s four IDs cost four searches of the skip array and three block decodes out of 2,605 blocks (300,000 and 300,003 share a block); the other 2,602 blocks are never decoded. With m short-list elements, the cost is O(m log(n/B)) for the skip searches (less if they gallop over the skip array instead of calling bisect) plus O(B) for each decoded block, and at most min(m, n/B) blocks are decoded. The len(pl.data) assertion is the compression side of the same example: a term in every third document out of a million has gaps of 3, one byte each, so the list takes a quarter of its 32-bit size.
BM25 Scoring
Probabilistic relevance ranking:
Score(D, Q) = Σ IDF(qi) × (tf × (k1 + 1)) / (tf + k1 × (1 - b + b × |D|/avgdl))
Where:
- tf = term frequency in document
- |D| = document length
- avgdl = average document length
- k1 = term frequency saturation (typically 1.2-2.0)
- b = length normalization (typically 0.75)
- IDF = log((N - n + 0.5) / (n + 0.5))
Top-k Retrieval: WAND and Block-Max WAND
A search page shows the k best documents by score, not every match, and for an OR query (“fibonacci heap data”) nearly every document matches some term. Exhaustive evaluation scores every document in the union of the posting lists and keeps the best k in a size-k min-heap, the top-k pattern of Chapter 9 §9.8. Its cost is proportional to the total length of all the lists, and that total is dominated by the common terms, which contribute least to any score.
The heap supplies the key quantity: the score θ of the current k-th best document, at its root. A new document matters only if it scores more than θ. WAND (“weak AND”, Broder, Carmel, Herscovici, Soffer and Zien, 2003) adds one number per term, computed at index time: the upper bound UB_t, the largest score contribution term t makes to any document. (BM25’s contribution is bounded for each term; Exercise 30.2(a) computes the limit.) A document’s score is at most the sum of UB_t over the terms whose lists contain it. WAND keeps one cursor per term, pointing at its current doc ID, and repeats:
- Sort the cursors by current doc ID.
- Add up UB_t in that order until the sum exceeds θ. The cursor where that happens is the pivot, and its doc ID is the pivot document p. If no prefix exceeds θ, stop: no remaining document can enter the top k.
- A document d < p can only appear in the lists of cursors before the pivot (every other cursor is already past d), and those bounds sum to at most θ. So no document before p can qualify. If some cursors are still before p, move them directly to p, using skip pointers, so the postings in between are never decoded.
- Otherwise every cursor up to the pivot is on p: score p in full, and push it into the heap if it beats θ.
The answer is exactly the exhaustive top k, not an approximation, because WAND only skips documents it has proved cannot qualify. As the heap fills with good documents θ rises, and more is skipped.
import heapq
from bisect import bisect_left
def wand_top_k(index, k):
"""index: term -> (doc_ids, scores), the term's posting list with each
document's precomputed score contribution. Returns the top k (score, doc)."""
ub = {t: max(sc) for t, (_, sc) in index.items()} # stored at index time
pos = {t: 0 for t in index}
heap = [] # min-heap of (score, doc)
fully_scored = 0
def cur(t):
docs = index[t][0]
return docs[pos[t]] if pos[t] < len(docs) else float("inf")
while True:
theta = heap[0][0] if len(heap) == k else float("-inf")
terms = sorted(index, key=cur)
pivot, bound = None, 0.0
for t in terms: # smallest prefix that could beat theta
if cur(t) == float("inf"):
break
bound += ub[t]
if bound > theta:
pivot = cur(t)
break
if pivot is None:
break # no remaining document can enter the top k
if cur(terms[0]) == pivot: # every term up to the pivot is on it
score = 0.0
for t in terms:
if cur(t) == pivot:
score += index[t][1][pos[t]]
pos[t] += 1
fully_scored += 1
if len(heap) < k:
heapq.heappush(heap, (score, pivot))
elif score > theta:
heapq.heapreplace(heap, (score, pivot))
else: # nothing before the pivot can win: skip
for t in terms:
if cur(t) < pivot:
pos[t] = bisect_left(index[t][0], pivot, pos[t])
return sorted(heap, reverse=True), fully_scored
index = {
"fibonacci": ([3, 9], [4.0, 3.5]),
"heap": ([1, 3, 5, 7, 9, 11], [1.5, 2.0, 1.0, 1.8, 1.2, 2.0]),
"data": (list(range(1, 13)), [0.5] * 12),
}
top, fully_scored = wand_top_k(index, k=2)
assert top == [(6.5, 3), (5.2, 9)] and fully_scored == 6 # docs 1, 2, 3, 5, 7, 9
The trace of that example, with k = 2:
| term | doc IDs | score contribution | UB |
|---|---|---|---|
| fibonacci | 3, 9 | 4.0, 3.5 | 4.0 |
| heap | 1, 3, 5, 7, 9, 11 | 1.5, 2.0, 1.0, 1.8, 1.2, 2.0 | 2.0 |
| data | 1 to 12 | 0.5 each | 0.5 |
Docs 1 (score 2.0) and 2 (0.5) fill the heap, so θ = 0.5. Doc 3 scores 6.5 and evicts doc 2: θ = 2.0. The cursors are now data at 4, heap at 5, fibonacci at 9. The bound of data alone is 0.5 ≤ 2.0, data plus heap is 2.5 > 2.0, so the pivot is heap’s cursor and p = 5: data jumps from 4 to 5, and doc 4 is never scored (it contains only “data”, worth at most 0.5). Doc 5 scores 1.5 and does not get in. Doc 6 is skipped the same way, doc 7 scores 2.3 and evicts doc 1 (θ = 2.3), doc 8 is skipped, and doc 9 scores 5.2 (θ = 5.2). Now fibonacci is exhausted and data plus heap is 2.5 ≤ 5.2: no remaining document can reach the top 2, so WAND stops. It fully scored 6 of the 12 matching documents; docs 10, 11 and 12 were never touched, although doc 11 matches two of the three terms.
Block-max WAND. The weakness of WAND is that UB_t is a maximum over the whole list: if “heap” scores 2.0 in one document, every “heap” posting looks as if it could be worth 2.0. Block-max WAND (Ding and Suel, 2011) also stores the maximum score within each block of postings, next to that block’s skip entry. After WAND picks a pivot with the global bounds, it adds up the block maxima of the blocks containing p in the pivot terms’ lists. If that tighter bound is still ≤ θ, no document from p up to the nearest of those block ends (or up to the next cursor after the pivot, if that comes first) can qualify, so the cursors skip there without decoding anything. Lucene 8.0 (2019) added block-max WAND, storing per-block “impacts” in the skip data (the competitive pairs of term frequency and document length, from which a block’s maximum BM25 score follows). The price of skipping is that the engine no longer knows the exact number of matching documents; Elasticsearch 7.0 changed its default to count hits exactly only up to 10,000 for this reason.
WAND has no better worst-case bound than exhaustive evaluation: if every document scores close to θ, nothing can be skipped. Its gains depend on the score distribution, and on real queries, where a few documents score far above the rest, θ rises fast and most postings of the common terms are skipped.
Segments, Merging, and Deletes
Everything so far describes a static index: sorted, compressed, block-packed lists with skip data and block maxima. That layout cannot absorb an insert in the middle of a packed block. Lucene’s answer (and so that of Elasticsearch, OpenSearch and Solr, which are built on it) is the same as the LSM tree’s in Chapter 29 §29.4 and Chapter 16 §16.4: never modify anything in place; write new immutable pieces and merge them in the background.
- Segments. A segment is a complete, self-contained inverted index over a subset of the documents: its own term dictionary, compressed posting lists and stored fields, with doc IDs 0 to n − 1 local to the segment. Dense local IDs are also what keeps the d-gaps small. New documents are buffered in memory and flushed as a new, small segment; in Elasticsearch this is the refresh, every second by default, which is what makes a new document searchable within a second (“near-real-time” search). A query runs against every segment and combines the per-segment results; a document’s global ID is its segment’s base offset plus its local ID.
- Deletes as bitsets. A segment’s files are never rewritten, so a delete cannot remove postings. Instead each segment has a live-docs bitset (Chapter 3 §3.5) with one bit per document, written as a new generation of a small file when deletes arrive. Queries still decode the postings of deleted documents and drop them with one bit test each. An update is a delete of the old version plus an add of the new one, which lands in a new segment.
- Merging. A background merge reads several segments and writes one. It merges their sorted term dictionaries (a k-way merge, Chapter 9 §9.8), and for each term concatenates the posting lists while renumbering doc IDs: each source segment’s documents get a new base offset, deleted documents are dropped, and later IDs shift down to fill the holes. Each source segment’s documents become one contiguous range of IDs in the result, so the concatenated lists are already sorted and the merge is a single sequential pass, linear in the size of its input. Lucene’s default
TieredMergePolicymerges segments of similar size (by default it tolerates about 10 segments per size tier), so each document is rewritten a logarithmic number of times over the life of the index, as in a size-tiered LSM tree, and it favors segments with many deletions, because a merge is the only way to reclaim their space.
| LSM tree (Chapter 29) | Lucene index |
|---|---|
| memtable | in-memory indexing buffer |
| immutable SSTable | immutable segment |
| compaction | segment merge |
| delete = tombstone written to a newer run | delete = bit cleared in the live-docs bitset of the segment that holds the document |
| point read checks runs newest first and can stop early | every query visits every segment |
The last two rows differ because of the access pattern. A key-value read wants the newest version of one key, so an LSM tree records a delete as a tombstone in the newest run and resolves versions at read time. A search reads all the matching documents in all the segments anyway, so Lucene resolves the delete once, when the buffered deletes are applied, by finding the document in the older segments and clearing its bit; after that a query needs only a bit test and never compares versions across segments. The cost pressure differs too: an LSM point read can stop at the first run that holds the key (and skip most runs with Bloom filters), but a search pays for every segment on every query. Keeping the segment count small is therefore as much about query latency as about disk space, and an index that will not change again is often force-merged down to a single segment.
Fenced and Sharded Indexes
Sharding by document: Different shards contain different documents. Parallel query all shards, merge results.
Sharding by term (router): One shard responsible for a term range. Queries routed based on first term. Problem: hot terms cause imbalance.
30.2 Recommendation System Data Structures
Collaborative Filtering with Matrix Factorization
User-item matrix decomposition:
R ≈ U × V^T
R: m×n user-item rating matrix
U: m×k user latent factors
V: n×k item latent factors
k: latent dimension (typical 50-200)
Alternating Least Squares (ALS):
def als(R, k, iterations, reg=0.1):
"""`reg` is the L2 regularization weight, spelled `lambda` in the papers,
which is a reserved word in Python."""
m, n = R.shape
U = random(m, k)
V = random(n, k)
I = identity(k)
for _ in range(iterations):
# Fix U, solve for V
for j in range(n):
users = R[:, j].nonzero()
V[j] = solve(
U[users].T @ U[users] + reg * I,
U[users].T @ R[users, j]
)
# Fix V, solve for U
for i in range(m):
items = R[i, :].nonzero()
U[i] = solve(
V[items].T @ V[items] + reg * I,
V[items].T @ R[i, items].T
)
return U, V
Approximate Nearest Neighbors
Vector search for embedding similarity:
class HNSW:
def __init__(self, m=16, ef_construction=200):
self.m = m
self.ef = ef_construction
self.mL = 1 / log(m) # level multiplier from the HNSW paper
self.graph = {} # node_id -> [neighbors]
self.layers = [] # layer -> [node_ids]
def insert(self, vector, max_layers=6):
# Random layer selection (geometric): P(level >= l) = m ** -l
level = min(int(-log(random()) * self.mL), max_layers - 1)
# (Greedy ef=1 descent through the layers above `level` omitted.)
# On each layer from `level` down to 0, search with ef_construction
for l in reversed(range(level + 1)):
candidates = self._search_layer(vector, ef=self.ef, layer=l)
# Connect to the m nearest candidates
self._connect(vector, candidates, l)
ANN benchmarks: HNSW, ScaNN, DiskANN, FAISS. Trade-offs: query speed vs recall vs memory.
30.3 Time Series Databases
Time series data requires specialized structures for append-heavy workloads and time-range queries.
Columnar Storage with Time Partitioning
Partitioning scheme:
/data/year=2024/month=01/day=15/hour=12/
segment_000.parquet
segment_001.parquet
segment_002.parquet
Within segment (columnar):
| timestamp | cpu | memory | disk_io |
| 1705312800 | 45 | 32 | 1200 |
| 1705312801 | 47 | 31 | 1150 |
Benefits:
- Columnar: Efficient aggregation (only read needed columns)
- Time partitioning: Prune irrelevant partitions
- Segment size: Balance between query efficiency and write buffering
Downsampling and Aggregation
Tiered storage: Raw data → Downsampled → Long-term retention
Raw (second precision) → 1 hour rollup → 1 day rollup → 1 month rollup
Retention: 1 week 6 months 2 years forever
Aggregation algorithms:
- LTTB: Largest Triangle Three Buckets for visual fidelity
- Min/max sketches: Approximate aggregates with space efficiency
30.4 Event Sourcing and CQRS
Event sourcing stores state as a sequence of events rather than current state.
Event Store Structure
class EventStore:
def __init__(self):
self.streams = {} # aggregate_id -> [event]
def append(self, aggregate_id, event):
self.streams.setdefault(aggregate_id, []).append(event)
def get_stream(self, aggregate_id, from_version=0):
return self.streams.get(aggregate_id, [])[from_version:]
def rebuild_state(self, aggregate_id):
state = {}
for event in self.get_stream(aggregate_id):
state = apply_event(state, event)
return state
Benefits: Complete audit trail, temporal queries, easy replay for debugging.
Challenges: Event schema evolution, eventual consistency, query complexity.
CQRS (Command Query Responsibility Segregation)
Separate read and write models:
Command side (write):
- Handle commands (not queries)
- Aggregate events into state
- Publish to event bus
Query side (read):
- Maintain read models optimized for specific queries
- Subscribe to events for projection updates
- Materialized views for fast access
30.5 Sharding Patterns
Horizontal partitioning across multiple databases.
Consistent Hash Ring with Virtual Nodes
Virtual node mapping:
Physical Node A → VNode_1, VNode_5, VNode_12, VNode_23
Physical Node B → VNode_3, VNode_8, VNode_15, VNode_19
Physical Node C → VNode_2, VNode_11, VNode_17, VNode_24
Shard calculation:
vnode = hash(key) % NUM_VNODES (fixed for the life of the cluster)
owner = vnode_owner[vnode]
Rebalancing: A new node takes over whole vnodes from existing nodes, and only the keys in those vnodes move: about 1/(n+1) of the data when growing from n to n+1 nodes. The vnode count controls how evenly load spreads, not how much data moves.
Skip Hash for Hot Data
Hot data (top 1% of access):
- Replicated 3-5x across nodes
- Stored in memory or fast SSDs
Warm data (next 19%):
- Partitioned across cluster
- Standard replication factor (3)
Cold data (bottom 80%):
- Archived to cheaper storage
- Reduced replication (2)
- Accessed rarely
30.6 Consistency Patterns in Practice
Saga Pattern for Distributed Transactions
Choreography vs orchestration:
Choreography (event-driven):
OrderCreated → InventoryReserve → PaymentCapture → OrderConfirmed
↓ ↓ ↓
(rollback) (rollback) (rollback)
Orchestration (centralized):
Saga Orchestrator:
1. Send ReserveInventory
2. Receive InventoryReserved
3. Send CapturePayment
4. Receive PaymentCaptured
5. Send ConfirmOrder
(On failure, send compensating transactions)
Two-Phase Commit (2PC)
Distributed transaction protocol:
Phase 1 - Prepare:
1. Coordinator asks all participants to prepare
2. Participants vote Yes/No (locks resources)
3. If all Yes, proceed to commit; otherwise abort
Phase 2 - Commit:
1. Coordinator sends commit to all participants
2. Participants apply changes, release locks
3. Coordinator confirms completion
Problems: Blocking, coordinator failure, latency.
30.7 Observability Data Structures
Distributed Tracing
Span graph for request flow:
class Span:
def __init__(self, name, trace_id, span_id, parent_id=None):
self.name = name
self.trace_id = trace_id
self.span_id = span_id
self.parent_id = parent_id
self.start_time = time.time()
self.end_time = None
self.tags = {}
self.annotations = []
def finish(self):
self.end_time = time.time()
def duration_ms(self):
return (self.end_time - self.start_time) * 1000
Trace assembly: Child spans attached to parents via span_id/parent_id. Hierarchical tree represents causal relationship.
Metric Aggregation
Time-series aggregation with downsampling:
Raw metrics (every 10s):
[23, 25, 22, 28, 24, ...]
1-minute rollup:
avg: 24.4, max: 28, min: 22, p50: 24, p95: 27, p99: 28
1-hour rollup:
avg: 24.1, max: 45 (spike during incident), p99: 38
Cardinality management: High-cardinality labels (user IDs, request IDs) must be aggregated before storage.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
30.1 ★ Answer a Boolean query. Add a third document, Doc3: “efficient data pipelines”, to the collection in §30.1. Write the posting lists for “data”, “structures”, “efficient” and “pipelines” (document IDs 1, 2, 3). Then write a function that intersects two sorted posting lists, and use it to answer “data AND efficient” and “structures AND pipelines”. What does the intersection cost?
Solution
Posting lists: data → [1, 2, 3], structures → [1, 2], efficient → [2, 3], pipelines → [3].
Because both lists are sorted, two pointers can walk them together, always advancing the one pointing at the smaller ID:
def intersect(a, b):
"""Intersect two sorted posting lists in O(len(a) + len(b))."""
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
out.append(a[i])
i += 1
j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
return out
index = {
"data": [1, 2, 3],
"structures": [1, 2],
"efficient": [2, 3],
"pipelines": [3],
}
assert intersect(index["data"], index["efficient"]) == [2, 3]
assert intersect(index["structures"], index["pipelines"]) == []
“data AND efficient” returns [2, 3]; “structures AND pipelines” returns []. The cost is O(|a| + |b|) comparisons. When one list is far shorter than the other (a rare term AND a common one), searching the long list for each element of the short one, by binary search or galloping, costs O(|short| × log |long|) instead, which is why engines intersect the rarest term first and store skip pointers in long posting lists.
30.2 ★★ Compute a BM25 score. A collection has N = 1,000 documents with average length avgdl = 200 terms. The query term “trie” appears in n = 10 documents. Document D has |D| = 100 terms and contains “trie” tf = 3 times. With k1 = 1.2 and b = 0.75, compute the IDF, the term-frequency factor, and the score, using the natural log. Then answer: (a) what is the largest score this term can contribute however large tf gets, for a document of this length? (b) What happens to the score if D were 400 terms long? (c) What IDF does a term found in 600 of the 1,000 documents get, and why is that a problem?
Hint
Compute the length normalization 1 − b + b × |D|/avgdl first; it multiplies k1 in the denominator.
Solution
IDF = ln((1000 − 10 + 0.5) / (10 + 0.5)) = ln(990.5 / 10.5) = ln(94.33) ≈ 4.547.
Length normalization: 1 − 0.75 + 0.75 × 100/200 = 0.625, so k1 × 0.625 = 0.75.
Term-frequency factor: 3 × (1.2 + 1) / (3 + 0.75) = 6.6 / 3.75 = 1.76.
Score ≈ 4.547 × 1.76 ≈ 8.00.
(a) As tf → ∞ the factor tf × (k1 + 1) / (tf + constant) approaches k1 + 1 = 2.2, so the score saturates at 4.547 × 2.2 ≈ 10.0. Going from tf = 3 to tf = 100 only raises the factor from 1.76 to about 2.18. This saturation is the point of k1: the hundredth occurrence of a word says much less than the first.
(b) With |D| = 400 the normalization is 1 − 0.75 + 0.75 × 2 = 1.75, so the factor is 6.6 / (3 + 2.1) ≈ 1.29 and the score drops to about 5.88. Three occurrences in a long document are weaker evidence than three in a short one.
(c) ln((1000 − 600 + 0.5) / (600 + 0.5)) = ln(400.5 / 600.5) ≈ −0.405. Any term in more than half the documents gets a negative IDF, so matching it lowers a document’s score. Lucene and most modern engines use ln(1 + (N − n + 0.5)/(n + 0.5)) instead, which stays positive.
30.3 ★★ How tall is an HNSW graph? The insert method in §30.2 picks level = ⌊−ln(u) × mL⌋ with u uniform on (0, 1] and mL = 1/ln(m). (a) Show that P(level ≥ l) = m^(−l). (b) For m = 16 and one million vectors, how many vectors do you expect on layer 1 and above, layer 2 and above, and so on? How many layers does the graph have? (c) Why is a level distribution that decays this fast what makes search fast?
Solution
(a) level ≥ l exactly when −ln(u) × mL ≥ l, that is −ln(u) ≥ l × ln(m), that is u ≤ e^(−l ln m) = m^(−l). Since u is uniform, that event has probability m^(−l).
(b) Expected count on layer l and above = 10⁶ × 16^(−l):
| layer l | expected nodes at level ≥ l |
|---|---|
| 0 | 1,000,000 |
| 1 | 62,500 |
| 2 | 3,906 |
| 3 | 244 |
| 4 | 15 |
| 5 | about 1 |
So the graph has about five or six layers, roughly log base 16 of a million, which is 5.
(c) Each layer has about 1/m as many nodes as the one below, like the levels of a skip list with promotion probability 1/m. A greedy search on a sparse upper layer covers large distances in a few hops and lands near the target; each lower layer refines the position. With a constant number of hops per layer and log_m(N) layers, the expected search cost grows logarithmically. If the distribution decayed slowly, upper layers would be nearly as large as layer 0 and would no longer give long-range shortcuts; that is exactly the bug in a version that computed the level as -log(random()) % max_layers, which puts about 37% of nodes above layer 0 instead of 1/16.
30.4 ★★ Snapshots for an event store. Rebuilding an aggregate from the EventStore in §30.4 replays its entire stream. Add a take_snapshot(aggregate_id) method that stores (version, state), and change rebuild_state to start from the snapshot and replay only later events. Test it on a bank account with events deposited 100, withdrew 30, (snapshot), deposited 50. What property must apply_event have for the snapshot to stay valid?
Hint
Consider what happens to the stored snapshot if apply_event updates the dictionary it is given in place.
Solution
def apply_event(state, event):
# Pure: returns a new dict and never mutates its input
kind, amount = event
balance = state.get("balance", 0)
if kind == "deposited":
return {**state, "balance": balance + amount}
if kind == "withdrew":
return {**state, "balance": balance - amount}
return state
class EventStore:
def __init__(self):
self.streams = {} # aggregate_id -> [event]
self.snapshots = {} # aggregate_id -> (version, state)
def append(self, aggregate_id, event):
self.streams.setdefault(aggregate_id, []).append(event)
def get_stream(self, aggregate_id, from_version=0):
return self.streams.get(aggregate_id, [])[from_version:]
def take_snapshot(self, aggregate_id):
version = len(self.streams.get(aggregate_id, []))
self.snapshots[aggregate_id] = (version, self.rebuild_state(aggregate_id))
def rebuild_state(self, aggregate_id):
version, state = self.snapshots.get(aggregate_id, (0, {}))
for event in self.get_stream(aggregate_id, from_version=version):
state = apply_event(state, event)
return state
store = EventStore()
store.append("acct-1", ("deposited", 100))
store.append("acct-1", ("withdrew", 30))
store.take_snapshot("acct-1")
assert store.snapshots["acct-1"] == (2, {"balance": 70})
store.append("acct-1", ("deposited", 50))
assert store.rebuild_state("acct-1") == {"balance": 120}
assert store.rebuild_state("acct-1") == {"balance": 120} # snapshot untouched
assert store.snapshots["acct-1"] == (2, {"balance": 70})
Rebuilding now costs O(events since the snapshot) instead of O(all events). The version stored with the snapshot is the number of events it covers, so get_stream(..., from_version=version) returns exactly the events not yet folded in.
apply_event must be pure: it must return a new state and never mutate its argument. rebuild_state starts from the very dictionary stored in self.snapshots; if apply_event did state["balance"] += amount in place, the first rebuild would silently add the deposit of 50 into the stored snapshot, and every later rebuild would add it again, giving 170, 220, and so on. The assertion that the snapshot is still (2, {“balance”: 70}) after two rebuilds catches exactly this. (A defensive alternative is to deep-copy the snapshot state before replaying.)
This is the same log-plus-checkpoint pattern as a Raft snapshot or a Delta Lake checkpoint: the log stays the source of truth, and the snapshot is a cache of a prefix of it.
30.5 ★ How much data moves? A cluster maps keys to 24 fixed vnodes as in §30.5, and three physical nodes own 8 vnodes each. (a) A fourth node joins and the vnodes are rebalanced evenly. What fraction of keys move? (b) Compare with owner = hash(key) % num_physical going from 3 to 4 nodes. (c) Suppose the vnode were instead computed as hash(key) % (num_physical × 8), so the vnode count grows with the cluster. What fraction of keys end up in a different vnode when going from 3 to 4 nodes?
Solution
(a) Each node should own 24/4 = 6 vnodes, so the new node takes 2 from each existing node: 6 vnodes, 6/24 = 25% of the keys, all moving to the new node. That is the minimum possible: the new node must end up with its fair share of 1/4.
(b) A key keeps its owner only if h mod 3 = h mod 4, which holds when h mod 12 is 0, 1 or 2: 3 values in 12, so 75% of keys move, most of them between old nodes.
(c) A key stays in the same vnode only if h mod 24 = h mod 32. Over one period of lcm(24, 32) = 96 this holds only for h in 0 to 23, so again 75% of keys move. The vnode layer only helps if the number of vnodes is fixed; changing the modulus brings back mod-N’s behavior.
30.6 ★★★ Where two-phase commit blocks. In the 2PC protocol of §30.6, participants P1, P2 and P3 all vote Yes, and the coordinator crashes before any of them receives the decision. (a) Can P1 commit on its own? Abort on its own? (b) P1 contacts P2 and P3. In which situations can they resolve the transaction without the coordinator, and when are they stuck? (c) Why must the coordinator write its decision to its own durable log before sending it? (d) How does a saga avoid this blocking, and what does it give up?
Hint
After voting Yes, a participant has promised it can commit, but it does not know whether everyone else promised too.
Solution
(a) Neither. P1 cannot commit, because some other participant might have voted No, in which case the coordinator decided abort. P1 cannot abort, because the coordinator might have decided commit and already told someone, or recorded it; aborting would then break atomicity. Having voted Yes, P1 must hold its locks and wait. That is the blocking problem.
(b) If any reachable participant received the decision, everyone adopts it. If any participant has not yet voted, it can unilaterally abort (no Yes vote means no promise), so everyone aborts. If any participant voted No, the outcome must be abort. But in this scenario all three voted Yes and none received the decision, so the outcome depends only on what the crashed coordinator decided, possibly commit. They are stuck holding locks until the coordinator recovers. Participants that are themselves unreachable make it worse: a silent one might be the one that received the decision.
(c) On recovery the coordinator must give the same answer it may already have sent to some participants. If it decided commit, told P1, then crashed and recovered with no record, it might abort when asked again by P2, leaving P1 committed and P2 aborted. Logging the decision durably before sending it is what makes the decision recoverable. (Protocols that replicate the coordinator’s decision with consensus, such as Paxos Commit, remove the single point of blocking.)
(d) A saga commits each local step immediately and never holds locks across services. If a later step fails, it runs compensating actions (release the inventory, refund the payment) for the steps already done. Nothing blocks, but there is no isolation: other transactions can observe the intermediate state (stock reserved for an order that will be cancelled), and every step needs a compensation that is correct to run after arbitrary interleavings.
30.7 ★★ Rollups that lie. §30.7 rolls 10-second samples up into 1-minute and 1-hour summaries. Minute 1 sees 100 requests: 98 at 10 ms and 2 at 300 ms. Minute 2 sees 100 requests, all at 10 ms. Using the nearest-rank percentile (the ⌈0.99 × n⌉-th smallest value), compute each minute’s p99, the true p99 of the two minutes combined, and the two “rollups” someone might compute from the per-minute p99s: their average and their maximum. Which summary statistics can be rolled up exactly from per-minute values, and what should you store to roll up percentiles?
Solution
Minute 1: the 99th smallest of 100 values. The 98 values at 10 ms come first, so the 99th is 300 ms. Minute 2: 10 ms.
Combined: 200 values, 198 at 10 ms and 2 at 300 ms. The ⌈0.99 × 200⌉ = 198th smallest is 10 ms.
Average of the per-minute p99s: (300 + 10)/2 = 155 ms. Maximum: 300 ms. Both are wrong: the true answer is 10 ms. With other data the average of p99s can just as easily be far too low.
Exact rollups: count, sum, min and max combine exactly (add, add, min, max), and the mean is sum/count, which needs both; averaging the per-minute averages is only correct when every minute has the same count. Percentiles do not combine from percentiles at all. To roll them up, store a mergeable summary per interval: a histogram with fixed bucket boundaries (merge by adding bucket counts, the Prometheus approach) or a mergeable sketch such as a t-digest or DDSketch. The percentile is then computed from the merged summary, with error set by the bucket or sketch resolution rather than by the rollup.
30.8 ★ Compress a posting list by hand. A term occurs in documents 5, 130, 131 and 16515. (a) Write the d-gaps and their varint bytes in hex, using the encoding of §30.1. How many bytes is that, against 32-bit integers and against varints of the raw IDs? (b) Pack the four gaps as one frame-of-reference block. What bit width does the block need, and how many bytes? (c) What would PForDelta do with this block?
Hint
16,384 is 2¹⁴, the smallest number that needs a third varint byte.
Solution
(a) The gaps are 5, 125, 1 and 16384. 5, 125 and 1 are below 128, so they take one byte each: 05, 7D, 01. 16384 = 2¹⁴ is 1 0000000 0000000 in binary, three 7-bit groups; lowest first with continuation flags, that is 80 80 01. Total 6 bytes, against 16 as 32-bit integers. The raw IDs as varints are 05, 82 01, 83 01, 83 81 01, 8 bytes: 130 and 131 need two bytes and 16515 three.
(b) The width is that of the largest gap: 16384 needs 15 bits, so 4 × 15 = 60 bits, 8 bytes, worse than varint. The other three gaps need at most 7 bits (125 < 128) but pay for the outlier.
(c) PForDelta picks the width that fits most of the block, here 7 bits: 4 × 7 = 28 bits, 4 bytes, and records 16384 separately as an exception (its position in the block and its value), patched in after the block is unpacked. On a real block of 128 gaps a single exception costs a few bytes, while widening the whole block from 7 to 15 bits would cost 128 extra bytes.
# Checked with the functions from §30.1
assert varint_encode(delta_encode([5, 130, 131, 16515])).hex(" ") == "05 7d 01 80 80 01"
assert len(varint_encode([5, 130, 131, 16515])) == 8
assert for_pack([5, 125, 1, 16384])[0] == 15 and for_pack([5, 125, 1])[0] == 7
30.9 ★★ When does galloping pay? (a) Intersect a list of m = 1,000 doc IDs with one of n = 10,000,000. Estimate the comparisons for the linear merge and for galloping. (b) Prove the O(m log(n/m) + m) bound from §30.1 for the case where every one of the m searches advances the long-list position by the same amount, and explain why unequal advances cannot cost more. (c) When the two lists have about the same length, which method is faster in practice, and how do implementations choose between them?
Solution
(a) The merge advances one of the two pointers on every comparison and can end only when one list runs out, so it does up to m + n ≈ 10⁷ comparisons (it may stop early if the short list’s last element is small, but in general it reads most of the long list). Galloping does about 2 log₂(n/m) = 2 log₂(10⁴) ≈ 27 comparisons per element of the short list, about 27,000 in total: a 370-fold reduction.
(b) If every search advances the position by g = n/m, each search costs about log₂ g probes to overshoot and log₂ g more to binary-search the last interval, so the total is about 2m log₂(n/m), plus O(1) per element for the first probe. With unequal advances g₁, …, g_m summing to at most n, the cost is Σ O(1 + log g_i). Since log is concave, Jensen’s inequality gives (1/m) Σ log g_i ≤ log((1/m) Σ g_i) ≤ log(n/m), so Σ log g_i ≤ m log(n/m): spreading the same total distance unevenly can only lower the sum of logs.
(c) The merge. When n ≈ m the gaps are about 1, so galloping does O(1) work per element and has the same O(n) bound, but each search still costs a probe or two plus the loop and bisect setup, while the merge does one comparison and one pointer increment per step. Both are linear, and the merge has the smaller constant. Implementations choose by the length ratio: merge when the lists are close in size, gallop when one is much shorter. (Python’s list.sort uses the same idea in reverse: its merge switches into galloping mode once one run keeps winning.) Search engines rarely face this choice on raw arrays; they advance through compressed blocks with skip data, and the shortest-list-first rule keeps the driving list short.
30.10 ★★ Merge two segments. Represent a segment as (postings, live), where postings maps each term to its sorted local doc IDs and live is a list of booleans, one per document (False means deleted). Write merge_segments(segments) that returns the postings of a single merged segment containing only live documents, with IDs renumbered 0, 1, 2, … in segment order, plus the merged document count. Test it on segment A with {"data": [0, 1, 2], "heap": [1]}, live [True, False, True], and segment B with {"data": [1], "trie": [0, 1]}, live [True, True]. Why does no posting list need re-sorting?
Solution
def merge_segments(segments):
"""segments: list of (postings, live) with postings: term -> sorted local
doc IDs and live: list of bools, one per document in the segment.
Returns the postings of one merged segment with no deleted documents."""
remaps, base = [], 0
for _, live in segments:
remap = {}
for local, alive in enumerate(live):
if alive:
remap[local] = base
base += 1
remaps.append(remap)
merged = {}
for (postings, _), remap in zip(segments, remaps): # segment order = ID order
for term, docs in postings.items():
new_ids = [remap[d] for d in docs if d in remap]
if new_ids:
merged.setdefault(term, []).extend(new_ids)
return dict(sorted(merged.items())), base
seg_a = ({"data": [0, 1, 2], "heap": [1]}, [True, False, True])
seg_b = ({"data": [1], "trie": [0, 1]}, [True, True])
merged, n_docs = merge_segments([seg_a, seg_b])
assert n_docs == 4
assert merged == {"data": [0, 1, 3], "trie": [2, 3]} # "heap" only had a deleted doc
The remap gives A’s live documents 0 and 2 the new IDs 0 and 1, and B’s documents 0 and 1 the IDs 2 and 3. Deleted document A1 gets no new ID, so its postings disappear, and “heap”, which occurred only there, disappears from the merged dictionary: this is how a merge reclaims the space of deletes.
No list needs re-sorting because the renumbering preserves order twice over: within a segment, the remap is increasing (later live documents get larger IDs), and across segments, every ID from A is smaller than every ID from B. So appending each segment’s remapped list in segment order produces a sorted list, and the whole merge is one sequential pass over the inputs, O(total postings + total documents). A real merge also streams the term dictionaries in sorted order (a k-way merge of the segments’ sorted term lists) instead of building a dictionary and sorting it at the end, and writes the merged lists straight into compressed blocks.
Where this connects
- Chapter 29: System Design as Data Structure Composition. The component structures these patterns compose
- Chapter 19: Emerging and Specialized Structures. The vector-search structures behind modern recommendation
Chapter 31: Real-World Case Studies
Five systems, examined for the same thing: which data structures they chose, and what those choices bought and cost. Each one made a decision the others didn’t, and in every case the decision traces back to a structure from earlier in this book.
31.1 Google’s Spanner: Globally Distributed SQL
Spanner combines B-tree storage with distributed systems innovations:
Architecture:
Universe (global deployment)
↓
Zone (data center)
↓
Spanserver (process)
↓
Tablet (range of rows, ~100GB)
↓
Colossus (distributed file system)
TrueTime API: GPS and atomic clocks provide bounded clock uncertainty (±1ms to ±7ms). This enables:
- External consistency (linearizable transactions)
- Snapshot reads without coordination
- Consistent schema changes
Paxos consensus: Data replicated via Paxos between zones. Two-phase commit with participant coordinators.
The central idea is that TrueTime turns time into a data structure with an error bar. Ordinary clocks return a timestamp; TrueTime returns an interval [earliest, latest] guaranteed to contain the true time. That single change makes global ordering possible without global coordination.
The mechanism is called commit wait, and it is almost aggressively simple:
To commit a transaction at timestamp s:
1. Acquire locks, pick s = TT.now().latest
2. Do the work
3. WAIT until TT.now().earliest > s ← deliberately sleep
4. Release locks, commit
After the wait, s is guaranteed to be in the past everywhere on Earth.
So any transaction that starts later gets a strictly larger timestamp.
Spanner waits out the clock uncertainty rather than trying to eliminate it. Because s is taken from the top of an interval 2ε wide and the wait ends only when the bottom of the interval passes s, a commit waits about 2ε: with ε ≈ 7ms, roughly 14ms before releasing locks (in practice partly overlapped with the Paxos round). Google chose to buy an ordering guarantee with latency, and then spent heavily on GPS receivers and atomic clocks in every datacenter to keep the price low, because the cost of the whole system is proportional to ε.
Structures in play: B-trees for tablet storage (via Colossus), a Paxos state machine per tablet group, two-phase locking, and MVCC. Every row version is timestamped, so a snapshot read at time t needs no locks at all and never blocks a writer. That last property is Chapter 17’s partial persistence, deployed globally.
The cost: writes pay a cross-region Paxos round trip plus commit wait, so write latency is tens to hundreds of milliseconds. Spanner is the right answer when you need global transactions and can tolerate that, and the wrong answer for a write-heavy local workload.
31.2 Amazon Dynamo: Highly Available Key-Value Store
Dynamo prioritizes availability over consistency:
Design decisions:
- “Always writable”: Sloppy quorum + hinted handoff
- Vector clocks for causality tracking
- Quorum guarantees configurable per request
Data distribution:
Consistent hashing ring (N=3, R=2, W=2):
- N: Number of replicas
- R: Minimum read replicas
- W: Minimum write replicas
- Quorum overlap: R + W > N
Anti-entropy: Merkle trees for background synchronization. Each replica maintains local Merkle tree of its key range; trees compared to detect divergence.
Dynamo is the deliberate opposite of Spanner, and the paper is unusually honest about why: for Amazon’s shopping cart, rejecting a write costs a sale. So Dynamo never rejects one. If the responsible node is unreachable, another node accepts the write and holds it with a hint to forward it later: sloppy quorum with hinted handoff.
The consequence is that two replicas can legitimately hold different values for the same key, and the system needs a way to tell “B replaced A” from “A and B happened concurrently”. That is what vector clocks provide:
Client writes cart to node A: [(A,1)]
Client adds item, writes to A: [(A,2)] A,2 descends from A,1 → replaces
Partition. Client adds via B: [(A,2), (B,1)]
Meanwhile client adds via C: [(A,2), (C,1)]
Partition heals. Neither vector dominates the other
→ concurrent. Both versions are returned to the client.
Dynamo pushes reconciliation to the application, and for a shopping cart the resolution is a set union, which is why a deleted item famously sometimes reappears. That is the visible cost of choosing availability, and it is a deliberate trade, not a bug.
Merkle trees solve the other problem: detecting divergence without comparing everything. Each replica hashes its key range into a tree; two replicas compare root hashes, and if they match (the common case) they are identical and nothing more transfers. If they differ, they descend only into subtrees whose hashes disagree. Comparing two replicas of a million keys with one difference takes about 20 hash comparisons instead of a million. The same structure, for the same reason, is how Git compares trees and how BitTorrent verifies pieces.
Structures in play: consistent hashing with virtual nodes (Chapter 27), vector clocks, Merkle trees, and per-node LSM or B-tree storage. Dynamo’s design became DynamoDB, Cassandra, Riak, and Voldemort.
31.3 Apache Kafka: Distributed Log as First-Class Citizen
Kafka treats the log as the primary data structure:
Storage architecture:
Topic: "orders"
↓
Partitions (16):
Partition 0: [0 → 1MB] [1MB → 2MB] ...
Partition 1: [0 → 1.2MB] [1.2MB → 2.1MB] ...
...
Each partition stored as:
- .log file (actual data)
- .index file (offset → position)
- .timeindex file (timestamp → offset)
Zero-copy I/O: Kafka uses kernel sendfile() to avoid copying data to user space. DMA transfers data from disk directly to network.
Page cache: Linux page cache used for hot data. Sequential writes cause read-ahead, sequential reads cause readahead.
Kafka’s insight is that an append-only log is a better primitive than a queue. A traditional message queue deletes a message once consumed, which forces it to track per-message delivery state and makes replay impossible. Kafka never deletes on consumption; it keeps an ordered, immutable log and lets each consumer track its own offset: a single integer.
That one decision produces most of Kafka’s properties:
- Multiple independent consumers read the same partition at different positions, without coordination.
- Replay is seeking backwards.
- Broker state per consumer is one integer, so brokers scale to enormous consumer counts.
- Writes are pure appends. Sequential disk I/O, which as Chapter 16 explains is often faster than random writes to memory, and vastly faster than random disk writes.
The .index file is a sparse index: an entry every few kilobytes, not per message. A lookup binary-searches it to find the nearest earlier offset, then scans forward. Sparse keeps the index small enough to stay in page cache, and the scan is sequential. The same “cheap sequential work beats expensive random work” reasoning throughout.
Zero-copy is worth understanding as an accounting exercise. A conventional send copies data four times: disk → kernel page cache → user buffer → socket buffer → NIC. sendfile() goes disk → page cache → NIC, eliminating two copies and two context switches. This is only possible because Kafka does not transform the bytes. It stores exactly what the producer sent, so the kernel can move them without user space ever seeing them. An immutable log makes the optimisation available.
The cost: ordering is guaranteed only within a partition, not across a topic. Anything needing global ordering must use a single partition and give up parallelism. That constraint shapes every Kafka data model.
31.4 Databricks Delta Lake: ACID on Data Lakes
Combines streaming (append-only log) with batch processing:
Transaction log: JSON entries recording changes:
{"add": "part-00000.snappy.parquet", "partitionValues": {"date": "2024-01-01"}, "size": 1234567}
{"remove": "part-00099.parquet"}
Optimistic concurrency: Delta Lake uses file-level locking. Transaction validation checks:
- Read current protocol version
- Verify read set files still exist
- Write new files and transaction commit
- If conflict, retry with exponential backoff
Delta Lake solves a problem created by cloud object storage: S3 gives cheap, durable, effectively infinite storage but no transactions and no atomic multi-file operations. A job writing 500 Parquet files that fails halfway leaves the table in a state no reader can interpret.
The fix is to stop treating the file listing as the source of truth. The transaction log is the table; the Parquet files are just content addressed by it. A reader replays the log to compute the current file set, and a file not named in the log does not exist as far as the table is concerned, so a failed job leaves orphaned files that are simply invisible, rather than corruption.
This makes the table state a persistent data structure in exactly the sense of Chapter 17: each log entry produces a new version, old versions remain valid, and unchanged files are shared between them. “Time travel” (querying the table as of last Tuesday) is not a feature bolted on but a direct consequence of the representation.
Replaying the entire log would get slow, so Delta periodically writes a checkpoint (a Parquet file holding the full state at version N), and readers start from the newest checkpoint and replay only the entries after it. This is the same log-plus-snapshot pattern used by Raft, Redis AOF with RDB, and every event-sourced system in Chapter 30.
Optimistic concurrency works here because the workload is right for it: writers are few and conflicts are rare. Each writer reads the current version, does its work, and attempts to commit version N+1 by atomically creating a file with that name. Exactly one wins; the loser checks whether the conflict was real (did anyone touch the files I read?) and retries if not. Pessimistic locking would be pure overhead at this conflict rate.
The cost: small, frequent writes produce many small files and log entries, degrading read performance until compaction runs. Delta Lake suits batch and micro-batch workloads, not per-record streaming.
31.5 Cloudflare’s Edge Cache: Global Caching Infrastructure
Anycast routing: All edge nodes announce same IP via BGP. Traffic routed to nearest PoP (Point of Presence).
Cache hierarchy:
User → Edge PoP (L1 cache, ~100GB)
↓ (miss)
Regional DC (L2 cache, ~1TB)
↓ (miss)
Origin Shield (L3 cache, ~10TB)
↓ (miss)
Origin server
Cache key normalization:
- Strip query parameters (configurable)
- Normalize URL encoding
- Include vary headers in key
- TTL rules per content type
Two structural ideas do most of the work here.
Anycast makes routing itself the load balancer. Hundreds of PoPs announce the same IP prefix via BGP, and the internet’s own routing tables (the tries of Chapter 28)deliver each packet to the topologically nearest one. There is no load balancer to scale, no DNS TTL to wait out during a failover, and a PoP that goes down simply stops announcing, after which BGP reconverges automatically. The cost is that the routing tables decide, not you: BGP optimises for AS-path length, which is not always the lowest latency.
The cache hierarchy is the memory hierarchy again, at planetary scale and with the same arithmetic. Each tier is larger, slower, and further away, and each absorbs the misses of the tier above:
| Tier | Size | Latency | Role |
|---|---|---|---|
| Edge PoP | ~100GB | ~5ms | Absorbs the bulk of requests |
| Regional | ~1TB | ~30ms | Catches what edges miss |
| Origin shield | ~10TB | ~80ms | Protects the origin from stampedes |
| Origin | n/a | ~200ms+ | Source of truth |
The origin shield exists for a specific failure mode: without it, a popular object expiring simultaneously across 300 edge PoPs sends 300 requests to the origin at once, a thundering herd. The shield collapses them into one. The general technique is request coalescing: concurrent misses for the same key wait on a single in-flight fetch rather than each issuing their own.
Cache key design is where correctness lives. Include too much in the key (a tracking parameter, a session cookie) and the hit rate collapses because every request is unique. Include too little and users are served each other’s content, which is a security incident rather than a performance problem. The Vary header is the standard mechanism, and getting it wrong is one of the more common ways to leak data between users.
31.6 What the Five Have in Common
Reading them side by side, the patterns are more instructive than any individual system:
| Spanner | Dynamo | Kafka | Delta Lake | Cloudflare | |
|---|---|---|---|---|---|
| Chooses | Consistency | Availability | Throughput | Correctness on cheap storage | Latency |
| Gives up | Write latency | Read consistency | Cross-partition order | Small-write efficiency | Cache-key complexity |
| Core structure | Paxos + MVCC B-trees | Consistent hash ring | Append-only log | Versioned log of files | Hierarchical cache + trie routing |
| Key insight | Bound clock error, then wait it out | Never reject a write | Never delete on read | The log is the table | Let BGP do the balancing |
Three observations worth carrying:
Every system is a composition, not an invention. Spanner is B-trees plus Paxos plus MVCC plus a clock. Dynamo is consistent hashing plus vector clocks plus Merkle trees. None of the components are new; the arrangement is. This is the claim Chapter 29 makes, and these systems are the evidence.
The interesting decision is always what to give up. Spanner and Dynamo faced the same problem and chose opposite sides of CAP, and both were right for their workload. A system that appears to give up nothing has usually hidden the cost somewhere you haven’t looked yet.
Sequential access wins repeatedly. Kafka’s append-only log, Delta Lake’s log, LSM-tree flushes, Merkle tree comparison: the same principle from Chapter 16, reappearing at every scale from cache lines to datacenters.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
31.1 ★★ How long is commit wait? Spanner’s TrueTime returns an interval [earliest, latest] of width 2ε around the true time. A transaction picks s = TT.now().latest and then waits until TT.now().earliest > s. Assuming ε stays constant, show that the wait lasts about 2ε, and compute it for ε = 1 ms, 4 ms and 7 ms. Then explain what could go wrong if Spanner skipped the wait.
Hint
Start by assuming the interval is centered on the true time t, so latest = t + ε and earliest = t − ε, then check whether an off-center clock changes the answer.
Solution
Take a clock centered on the true time. At true time t₀, the transaction picks s = latest = t₀ + ε. At a later true time t, earliest = t − ε, and the wait ends when t − ε > s = t₀ + ε, that is when t > t₀ + 2ε. So the wait is 2ε: 2 ms, 8 ms and 14 ms for ε = 1, 4 and 7 ms. If the true time sits at some other fixed position inside the interval, both bounds shift by the same amount and the offset cancels: the wait is still 2ε.
After the wait, earliest > s, which means the true time is definitely past s on every machine whose TrueTime interval is correct. Any transaction that starts after this one commits will pick a timestamp from a later interval, so its timestamp exceeds s. Commit order then matches real-time order: external consistency.
Without the wait, transaction T1 could commit with s₁ = t₀ + ε and release its locks immediately. A client sees T1’s result and then starts T2 on another server whose clock reads slightly behind; that server might pick s₂ < s₁. A snapshot read at a time between s₂ and s₁ would then see T2’s write but not T1’s, although T1 visibly finished first. The wait trades a few milliseconds of write latency for never having that anomaly, and halving ε halves the price.
31.2 ★ Quorums and sloppy quorums. Dynamo uses N = 3. For each (R, W) of (1, 1), (1, 3), (2, 2), (3, 1), say whether a read is guaranteed to see the latest acknowledged write when no nodes fail, and which configuration favors what. Then explain why, even with R + W > N, a sloppy quorum does not give that guarantee during a failure.
Solution
The overlap condition is R + W > N, here R + W > 3.
| (R, W) | R + W | read sees latest write? | favors |
|---|---|---|---|
| (1, 1) | 2 | no | lowest latency, highest availability |
| (1, 3) | 4 | yes | fast reads; any one node down blocks writes |
| (2, 2) | 4 | yes | balanced; tolerates one failure for both |
| (3, 1) | 4 | yes | fast, always-available writes; slow reads |
Dynamo’s common configuration is (2, 2).
A sloppy quorum counts the first W healthy nodes on the preference list, which may include nodes outside the key’s normal three replicas. If replica B is unreachable, a write might be acknowledged by A and D (holding a hint for B). A read that then goes to B (now reachable) and C reaches two of the key’s home replicas, neither of which has the write, so it returns stale data even though R + W = 4 > 3. The overlap argument only works when both quorums are drawn from the same set of N nodes. Sloppy quorum gives up that guarantee to keep accepting writes, and hinted handoff plus anti-entropy repair the divergence later.
31.3 ★★ Vector clocks after reconciliation. Continue the shopping-cart example in §31.2. The client reads the key, receives both [(A,2), (B,1)] and [(A,2), (C,1)], merges the carts, and writes the result through node A. (a) What vector clock does the new version get, and why does it replace both siblings? (b) For each pair, say whether the first happened before the second, after it, or concurrently: [(A,1)] and [(A,1), (B,1)]; [(A,2), (B,1)] and [(A,1), (B,2)]; [(A,3), (B,1), (C,1)] and [(A,2), (C,1)]; [(B,1)] and [(C,1)].
Solution
(a) The client sends back a context that is the entry-wise maximum of the clocks it read, [(A,2), (B,1), (C,1)], and node A increments its own entry: [(A,3), (B,1), (C,1)]. This clock is at least as large as both siblings in every entry and strictly larger in A, so it dominates both. Every node that later sees it can discard the two siblings: the conflict is resolved.
(b) Compare entry by entry, treating a missing entry as 0.
| first | second | relation |
|---|---|---|
| [(A,1)] | [(A,1), (B,1)] | before: equal on A, and B: 0 < 1 |
| [(A,2), (B,1)] | [(A,1), (B,2)] | concurrent: A is larger in the first, B in the second |
| [(A,3), (B,1), (C,1)] | [(A,2), (C,1)] | after: every entry ≥, A strictly greater |
| [(B,1)] | [(C,1)] | concurrent: each has an entry the other lacks |
Concurrent versions are returned to the client as siblings; ordered ones are resolved by keeping the later.
31.4 ★★ The arithmetic of Merkle comparison. Two replicas each store 2^20 (about a million) keys under a binary Merkle tree with one leaf per key. They compare by checking the roots, then, at every node whose hashes differ, comparing both children. (a) How many hash comparisons if exactly one key differs? (b) Estimate the count if 1,000 keys, scattered at random, differ. (c) What does that suggest about when Merkle synchronization stops paying off?
Solution
(a) The tree has 20 levels below the root. One differing leaf makes exactly one node differ at each level: the root and 19 internal nodes above the leaf, 20 differing internal nodes in all. The protocol compares the root (1) and both children of each differing internal node (2 × 20), so 41 hash comparisons in total, against a million for a flat comparison. (The chapter’s “about 20” counts levels. Skipping the right child when the left child matches, since a differing parent with a matching left child must have a differing right child, brings it down to between 21 and 41.)
(b) Near the top, 1,000 random leaves make nearly every node differ, but levels 0 to 9 hold only 1,023 nodes in total (about 950 of them differ). Further down there are more nodes per level than differences, so close to 1,000 nodes differ per level, one per differing key, for the remaining 10 levels. That is about 10,000 differing internal nodes (the exact expectation is 10,145), so about 20,300 comparisons. A rule of thumb is 2 × k × log₂(N/k) for k differences among N keys: 2 × 1,000 × log₂(1,048) ≈ 20,000.
(c) The cost grows nearly linearly in the number of differences, plus a log factor. When the replicas differ in a large fraction of keys, the tree walk costs more than just streaming every key’s hash in order (N comparisons, sequential). Merkle trees are built for the common case: replicas that are almost the same. This is also why Dynamo-style systems run anti-entropy continuously, so the differences stay small.
31.5 ★ Find an offset with a sparse index. A Kafka segment’s .index file holds these (offset, byte position) entries: (0, 0), (52, 4120), (97, 8233), (150, 12400). How does the broker find offset 120? With the default of one index entry per 4,096 bytes of log and 8 bytes per entry, how large is the index for a 1 GiB segment?
Solution
Binary-search the index for the largest offset ≤ 120: that is (97, 8233). Seek to byte 8,233 of the .log file and scan forward, reading record headers, past offsets 97 to 119 (23 records) until reaching offset 120. The scan reads at most about 4 KB, which is likely already in the page cache and is sequential.
Index size: 2^30 / 2^12 = 262,144 entries × 8 bytes = 2 MiB per 1 GiB segment, 1/512 of the data. A dense index with one entry per record would be far larger for small records, which is the trade the chapter describes: a little sequential scanning in exchange for an index small enough to stay in memory.
31.6 ★★ What the hierarchy buys. Use the tier latencies in §31.5 as end-to-end response times. Suppose the edge PoP hits 90% of requests, the regional tier hits 60% of what reaches it, and the origin shield hits 50% of what reaches it. (a) What fraction of requests reach the origin, and what is the mean latency? (b) What is the mean latency if the edge hit rate improves to 95%, with the other tiers’ hit rates unchanged? (c) Without the shield (regional misses go straight to the origin), what fraction of requests reach the origin?
Solution
(a) Served at the edge: 0.90. At regional: 0.10 × 0.6 = 0.06. At the shield: 0.10 × 0.4 × 0.5 = 0.02. At the origin: 0.10 × 0.4 × 0.5 = 0.02, that is 2% of requests.
Mean latency = 0.90 × 5 + 0.06 × 30 + 0.02 × 80 + 0.02 × 200 = 4.5 + 1.8 + 1.6 + 4.0 = 11.9 ms.
(b) Edge 0.95, regional 0.05 × 0.6 = 0.03, shield 0.01, origin 0.01. Mean = 4.75 + 0.9 + 0.8 + 2.0 = 8.45 ms. Five more points of edge hit rate cut mean latency by 29% and origin load in half, because misses are what dominate the mean: 2% of requests at the origin contributed a third of the latency in (a). This is the same reasoning as average memory access time for CPU caches.
(c) 0.10 × 0.4 = 4% of requests reach the origin, double the load. And that is the average; the shield’s larger job is collapsing simultaneous misses for the same object from many PoPs into one origin fetch, which the averages here do not show.
31.7 ★★★ Optimistic commits on object storage. In Delta Lake (§31.4), writers commit version N+1 by atomically creating the log file for N+1. Writers W1 and W2 both read version 7. W1 commits version 8 first. (a) W1 only appended new files to partition date=2024-01-01. W2 read and rewrote files in partition date=2024-01-02. Must W2 redo its work? (b) Instead, W1 was a compaction that removed file f4 and added a merged file, and W2 was an UPDATE that read f4 and wrote a modified copy. Must W2 redo its work? (c) Why must “create the file for version N+1” be a put-if-absent operation, and what happens if the storage only offers a plain overwrite?
Hint
The conflict check compares what W2 read against what W1’s commit changed. For (c), consider both writers succeeding at writing the same file name.
Solution
(a) No. W2’s attempt to create version 8 fails, so it reads version 8’s log entry, sees that W1 only added files in a partition W2 never read, and concludes its own result is still correct against the new table state. It retries the commit as version 9 without redoing any work. This is the common case the design relies on: concurrent writers usually touch disjoint data.
(b) Yes. W2 read f4, but version 8 removed f4, and the merged file now holds those rows. If W2 committed anyway, its log entry would remove f4 (already gone) and add its modified copy, while the merged file still contains the unmodified rows: the table would hold both versions of those rows. This is a real conflict, so W2 must abort, re-read the table at version 8, and redo the UPDATE.
(c) The atomic create is the only serialization point in the whole protocol: it decides which of the concurrent writers gets each version number. With plain overwrite, both W1 and W2 would successfully write the file for version 8, the second silently replacing the first. W1 believes it committed, but its log entry is gone, and readers will never see its files: a lost write with no error. This is why Delta Lake on stores that lacked a put-if-absent primitive needed an external coordination service (a lock or a conditional write in a database) to guard log commits.
Where this connects
- Chapter 29: System Design as Data Structure Composition. The composition principle these systems demonstrate
- Chapter 27: Distributed Data Structures. The distributed primitives they are built from
Chapter 32: Synthesis and Future Directions
32.1 The Data Structure Spectrum
From fundamental to application-specific:
Abstraction Level
├── Fundamental: Array, List, Tree, Hash, Graph
│
├── Composite: Skip lists, Tries, Heaps, Bloom filters
│
├── Specialized: Segment trees, B-trees, LSM trees
│
├── Distributed: DHT, CRDT, Raft state machines
│
└── Application: Routing tables, Inverted indexes,
Time series stores, Graph DBs
The layers are not just an organising convenience. each one is built by composing the layer beneath it, and tracing a structure down through the stack usually explains why it behaves the way it does.
A routing table is a trie is a tree is pointers into memory. An LSM tree is sorted runs plus a memtable plus Bloom filters, which are a bit array plus hash functions. A DHT is a hash function plus a ring plus a routing table plus failure detection. Nothing at the top of this diagram is novel at the bottom of it.
Read the other direction, the same diagram is a map of what changes as you ascend:
| Level | The binding constraint | What you optimise |
|---|---|---|
| Fundamental | CPU cycles, cache lines | Operation count, locality |
| Composite | Memory footprint | Bits per element, pointer overhead |
| Specialized | Disk and page transfers | I/O count, write amplification |
| Distributed | Network round trips, partitions | Coordination avoided |
| Application | Human requirements | The right approximation |
Complexity analysis is most useful at the top two rows and least useful at the bottom two. Nobody chooses between two distributed designs by comparing O(log n) to O(1); they compare round trips, failure modes, and what happens during a partition. The asymptotics have not become wrong, they have become the least interesting term.
32.2 Emerging Paradigms
Learned Data Structures
Machine learning models replacing traditional structures:
- Learned indexes: Replace B-trees with neural networks predicting data positions
- Learned cardinalities: Better statistics for query optimization
- Learned compression: Adaptive compression based on data distribution
Neural B-tree:
Input: key
Output: predicted position + confidence interval
Training: Supervised learning on key distributions
Prediction: Binary search within confidence bounds
The reframing is genuine: an index is a function from key to position, and a model can approximate a function. A B-tree assumes nothing whatsoever about the key distribution, which makes it robust and also means it throws away information. Real key distributions (timestamps, auto-increment IDs, sorted identifiers) are highly regular, and a model that captures that regularity beats a structure that ignores it.
The honest status, five years on from the original paper: learned indexes remain mostly research, and the parts that shipped are elsewhere. Updates are the hard problem. The original design was read-only, and while ALEX and the PGM-index support updates, distribution shift can force retraining. Worst-case bounds disappear, which matters for anything adversarial. And “neural network” oversells it: the models that work are staged linear regressions, because inference has to cost nanoseconds.
What has landed from this line of work is less glamorous and more useful: learned cardinality estimation in query optimisers, learned cache-eviction policies, and learned Bloom filters. Chapter 19 covers the details.
Quantum Data Structures
Quantum computing offers new primitives:
- Quantum search: O(√n) search (Grover’s algorithm)
- Quantum random access memory (QRAM): Sub-linear access with superposition
- Quantum fingerprints: Exponential space reduction for equivalence testing
Worth stating the caveats plainly, because this area attracts more enthusiasm than it currently earns.
Grover’s algorithm gives a quadratic speedup for unstructured search: O(√n) instead of O(n). That is real but modest, and it applies to unstructured search. A sorted array with binary search is already O(log n), which beats O(√n) comfortably. Grover helps where no structure exists to exploit, which is precisely the case where you would normally add an index.
QRAM is the deeper problem. Most quantum algorithms with impressive speedups assume a memory that can be queried in superposition, and no scalable QRAM has been built. The theoretical speedups are frequently accounted without the cost of loading classical data into quantum state, which can erase the advantage entirely.
The realistic near-term position: quantum computing will likely matter first for simulation, optimisation, and cryptography, not for data structures. The exception is cryptographic hashing: Grover halves the effective bit strength of a hash function, which is why post-quantum guidance recommends 256-bit hashes where 128 was sufficient. That is a live concern for Merkle trees and content-addressed storage.
32.3 The Road Ahead
Software-hardware co-design: As memory hierarchies deepen (NVM, CXL), data structures must adapt. Cache-oblivious structures gain importance.
Specialized accelerators: FPGAs and ASICs for network processing, search, and analytics push structure design toward hardware.
Declarative data structures: The boundary between algorithms and data structures blurs as query optimizers automatically choose structures based on workload patterns.
Two shifts already underway deserve to be added, because they are changing decisions today rather than eventually.
Vector search became infrastructure in about three years. Embedding models turned similarity search from a niche problem into a default component of application architecture, and the structures that serve it (HNSW graphs, IVF, product quantization) went from papers to production defaults faster than almost anything in this book’s history. Note what drove it: not a better algorithm, but a change in what data looked like. Structures follow workloads.
NVMe is quietly reopening settled questions. A great deal of received wisdom: B-trees over hash indexes on disk, LSM trees over in-place updates, “random I/O is catastrophic”. Was calibrated against spinning disks where a seek cost 10ms. On NVMe a random read costs about 10μs, a thousandfold improvement, and the gap between sequential and random access narrows from 10,000× to something closer to 10×. Several tradeoffs that were obvious in 2005 are now genuinely arguable. When the hardware assumptions under a piece of conventional wisdom change by three orders of magnitude, the wisdom deserves rechecking.
The general lesson across both: the structures that win are the ones that answer a question created by a hardware or workload shift. LSM trees won when write amplification on flash started to matter. HNSW won when embeddings created a new query type. Neither was primarily an algorithmic advance.
32.4 Principles for the Practitioner
- Measure before optimizing: Profile against real workloads
- Understand trade-offs: Every structure excels in some dimensions
- Prefer simplicity: Complex structures have hidden costs
- Plan for scale: Design for 10x growth
- Embrace approximation: Probabilistic structures often suffice
- Consider distribution: At scale, single-machine solutions fail
- Document assumptions: Workload characteristics drive structure choice
Four of those are worth sharpening, because as stated they are easy to agree with and hard to act on.
Measure the right thing. “Profile” usually means a wall-clock profiler, which tells you where time goes but not why. If a function is slow and its arithmetic is trivial, the answer is memory, and you need hardware counters to see it. An instructions-per-cycle figure below 1.0 with high cache misses means the layout is wrong and no algorithmic tuning will help: see Chapter 22.
Prefer simplicity, and mean it. The most common real-world mistake is not picking an O(n log n) structure where O(n) existed. It is picking a sophisticated structure whose constant factors, memory overhead, and bug surface exceed the benefit. Fibonacci heaps are the standing example: optimal on paper, beaten by binary heaps in practice, and vastly harder to get right. A linear scan over a contiguous array beats almost everything below a few hundred elements.
“Design for 10× growth” is a claim about which dimension grows. Ten times the data is a different problem from ten times the write rate, which is different again from ten times the concurrent readers. B-trees handle the first, LSM trees the second, immutable structures the third. Designing for unspecified “scale” produces systems that are complex in the wrong direction.
Embrace approximation, after checking the error direction. A Bloom filter’s false positives are safe as a cache filter and unsafe as an access-control check. The question is never just “is approximate good enough” but “what does a mistake cost, and which way does this structure make them” (Chapter 14).
Three more that this book has argued throughout:
-
Identify the repeated question. Every algorithm asks one thing over and over. “which is nearest”, “have I seen this”, “would this create a cycle”. Name it, and the structure is usually obvious. Get it wrong and no optimisation will save you (Chapter 21).
-
Abstract the interface, document the cost. A
Listbacked by an array and one backed by a linked list have identical signatures and completely different performance. Hiding the layout is good design; hiding the cost is how O(n²) loops get written by accident. -
Write the invariant checker. For every structure there is a predicate that must hold after every operation. Written as code and asserted in debug builds, it converts a silent wrong answer a thousand operations later into a failure on the operation that caused it.
32.5 A Closing Thought
The through-line of these thirty-one chapters is that there are far fewer ideas here than there are structures. Almost everything in this book is one of a handful of moves, applied at a different scale:
- Divide the space so most of it can be discarded: binary search, trees, tries, KD-trees, sharding.
- Trade exactness for space: Bloom filters, HyperLogLog, sketches, learned indexes.
- Trade space for time, or the reverse: indexes, caches, memoization, compression.
- Batch the expensive thing: LSM trees, B-tree fanout, external sorting, request coalescing.
- Share what didn’t change: persistent structures, copy-on-write, Git, snapshots, Merkle trees.
- Randomize to defeat the adversary: skip lists, treaps, universal hashing, randomized pivots.
- Never mutate; append and reference: logs, event sourcing, immutable collections, Kafka, Delta Lake.
Each of those appears at every level of the spectrum in §32.1, from cache lines to continents. A B-tree fans out to reduce disk transfers; a CDN hierarchy fans out to reduce origin requests; both are the same move against a different cost. Recognising which move a system is making is usually faster than learning the system.
New structures will keep arriving, and most will not last. The survivors are the ones answering a question that new hardware or a new workload just created. But they will be built from these same moves, because the moves are responses to constraints that have not changed: memory is a hierarchy, coordination is expensive, and you cannot have everything at once.
That last constraint is the one this book opened with, in Chapter 1: there is no free lunch. Every structure is fast at something because it agreed to be slow at something else. Knowing what a structure gave up is knowing when to use it.
Exercises
Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch.
32.1 ★ Name the move. For each technique, say which of the seven moves in §32.5 it makes, and in one sentence why: (a) Dynamo comparing Merkle trees to find divergent keys; (b) a database group commit that flushes the write-ahead log once for many transactions; (c) a Count-Min sketch for per-flow traffic; (d) Redis forking to write an RDB snapshot while the parent keeps serving writes; (e) a Chord finger table; (f) a Delta Lake checkpoint.
Solution
(a) Divide the space so most of it can be discarded. A matching subtree hash rules out every key below it, so the comparison only descends where differences are.
(b) Batch the expensive thing. An fsync costs about the same for one commit record as for a hundred, so paying it once per batch divides its cost among the transactions.
(c) Trade exactness for space. Fixed memory independent of the number of flows, in exchange for estimates that can only be too high.
(d) Share what didn’t change. After fork, parent and child share every memory page copy-on-write; only pages the parent modifies during the snapshot get copied.
(e) Divide the space so most of it can be discarded. Each hop jumps to the finger that most closely precedes the key, at least halving the remaining distance, so the lookup ignores most of the ring.
(f) Trade space for time. The checkpoint stores redundant state (everything the log already implies) so that readers can skip replaying the log from the start. It also sits on top of the “never mutate; append and reference” move that makes the log itself.
Several techniques make two moves at once, as (f) shows; naming the dominant one is the useful part.
32.2 ★ Put numbers on Grover. An unsorted table has n = 2^40 (about 10^12) records. Compare the expected number of probes to find one marked record by (a) linear scan, (b) Grover’s algorithm (about (π/4)√n oracle queries), (c) binary search after sorting. Then: how many Grover iterations does a preimage attack on a 128-bit hash need, and on a 256-bit hash?
Solution
(a) Linear scan: n/2 ≈ 5.5 × 10^11 probes on average.
(b) Grover: (π/4) × 2^20 ≈ 823,550 queries. A real speedup of more than five orders of magnitude, if a quantum memory holding the table existed (it does not; see the QRAM caveat).
(c) Binary search: log₂(2^40) = 40 comparisons, after a one-time sort. Grover loses to a classical index by a factor of about 20,000, which is the chapter’s point: Grover only competes where no structure can be built.
Hash preimages: Grover reduces a 2^k search to about 2^(k/2) iterations. A 128-bit hash falls to about 2^64, which is within reach of a large attacker, so it no longer counts as 128-bit secure. A 256-bit hash needs about 2^128, which keeps a comfortable margin. Hence the guidance to use 256-bit hashes for long-lived Merkle trees and content addresses.
32.3 ★★ Rechecking a settled question. Two designs serve a request. Design A does 2 random 4 KB page reads. Design B does 1 random read and then a 1 MB sequential read. Assume an HDD with 10 ms per random read and 200 MB/s sequential, and an NVMe SSD with 10 μs per random read and 3 GB/s sequential. Which design wins on each device, and by how much?
Hint
Compute the time for 1 MB of sequential transfer on each device first.
Solution
Sequential 1 MB: HDD 1/200 s = 5 ms; NVMe 1/3000 s ≈ 0.33 ms.
| HDD | NVMe | |
|---|---|---|
| A: 2 random | 20 ms | 0.02 ms |
| B: 1 random + 1 MB sequential | 10 + 5 = 15 ms | 0.01 + 0.33 ≈ 0.34 ms |
On the HDD, B wins by 25%: avoiding one seek is worth reading a whole megabyte. On NVMe, A wins by a factor of about 17: random reads are so cheap that reading extra data sequentially is now the expensive part.
Nothing about the algorithms changed. The ratio of random to sequential cost moved by orders of magnitude, and the preferred design flipped. Designs that read extra data to avoid seeks (large pages, wide sequential scans, aggressive prefetching) were tuned to the left column; that is the chapter’s “NVMe is quietly reopening settled questions” in two lines of arithmetic.
32.4 ★★ Which way does it err? For each use, name the structure’s error direction and decide whether it is safe: (a) a Bloom filter in front of an SSTable to skip disk reads for absent keys; (b) a Bloom filter of revoked session tokens, checked on each request; (c) a Bloom filter of users allowed into an admin panel; (d) billing each customer by a Count-Min sketch estimate of their API calls; (e) a HyperLogLog count of unique visitors on a public dashboard.
Solution
A Bloom filter has false positives (says “present” for an absent item) and never false negatives. A Count-Min sketch only overestimates. HyperLogLog has a symmetric relative error, typically around 1 to 2%.
(a) Safe. A false positive means one wasted disk read; a false negative cannot happen, so no stored key is ever missed.
(b) Safe for security. A revoked token is always caught. A false positive rejects a valid token, which costs a user a re-login. That is an availability cost, and the false-positive rate controls how often it happens.
(c) Unsafe. A false positive admits someone who is not on the list. The error falls on the side that matters, and no false-positive rate is low enough for access control.
(d) Unsafe as designed. Every error overcharges the customer, and colliding with a heavy customer can overcharge a light one by a lot. Bill from exact counts, and use the sketch for detecting heavy hitters or for alerting.
(e) Safe. A 1 to 2% error either way on a public visitor count costs nothing, and exact counting would need memory proportional to the number of visitors.
The same structure is right in (a) and (b) and wrong in (c): the question is never only “how often is it wrong?” but “which way, and what does that mistake cost here?”
32.5 ★★ Write the invariant checker. Principle 10 in §32.4 says to write a predicate that must hold after every operation. For a binary search tree whose nodes store size (the number of nodes in their subtree, used for order-statistic queries), write check(root) that asserts both the ordering invariant and the size invariant in one O(n) pass. Then show it catching an insert that forgets to update size on the way back up, on the first operation where the bug has an effect.
Hint
Checking only left.key < node.key < right.key at each node is not enough for the ordering invariant. Pass down the bounds that every key in a subtree must respect.
Solution
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.size = 1 # number of nodes in this subtree
def size(node):
return node.size if node else 0
def check(node, lo=None, hi=None):
"""Assert the BST and size invariants; return the subtree size."""
if node is None:
return 0
assert lo is None or node.key > lo, f"{node.key} not > {lo}"
assert hi is None or node.key < hi, f"{node.key} not < {hi}"
n = 1 + check(node.left, lo, node.key) + check(node.right, node.key, hi)
assert node.size == n, f"size of {node.key} is {node.size}, expected {n}"
return n
def insert_buggy(root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = insert_buggy(root.left, key)
elif key > root.key:
root.right = insert_buggy(root.right, key)
return root # forgot: root.size += 1 on the way back up
def insert(root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
elif key > root.key:
root.right = insert(root.right, key)
else:
return root # duplicate: nothing changes, so no size update
root.size = 1 + size(root.left) + size(root.right)
return root
root = None
for k in [50, 30, 70, 20, 40]:
root = insert(root, k)
check(root)
assert root.size == 5
bad = None
caught = None
for k in [50, 30, 70]:
bad = insert_buggy(bad, k)
try:
check(bad)
except AssertionError as e:
caught = (k, str(e))
break
assert caught == (30, "size of 50 is 1, expected 2")
check passes an open interval (lo, hi) down the tree: a node in the right subtree of 50 that sits in the left subtree of 70 must lie strictly between 50 and 70. Checking only parent against child would accept a 60 placed in the left subtree of 30, under 50’s left side, which is a broken tree. The same recursion returns the true subtree size, so verifying size costs nothing extra: one visit per node, O(n).
The buggy insert of 30 under 50 leaves 50’s size at 1, and check fails on that very insert with “size of 50 is 1, expected 2”. Without the checker, the tree still looks fine to every search and traversal; the bug would surface much later as a wrong answer from a rank or k-th smallest query, far from its cause. Run the checker in tests and debug builds only, since O(n) per operation would turn an O(log n) structure into an O(n) one.
32.6 ★★★ Ten times what? A profile service stores 10^8 user records in a B-tree with a fanout of about 200 per page, takes 5,000 writes per second, and serves 50,000 reads per second. For each of the three ways it can grow tenfold (data, write rate, concurrent readers), say what breaks first, what structural change you would make, and what that change costs. Quantify the data case.
Hint
For the data case, count B-tree levels: how many keys do 3 levels and 4 levels of fanout 200 address?
Solution
10× data (10^9 records). Three levels of fanout 200 address 200³ = 8 × 10⁶ keys; four levels address 1.6 × 10⁹. So 10⁸ and 10⁹ records both need 4 levels: tenfold data adds no extra level and no extra page reads per lookup. What does change is whether the upper levels stay in memory and whether the data fits on one machine. The structural change, if any, is sharding by key (consistent hashing or a fixed vnode map), which costs cross-shard queries and a rebalancing story. The B-tree itself handles this growth well, which is the chapter’s point.
10× writes (50,000 per second). In-place B-tree updates turn each write into random page writes plus WAL, and the write rate saturates the device or contends on hot pages. The change is an LSM tree: writes go to a WAL and an in-memory memtable, then are flushed as sorted runs, all sequential. The cost is read amplification (a lookup may check several levels, mitigated by Bloom filters), space amplification until compaction, and background compaction that competes for I/O and can cause latency spikes.
10× concurrent readers (500,000 reads per second). Readers contending with writers on locks, and one machine’s CPU and network, run out first. The change is to make reads not interfere with writes: MVCC or immutable snapshots, so a reader works on a fixed version with no locks, plus read replicas and caches to spread the load. The cost is staleness (a replica or snapshot can lag the latest write) and memory for keeping old versions until no reader needs them.
Each answer is a different structure, which is why “design for 10× scale” without naming the dimension gives no guidance. A system built for all three at once pays all three costs, even if only one kind of growth ever arrives.
Where this connects
- Chapter 25: Complete Selection Guide and Complexity Reference. The selection guide, for putting this into practice
- Chapter 1: The Philosophy and Mathematics of Data Structures. Where the no-free-lunch argument started
Appendix A: Complexity Cheat Sheet
Two conventions for reading these tables:
- Average assumes random or well-distributed data. Worst is the adversarial case. Where they differ, the gap is usually the whole story. A hash table is O(1) average and O(n) worst, and which one you get depends on your hash function and your adversary.
- ★ marks amortized bounds: cheap on average across a sequence of operations, with occasional expensive ones. A dynamic array append is O(1)★ because the resize that costs O(n) happens rarely enough to average out.
A.1 Linear Structures
| Structure | Access by index | Search by value | Insert | Delete | Space |
|---|---|---|---|---|---|
| Static array | O(1) | O(n) | n/a | n/a | O(n) |
| Sorted array | O(1) | O(log n) | O(n) | O(n) | O(n) |
| Dynamic array | O(1) | O(n) | O(1)★ at end, O(n) elsewhere | O(n) | O(n) |
| Singly linked list | O(n) | O(n) | O(1) given the node | O(1) given the previous node | O(n) |
| Doubly linked list | O(n) | O(n) | O(1) given the node | O(1) given the node | O(n) |
| Stack | n/a | O(n) | O(1)★ | O(1)★ | O(n) |
| Queue | n/a | O(n) | O(1)★ | O(1)★ | O(n) |
| Deque | O(1) | O(n) | O(1)★ at either end | O(1)★ at either end | O(n) |
| Circular buffer (fixed capacity) | O(1) | O(n) | O(1) at the rear | O(1) at the front | O(capacity) |
| Bit array | O(1) | O(n/w) | O(1) set a bit | O(1) clear a bit | n bits |
| Persistent vector (32-way trie) | O(log₃₂ n) | O(n) | O(log₃₂ n) append, path copied | O(log₃₂ n) update | O(n), shared between versions |
| Finger tree | O(log n) by index; O(1)★ at the ends | O(n) | O(1)★ at either end | O(1)★ at either end | O(n) |
| Gap buffer (text) | O(1) | O(n) | O(1) at the cursor, O(distance) to move it | O(1) at the cursor | O(n) |
| Rope (text) | O(log n) | O(n) | O(log n) anywhere | O(log n) anywhere | O(n) |
| Piece table (text, list of k pieces) | O(k) | O(n) | O(k), text itself never moves | O(k) | O(n + k) |
Where w = machine word size in bits.
The linked-list rows come with the caveat that makes them much less useful than they look: insertion and deletion are O(1) only once you already hold the relevant node. Getting there is O(n), so an insert-at-position is O(n) overall.
A.2 Trees and Ordered Maps
| Structure | Search (avg) | Search (worst) | Insert | Delete | Space |
|---|---|---|---|---|---|
| BST (unbalanced) | O(log n) | O(n) | O(log n) / O(n) | O(log n) / O(n) | O(n) |
| AVL tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Red-black tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Splay tree | O(log n)★ | O(n) single op | O(log n)★ | O(log n)★ | O(n) |
| Left-leaning red-black tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Treap | O(log n) expected | O(n) | O(log n) expected | O(log n) expected | O(n) |
| Skip list | O(log n) expected | O(n) | O(log n) expected | O(log n) expected | O(n) expected |
| B-tree / B+ tree | O(log_B n) I/Os | O(log_B n) I/Os | O(log_B n) | O(log_B n) | O(n) |
| Order-statistic tree (size-augmented balanced BST) | O(log n) select / rank | O(log n) | O(log n) | O(log n) | O(n) |
| van Emde Boas tree (integer keys < u) | O(log log u) | O(log log u) | O(log log u) | O(log log u) | O(u), or O(n log log u) hashed |
| y-fast trie (integer keys < u) | O(log log u) | O(log log u) | O(log log u)★ | O(log log u)★ | O(n) |
| Trie | O(L) | O(L) | O(L) | O(L) | O(N·A) |
| Radix / Patricia trie | O(L) | O(L) | O(L) | O(L) | O(N) |
Where L = key length, N = total characters stored across all keys, A = alphabet size.
On a BST of height h, successor, predecessor, floor and ceiling are O(h), and reporting every key in a range is O(h + k) for k results. A B-tree with minimum degree t has height at most log_t((n+1)/2); with t = 500, a billion keys fit in 4 levels. (Chapter 7, Chapter 10)
AVL insertion needs at most one single or double rotation, but AVL deletion may rotate at every level on the way up, O(log n) rotations. Red-black trees need at most 2 rotations per insert and 3 per delete, plus O(log n) recolourings (Chapter 8).
Two rows worth reading carefully. Skip list space is O(n) expected, not O(n log n): with promotion probability p = ½, the expected total number of nodes across all levels is 2n. The O(log n) is the expected height, which is a different quantity. And splay trees have no per-operation guarantee at all: a single access can cost O(n), and only a sequence of m operations is bounded, at O(m log n). That makes them unsuitable for latency-sensitive work regardless of their excellent amortized behavior.
A.3 Hash-Based Structures
| Structure | Search (avg) | Search (worst) | Insert | Delete | Space |
|---|---|---|---|---|---|
| Hash table (chaining) | O(1) | O(n) | O(1)★ | O(1) | O(n + m) |
| Hash table (open addressing) | O(1) | O(n) | O(1)★ | O(1) | O(m) |
| Robin Hood hashing | O(1) | O(n) | O(1)★ | O(1), backward shift | O(m) |
| Swiss table | O(1) | O(n) | O(1)★ | O(1) | O(m) plus 1 control byte per slot |
| Cuckoo hashing | O(1) | O(1) worst case | O(1)★ expected | O(1) | O(n) |
| Perfect hashing (static) | O(1) | O(1) | n/a | n/a | O(n) |
Where m = number of buckets. Cuckoo hashing is the notable row: it is one of the few hash schemes with a genuine O(1) worst-case lookup, because a key can only live in one of two positions. Insertion pays for it, and can fail and require a full rehash.
Robin Hood hashing has the same average probe length as plain linear probing; what it improves is the variance, so the longest probe sequence and the cost of an unsuccessful lookup (which can stop early) drop sharply at high load. (Chapter 12)
Java’s HashMap converts a bucket to a red-black tree past 8 entries, giving O(log n) rather than O(n) in the worst case: a defense against deliberate collision flooding.
A.4 Heaps and Priority Queues
| Structure | Find min | Insert | Delete min | Decrease key | Merge | Space |
|---|---|---|---|---|---|---|
| Binary heap | O(1) | O(log n) | O(log n) | O(log n) | O(n) | O(n) |
| Indexed binary heap (position map) | O(1) | O(log n) | O(log n) | O(log n), and O(1) to locate the item | O(n) | O(n) |
| d-ary heap | O(1) | O(log_d n) | O(d·log_d n) | O(log_d n) | O(n) | O(n) |
| Binomial heap | O(log n) | O(1)★ | O(log n) | O(log n) | O(log n) | O(n) |
| Fibonacci heap | O(1) | O(1) | O(log n)★ | O(1)★ | O(1) | O(n) |
| Pairing heap | O(1) | O(1) | O(log n)★ | o(log n)★, exact bound open | O(1) | O(n) |
Building a heap from n existing elements is O(n), not O(n log n): Floyd’s bottom-up heapify. This surprises people and is worth remembering.
The pairing heap’s decrease-key is known to be Ω(log log n)★ (Fredman, 1999) and o(log n)★ (Pettie’s 2005 bound is O(2^(2√(log log n)))★), but its exact cost is still an open problem.
Fibonacci heaps have the best bounds on this table and lose to binary heaps on most real workloads; see Chapter 19.
A.5 Graphs
For a graph with V vertices and E edges:
| Operation | Adjacency list | Adjacency matrix | CSR (static) |
|---|---|---|---|
| Space | O(V + E) | O(V²) | O(V + E), no pointers |
| Add edge | O(1) | O(1) | O(V + E) rebuild |
| Check edge (u,v) | O(deg(u)) | O(1) | O(log deg(u)) if sorted |
| Iterate neighbors of u | O(deg(u)) | O(V) | O(deg(u)), sequential |
| BFS / DFS | O(V + E) | O(V²) | O(V + E) |
| Algorithm | Complexity | Requires |
|---|---|---|
| BFS / DFS | O(V + E) | n/a |
| Cycle detection (directed, three-colour DFS) | O(V + E) | n/a |
| Bipartiteness check (BFS 2-colouring) | O(V + E) | n/a |
| Topological sort (Kahn or DFS) | O(V + E) | DAG; Kahn also detects cycles |
| Strongly connected components (Kosaraju, Tarjan) | O(V + E) | Directed graph |
| 0-1 BFS | O(V + E) | Edge weights 0 or 1 |
| DAG shortest paths | O(V + E) | DAG, any weights |
| Dijkstra (binary heap) | O((V + E) log V) | Non-negative weights |
| Dijkstra (Fibonacci heap) | O(E + V log V) | Non-negative weights |
| Bellman-Ford | O(V·E) | Detects negative cycles |
| Floyd-Warshall | O(V³) | All pairs; negative edges but no negative cycles |
| Johnson’s algorithm | O(V·E log V) | All pairs, sparse graphs, negative edges |
| Kruskal MST | O(E log E) | Union-find |
| Prim MST (binary heap) | O(E log V) | n/a |
| Union-Find (path compression + union by rank) | O(α(n)) ★ | n/a |
| Union-Find with rollback | O(log n) | No path compression |
That last row is a common trap. Rollback requires undoing parent changes, which path compression makes impossible to track cheaply, so rollback DSU uses union by rank alone and costs O(log n), not O(α(n)).
α(n) is the inverse Ackermann function, below 5 for any n that fits in the observable universe.
A.6 Probabilistic and Specialized
| Structure | Query | Insert | Space | Error |
|---|---|---|---|---|
| Bloom filter | O(k) | O(k) | ~1.44·log₂(1/ε)·n bits | False positives only |
| Counting Bloom filter | O(k) | O(k) | 4× a Bloom filter | False positives only |
| Cuckoo filter | O(1) | O(1)★ | ~(log₂(1/ε) + 3)·n bits | False positives; supports delete |
| HyperLogLog | O(1) | O(1) | O(log log n) bits per register; 12 KB in the standard configuration | ~0.81% standard error with 16,384 registers (1.04/√m) |
| Roaring bitmap | O(log c) to find the container, then O(1) or O(log 4096) | O(log c), plus up to 4,096 shifted values in an array container | ≤ 16 bits per value within a container | None, exact |
| Count-Min Sketch | O(k) | O(k) | O((1/ε)·log(1/δ)) | Overestimates only |
| Skip list | O(log n) expected | O(log n) expected | O(n) expected | None, exact |
Where c = number of non-empty Roaring containers (at most 65,536 for 32-bit values).
A Bloom filter with 1% false-positive rate needs about 9.6 bits per element regardless of how large the elements are, which is the property that makes it useful.
A.7 Competitive Programming Structures
| Structure | Build | Query | Update | Space |
|---|---|---|---|---|
| Prefix sum array | O(n) | O(1) | Rebuild O(n) | O(n) |
| Fenwick tree (BIT) | O(n) | O(log n) | O(log n) | O(n) |
| Segment tree | O(n) | O(log n) | O(log n) | O(n) |
| Segment tree + lazy propagation | O(n) | O(log n) | O(log n) range | O(n) |
| Sparse table | O(n log n) | O(1) | Not supported | O(n log n) |
| Sqrt decomposition | O(n) | O(√n) | O(1) | O(n) |
| Mo’s algorithm | n/a | O(√n) ★ per query | n/a | O(n) |
| Heavy-light decomposition | O(n) | O(log² n) | O(log² n) | O(n) |
| Link-cut tree | O(n) | O(log n)★ | O(log n)★ | O(n) |
| Wavelet tree | O(n log σ) | O(log σ) | Static | O(n log σ) |
| Suffix array (SA-IS) | O(n) | O(m log n) | Static | O(n) |
| Suffix automaton | O(n) | O(m) | Incremental | O(n), ≤ 2n−1 states |
| Suffix tree | O(n) | O(m) | Static | O(n) |
| Palindromic tree (eertree) | O(n) | O(1)★ | Incremental | O(n) |
| Li Chao tree | O(n log C) by n inserts | O(log C) | O(log C) | O(n) |
Where σ = alphabet size, m = pattern length, C = coordinate range.
Mo’s algorithm is offline and processes q queries in O((n + q)√n) total; the O(√n) figure is the amortized per-query share, not a bound on any single query.
A.8 Array and Sequence Techniques
| Technique | Time | Extra space | Requires |
|---|---|---|---|
| Binary search (lower / upper bound) | O(log n) | O(1) | Sorted array |
| Binary search on the answer | O(log R) predicate calls | O(1) | Monotone predicate over a range of size R |
| Two pointers | O(n) | O(1) | Sorted array (for pair-sum style problems) |
| Sliding window (fixed or variable) | O(n) | O(1) | Non-negative values for the variable “sum ≥ target” form |
| Prefix sums (1-D) | O(n) build, O(1) range sum | O(n) | Static array |
| Prefix sums (2-D) | O(rc) build, O(1) rectangle sum | O(rc) | Static r × c matrix |
| Difference array | O(1) per range add, O(n) to rebuild | O(n) | All updates before reads |
| Monotonic stack (next greater element) | O(n) total, amortized | O(n) | n/a |
| Monotonic deque (sliding-window maximum) | O(n) total, amortized | O(k) | n/a |
| In-place linked-list reversal | O(n) | O(1) | n/a |
| Floyd’s cycle detection | O(μ + λ) | O(1) | n/a |
| Merge sort on a linked list | O(n log n) | O(log n) stack, O(1) bottom-up | n/a |
Where μ = distance to the cycle and λ = cycle length.
| String matching | Preprocess | Search a text of length n | Notes |
|---|---|---|---|
| KMP (prefix function) | O(m) | O(n) worst case | Never backs up in the text |
| Z-algorithm | O(n + m) total | O(n + m) worst case | Search P + separator + T |
| Rabin-Karp (rolling hash) | O(m) | O(n + m) expected | Random base and a large prime; verify matches to make it exact |
| Aho-Corasick (many patterns) | O(total pattern length) | O(n + number of matches) | One pass for every pattern |
| Suffix array (search) | O(n) to O(n log n) build | O(m log n) per query | Index the text once, query many patterns |
| Posting-list intersection (lists of length m ≤ n) | Time |
|---|---|
| Linear merge | O(m + n) |
| Galloping (exponential) search | O(m log(n/m)) |
| Skip pointers | Between the two, depending on skip spacing |
A.9 Caches and Load Balancing
| Structure | Per access | Metadata per entry | Scan-resistant |
|---|---|---|---|
| LRU (hash map + doubly linked list) | O(1) | Two pointers | No |
| LFU (frequency buckets) | O(1) | Pointers plus a count | Yes, but slow to forget |
| CLOCK (second chance) | O(1) amortized | One reference bit | No |
| ARC | O(1) | Pointers, plus ghost lists | Yes |
| W-TinyLFU | O(1) | Pointers, plus a shared Count-Min sketch | Yes |
| Load balancing rule | Maximum load, n requests into n servers |
|---|---|
| Uniformly random | Θ(log n / log log n) with high probability |
| Power of d choices (d ≥ 2) | ln ln n / ln d + Θ(1) with high probability |
See Chapter 29 for the simulations behind both tables.
A.10 Allocators, Clocks and Routing
| Memory allocator | malloc | free | Fragmentation |
|---|---|---|---|
| Implicit free list, first fit | O(blocks) | O(1) with boundary tags | External; depends on placement policy |
| Segregated free lists (size classes) | O(1) typical | O(1) | Internal, bounded by class spacing (about 20% in jemalloc) |
| Buddy system | O(log M) splits | O(log M) merges | Internal, up to about 50% from rounding to a power of two |
| Slab (fixed-size objects) | O(1) | O(1) | Little, for objects of one size |
| Arena / bump | O(1) | Only all at once | None until reset |
Where M = the size of the managed region in units of the smallest block (Chapter 2).
| Logical clock | Timestamp size | Detects concurrency? | Close to wall-clock time? |
|---|---|---|---|
| Lamport clock | O(1) | No | No |
| Vector clock | O(n) for n processes | Yes | No |
| Hybrid logical clock | O(1) | No | Yes, within the clock skew |
| Routing lookup (W-bit addresses, N prefixes) | Memory reads per lookup | Memory |
|---|---|---|
| Binary trie | Up to W | Up to 1 + N·W nodes |
| Multibit trie, stride k | ⌈W/k⌉ | Grows with 2^k per node (controlled prefix expansion) |
| DIR-24-8 (IPv4) | 1 for prefixes up to /24, else 2 | 32 MB first-level table plus second-level blocks |
| Maglev table (ECMP / load balancing) | 1 hash and 1 table read | O(M) for a prime table size M |
A.11 Complexity Growth Reference
How the classes actually behave, for intuition about when each becomes infeasible:
| n | O(log n) | O(n) | O(n log n) | O(n²) | O(2ⁿ) |
|---|---|---|---|---|---|
| 10 | 3 | 10 | 33 | 100 | 1,024 |
| 100 | 7 | 100 | 664 | 10,000 | 10³⁰ |
| 1,000 | 10 | 1,000 | 9,966 | 10⁶ | n/a |
| 10⁶ | 20 | 10⁶ | 2×10⁷ | 10¹² | n/a |
| 10⁹ | 30 | 10⁹ | 3×10¹⁰ | 10¹⁸ | n/a |
Rough practical ceilings at roughly 10⁸ simple operations per second: O(n²) is fine to n ≈ 10,000; O(n log n) to n ≈ 10⁷; O(n) to n ≈ 10⁸; O(2ⁿ) to n ≈ 25; O(n!) to n ≈ 11.
Appendix B: When to Use What
B.1 The Short Answer
| Need | Structure |
|---|---|
| Fast lookup by key | Hash table |
| Ordered data | Balanced BST, B+ tree |
| Range queries | B+ tree, segment tree |
| Priority access | Heap |
| LIFO | Stack |
| FIFO | Queue |
| Graph traversal | Adjacency list |
| String prefix | Trie |
| Approximate membership | Bloom filter |
| Approximate counting | HyperLogLog |
| 2D spatial | R-tree, KD-tree |
| 3D spatial | Octree |
B.2 The Decision, in Four Questions
Most structure choices resolve with these, asked in order.
1. Do I ever need the elements in order?
This is the single most consequential question, and the one most often skipped. Ordered iteration, range queries, “the next key after X”, and “the smallest key” all require a tree or a sorted structure. A hash table can do none of them at any price.
The failure mode is not discovering this on day one. It is discovering it six months in, when someone asks for “all records between these two dates” and the answer requires replacing the container.
| Order needed? | Go to |
|---|---|
| No, point lookups only | Hash table |
| Yes | Balanced BST (in memory), B+ tree (on disk) |
| Only by priority, one at a time | Heap |
| Only by prefix | Trie or radix tree |
2. What is the read/write mix?
| Pattern | Favors |
|---|---|
| Read-heavy, rarely changes | Sorted array, perfect hash, immutable structure |
| Balanced | Hash table, balanced BST |
| Write-heavy | LSM tree, append-only log |
| Append-only | Dynamic array, log |
3. Where does it live?
| Location | Constraint | Choose |
|---|---|---|
| CPU cache / small | Constant factors dominate | Array, linear scan |
| RAM | Pointer chasing costs | Hash table, B-tree (not BST) |
| Disk / SSD | Block transfers dominate | B+ tree, LSM tree |
| Across machines | Round trips dominate | Consistent hashing, CRDT, DHT |
4. How exact must it be?
If an approximate answer is acceptable, the space savings are usually one to five orders of magnitude, but check which way the errors go first (Chapter 14).
B.3 By Operation
The structure that makes each operation cheapest, with the cost of choosing it.
| Operation | Best choice | Cost of that choice |
|---|---|---|
| Lookup by key | Hash table, O(1) | No ordering at all |
| Lookup by index | Array, O(1) | Insertion in the middle is O(n) |
| Min or max | Heap, O(1) | Arbitrary search is O(n) |
| k-th smallest | Order-statistic tree, O(log n) | Extra size field per node |
| Predecessor / successor | Balanced BST, O(log n) | Slower than a hash table for point lookups |
| Range query | B+ tree or segment tree, O(log n + k) | Higher write cost |
| Prefix match | Trie, O(P) | Memory per node |
| Insert at both ends | Deque, O(1) | No O(1) middle insertion |
| Insert in the middle given a position | Linked list, O(1) | Finding the position is O(n) |
| Merge two collections | Leftist / pairing heap, O(log n) | Slower than a binary heap otherwise |
| Membership, huge set | Bloom filter, O(k) | False positives; no enumeration |
| Count distinct | HyperLogLog, O(1) | ~0.81% standard error in 12 KB |
| Connectivity under merging | Union-find, O(α(n)) | Cannot split |
B.4 By Scale
The right answer changes with n, and the changes are larger than intuition suggests.
| n | What actually wins |
|---|---|
| < 100 | A flat array and a linear scan. One cache line at a time, perfect prefetching, no hashing. Clever structures usually lose here. |
| 10³–10⁶ | Hash tables, balanced trees. Classic complexity analysis applies cleanly. |
| 10⁶–10⁹ | Cache and memory layout dominate. Prefer B-trees over BSTs, arrays over pointer chains. |
| > RAM | External memory model. B+ trees, LSM trees, memory-mapped files. |
| > one machine | Sharding, consistent hashing, replication. Coordination becomes the cost. |
B.5 Common Mistakes
Using a linked list because insertion is O(1). It is O(1) only once you already hold the node. Finding it is O(n), and the traversal is cache-hostile. std::vector beats std::list for middle insertion at surprisingly large sizes: measure before believing otherwise.
Using a hash map when you needed order. See B.2, question 1. This is the most expensive mistake on this page because it surfaces late.
Reaching for a fancy structure at small n. A segment tree over 50 elements is slower than a loop, and considerably more code to get wrong.
Ignoring the worst case on untrusted input. A hash table is O(1) average and O(n) adversarial. If users can choose the keys, you need a keyed hash or a treeifying table (Chapter 12).
Optimizing before profiling, and profiling the wrong thing. If a function is slow and the arithmetic is trivial, the problem is memory, and only hardware counters will show it (Chapter 22).
Testing with random data. Real data arrives sorted far more often than random data does: by timestamp, by ID, by insertion order. Sorted input is the worst case for a naive BST and for quicksort with a fixed pivot. Test sorted, reverse-sorted, and all-identical deliberately.
B.6 Language Defaults
What to reach for first, per language, before writing anything custom.
| Need | Python | Java | C++ | Go | Rust |
|---|---|---|---|---|---|
| Hash map | dict | HashMap | unordered_map | map | HashMap |
| Ordered map | None (use sortedcontainers) | TreeMap | map | n/a | BTreeMap |
| Dynamic array | list | ArrayList | vector | slice | Vec |
| Deque | collections.deque | ArrayDeque | deque | n/a | VecDeque |
| Heap | heapq (min only) | PriorityQueue | priority_queue (max) | container/heap | BinaryHeap (max) |
| Set | set | HashSet | unordered_set | map[T]struct{} | HashSet |
| Ordered set | n/a | TreeSet | set | n/a | BTreeSet |
Two traps worth remembering: Python has no ordered map or tree in the standard library. dict preserves insertion order, which is not the same as sorted order. And heapq is min-only while C++ and Rust default to max-heaps, which is a reliable source of inverted-comparator bugs when porting.
For fuller detail on what these are actually implemented as, see Chapter 22; for exact complexities, Appendix A.
Appendix C: Glossary
Complexity and Analysis
ADT (Abstract Data Type): A data type defined by its operations, not implementation. A stack is an ADT; an array-backed stack is an implementation.
Amortized: Average cost over a sequence of operations, where occasional expensive operations are paid for by many cheap ones. A dynamic array append is O(1) amortized because the O(n) resize happens rarely enough to average out. Distinct from average case, which is about input distribution rather than operation sequences.
Asymptotic: Describing behavior as input size grows without bound. Says nothing about small inputs, which is why an O(n log n) algorithm can lose to an O(n²) one at n = 50.
Big-O: An upper bound on growth. Θ is a tight bound and Ω a lower bound; most practical writing uses O loosely to mean Θ.
Expected: Average over the structure’s own random choices, not over inputs. A skip list is O(log n) expected regardless of input, because the randomness is internal.
Inverse Ackermann α(n): A function growing so slowly it is below 5 for any n that could physically exist. The bound on union-find with path compression.
Time / Space Complexity: How running time or memory grows with input size.
Word RAM: A cost model in which memory holds w-bit words and arithmetic and bitwise operations on a word cost O(1). It is the model in which integer structures such as van Emde Boas trees beat the O(log n) comparison bound.
Worst case: The maximum over all inputs, including adversarial ones. The bound that matters when input is untrusted.
Structural Terms
2-3-4 Tree: A balanced search tree whose nodes hold one, two or three keys. A red-black tree is a binary encoding of one: each black node together with its red children is one 2-3-4 node.
Augmented Tree: A tree whose nodes store extra summary data about their subtrees (sizes, sums, maximums) that is kept correct through inserts, deletes and rotations. Order-statistic trees and interval trees are examples.
Balanced Tree: A tree whose subtree heights differ by at most a constant factor, guaranteeing O(log n) height.
Bulk Loading: Building a B-tree or B+ tree bottom-up from sorted data instead of by repeated insertion. Much faster, and it lets you choose how full each node is.
Cursor: A position indicator within a data structure.
Decrease-Key: The priority-queue operation that lowers an existing element’s priority. A binary heap needs a position map (an indexed heap) to find the element first.
Degenerate Tree: A tree that has degraded to essentially a linked list, the worst case for an unbalanced BST.
Double Black: The bookkeeping state in red-black tree deletion when removing a black node leaves one path short of a black node. The four repair cases correspond to borrowing from or merging with a sibling in the 2-3-4 view.
Fan-out: The number of children a node can have. High fan-out is what makes B-trees shallow.
Fill Factor: How full a B-tree’s nodes are allowed or chosen to be. Sorted inserts leave nodes about half full; bulk loading can pack them completely.
Heap Property: Every parent compares greater (max-heap) or less (min-heap) than its children. Note this is a weaker invariant than sorted order.
Invariant: A property that must hold before and after every operation. Writing invariants as runnable assertions is the most effective way to catch structural bugs near their cause.
Leaf: A node with no children.
Left-Leaning Red-Black Tree: A red-black variant (Sedgewick, 2008) in which red links may only lean left, corresponding to 2-3 trees and shortening insertion code considerably.
Minimum Degree (t): The B-tree parameter that bounds node size: every node except the root holds between t − 1 and 2t − 1 keys.
Order Statistic: The k-th smallest element of a set. A BST augmented with subtree sizes answers select (k-th smallest) and rank (position of a key) in O(height).
Predecessor / Successor: The largest key smaller than x, and the smallest key larger than x. The core query of ordered sets, and the problem van Emde Boas trees solve for integer keys.
Rope: A balanced tree whose leaves hold chunks of text, giving O(log n) insert, delete and indexing anywhere in a large string. Used by several text editors.
Sentinel: A dummy node that removes special cases (an empty-list check, a null-pointer test) by guaranteeing a node always exists.
Serialization: Writing a structure to a flat sequence (bytes, text) from which it can be rebuilt. A binary tree needs either null markers or two traversals to be rebuilt exactly.
Tombstone: A marker left in place of a deleted entry so that probe sequences in an open-addressed hash table are not broken.
van Emde Boas Tree: A recursive structure for integer keys below u that splits each key into high and low halves, answering predecessor and successor queries in O(log log u).
Hashing
Collision: When two distinct keys hash to the same index. Unavoidable whenever the key space exceeds the table size.
Control Byte: In a Swiss table, one byte of metadata per slot recording empty, deleted, or full plus 7 bits of the key’s hash. A lookup compares a whole group of control bytes at once before touching any keys.
Hash Flooding: A denial-of-service attack that sends many keys known to collide, turning a hash table’s O(1) operations into O(n). Defended against with seeded, keyed hash functions such as SipHash.
Load Factor (α): Ratio of stored elements to capacity. Open addressing degrades sharply above ~0.7; chaining tolerates α > 1.
Open Addressing: Resolving collisions by probing for another slot within the table itself, rather than chaining externally.
Perfect Hashing: A collision-free hash for a known, fixed key set. Minimal perfect hashing maps n keys onto exactly n slots.
Probe Sequence Length (PSL): How far an entry in an open-addressed table sits from its home slot. Robin Hood hashing keeps PSLs even by letting an inserted key take the slot of any entry closer to home.
Robin Hood Hashing: Linear probing where an inserted key displaces any entry with a shorter probe sequence length. Average cost is unchanged, but the variance and the cost of misses drop sharply.
SipHash: A fast keyed hash function designed to resist hash flooding. The default string hash in Python, Ruby and Rust.
Swiss Table: An open-addressing hash table that stores a control byte per slot and probes 16-slot groups with SIMD instructions. Abseil’s flat_hash_map, Rust’s HashMap and Go’s maps since 1.24 use the design.
Universal Hashing: Choosing a hash function at random from a family, so that no fixed input is reliably bad. The defense against collision-flooding attacks.
Memory and Storage
Arena (Bump Allocator): An allocator that hands out memory by advancing a pointer through a large block and frees everything at once. O(1) allocation, no per-object free; used by compilers and per-request memory pools.
Bit-Packing: Storing a block of small integers in exactly as many bits each as the largest needs. With delta encoding, the basis of posting-list compression in search engines.
Boundary Tag: A size-and-status field stored at both ends of a heap block, so the allocator can find and merge a free neighbour in O(1) when a block is freed.
Buddy Allocator: An allocator that splits memory into power-of-two blocks and merges a freed block with its “buddy”, found by flipping one address bit. The Linux page allocator uses it.
Cache Line: The unit of transfer between memory and cache, typically 64 bytes. Reading one byte costs the same as reading its whole line.
Cache-Oblivious: Achieving optimal I/O performance without knowing the block size. By being well-organized at every scale simultaneously.
External Memory Model: A cost model counting block transfers rather than operations. Predicts real disk performance where the RAM model does not.
Fragmentation: Memory that is free but unusable. Internal fragmentation is wasted space inside allocated blocks (rounding up); external fragmentation is free space split into pieces too small to satisfy a request.
Gap Buffer: A text buffer that keeps one contiguous gap at the cursor, so typing is O(1) but moving the cursor far away costs a large copy. Used by Emacs.
Locality: The tendency of an access pattern to touch nearby addresses. Sequential access has good locality; pointer chasing has none.
LSM Tree (Log-Structured Merge): A write-optimized structure that buffers writes in memory and flushes them as sorted immutable runs, converting random writes to sequential ones.
Page: The unit of transfer between memory and disk, typically 4KB.
Piece Table: A text representation made of an append-only original buffer, an append-only add buffer, and a list of pieces pointing into them. Edits never move text, and undo is cheap.
Segment (search index): An immutable chunk of an inverted index. New documents create new segments, deletions are marked in a bitset, and background merges combine segments, much like LSM-tree compaction.
Size Class: One of a fixed set of block sizes an allocator rounds requests up to, each with its own free list. The basis of jemalloc, tcmalloc and glibc’s bins.
Slab Allocator: An allocator that keeps caches of same-sized, pre-initialized objects carved from pages. Introduced by Bonwick in 1994; Linux’s SLUB is a descendant.
Varint (Variable-Byte Encoding): Encoding an integer in 7-bit groups, one per byte, with the high bit marking that more bytes follow. Small numbers take one byte.
Write Amplification: The ratio of bytes actually written to storage versus bytes logically written by the application.
Persistence and Concurrency
ABA Problem: A compare-and-swap succeeds because a pointer’s value is unchanged, even though the state it refers to has changed and changed back. Defended against with tagged pointers or hazard pointers.
Banker’s Queue: Okasaki’s persistent queue, which keeps amortized O(1) operations even when old versions are reused by scheduling the expensive list reversal lazily and memoizing it.
CAS (Compare-and-Swap): An atomic hardware instruction that sets a memory location to a new value only if it currently holds an expected one. The universal primitive for lock-free programming.
Copy-on-Write: Sharing data until a write occurs, at which point the written portion is duplicated.
Fat Node: A persistence technique that stores every historical value of a field, stamped with its version, inside the node itself. Updates cost O(1) space; reads pay a search over the stamps.
Finger Tree: A persistent sequence with amortized O(1) access at both ends and O(log n) split and concatenation. Annotating it with a monoid yields indexed sequences, priority queues and interval trees from one structure.
Linearizability: Every operation appears to take effect instantaneously at some moment between its call and return, consistent with real time. The standard correctness condition for concurrent objects, and notable for composing.
Lock-Free: Guaranteeing that some thread always makes progress. Weaker than wait-free, which guarantees every thread finishes in bounded steps.
MVCC (Multi-Version Concurrency Control): Keeping multiple versions of each row so readers see a consistent snapshot without blocking writers. Partial persistence, applied to databases.
Path Copying: Achieving persistence by duplicating only the nodes on the path from root to the modification point, O(log n) per update in a balanced tree.
Persistent: Preserving previous versions after modification. Partial persistence allows querying old versions; full allows updating them; confluent allows merging them. Unrelated to durable storage.
Persistent Vector: A persistent array stored as a wide trie (typically 32-way) indexed by groups of bits of the position. Updates copy one root-to-leaf path, O(log₃₂ n). Used by Clojure and Scala.
Structural Sharing: Reusing unchanged subtrees between versions of an immutable structure. What makes persistence affordable.
Distributed Systems
Admission Policy: A cache’s rule for whether a new item should enter at all, rather than which item to evict. W-TinyLFU admits a newcomer only if it is estimated to be more popular than the victim.
CAP Theorem: During a network partition, a distributed system must sacrifice either consistency or availability. See Appendix D for why “CA” is not a third option.
Consistent Hashing: Mapping keys and nodes onto a ring so that adding or removing a node remaps only ~1/n of keys, rather than nearly all of them.
CRDT (Conflict-Free Replicated Data Type): A structure whose merge is commutative, associative, and idempotent, so replicas converge without coordination.
DHT (Distributed Hash Table): A hash table partitioned across many machines, with a routing protocol for locating the responsible node.
ECMP (Equal-Cost Multipath): Spreading traffic across several equally good next hops by hashing each flow’s header fields, so that packets of one flow stay on one path and are not reordered.
Eventual Consistency: A guarantee that replicas converge given no further updates, with no bound on when.
Happens-Before: The causal order of events in a distributed system: a precedes b if they are on the same process in that order, or a message chain connects them. Events not ordered either way are concurrent.
Hybrid Logical Clock (HLC): A timestamp that stays close to physical time but, like a Lamport clock, never violates causality. Used by CockroachDB.
Lamport Clock: A per-process counter incremented on each event and advanced past any timestamp received in a message. If a happens before b then L(a) < L(b), but not conversely.
Maglev Hashing: Google’s consistent hashing scheme for load balancers: each backend fills a prime-sized lookup table in its own permutation order, giving near-perfect balance and little remapping when a backend changes.
Merkle Tree: A tree of hashes where each node hashes its children, allowing two large datasets to be compared (and their differences located) in logarithmic work.
Power of Two Choices: Sending each request to the less loaded of two randomly chosen servers. Cuts the maximum load from Θ(log n / log log n) to Θ(log log n) and avoids the herding that “least loaded” suffers with stale data.
Quorum: A subset of replicas that must acknowledge an operation. Overlapping read and write quorums (R + W > N) give strong consistency.
Scan Resistance: A cache policy’s ability to survive a one-off sequential scan without evicting its genuinely popular items. LRU has none; LFU, ARC and W-TinyLFU do.
Sequence CRDT: A replicated list or text that gives every element a unique, ordered identifier so concurrent inserts and deletes converge. RGA, used in Automerge, is one example.
Vector Clock: A per-replica counter vector that distinguishes causally-ordered updates from genuinely concurrent ones.
Probabilistic and Compressed
Bloom Filter: A bit array with k hash functions giving approximate membership: false positives are possible, false negatives are not.
Count-Min Sketch: A fixed-size frequency estimator over a stream, which overestimates but never underestimates.
HyperLogLog: A cardinality estimator using the maximum leading-zero count of hashes, giving about 0.81% standard error in 12 KB (16,384 registers) regardless of set size.
Rank / Select: The two primitives underlying succinct structures. rank(i) counts 1-bits before position i; select(k) finds the position of the k-th 1-bit.
Roaring Bitmap: A compressed bitmap that splits 32-bit values into 65,536 chunks and stores each chunk as a sorted array, a plain bitmap or a list of runs, whichever is smallest. Used by Lucene, Druid, ClickHouse and many others.
Succinct: Using space within a lower-order term of the information-theoretic minimum, while still supporting queries without decompressing.
Spatial and String
Border: A string that is both a proper prefix and a suffix of another. The prefix function (KMP’s failure function) records the longest border of each prefix of a pattern.
Controlled Prefix Expansion: Rewriting routing prefixes whose length is not a multiple of a trie’s stride into several longer prefixes that are, so a multibit trie can consume several address bits per memory access.
Inverted Index: A map from each term to its posting list, the sorted list of documents containing it. The core structure of full-text search.
LCP Array: Longest Common Prefix between each pair of adjacent suffixes in a suffix array. Together they encode a suffix tree implicitly.
Longest-Prefix Match: The IP routing lookup: among all table prefixes matching an address, choose the longest, because it is the most specific route.
MBR (Minimum Bounding Rectangle): The smallest axis-aligned rectangle enclosing a set of objects. The key type in an R-tree, and overlap between sibling MBRs is what degrades R-tree queries.
Posting List: The sorted list of document IDs (plus frequencies or positions) for one term in an inverted index. Stored as compressed gaps between consecutive IDs.
Rolling Hash: A hash of a sliding window that can be updated in O(1) as the window moves one character. The basis of Rabin-Karp matching and of content-defined chunking in rsync and backup tools.
Space-Filling Curve: A mapping from multi-dimensional coordinates to one dimension that mostly preserves locality, Z-order and Hilbert being the common ones. The basis of geohashing.
Suffix Array: The sorted list of a string’s suffix starting positions. Suffix-tree power at about 4 bytes per character rather than 20.
Trie: A tree keyed by character position, where lookup costs O(key length) independent of how many keys are stored.
Z-Array: For each position i of a string, the length of the longest substring starting at i that matches a prefix of the string. Computed in O(n) and used for pattern matching.
Graphs
Adjacency List / Matrix: The two standard graph representations. A list stores each vertex’s neighbours (O(V + E) space); a matrix stores a V × V table of edges (O(V²) space, O(1) edge test).
Back Edge: In a DFS, an edge to an ancestor still on the recursion stack. A directed graph has a cycle exactly when DFS finds one.
Bipartite: A graph whose vertices split into two sides with every edge crossing between them. Equivalent to having no odd-length cycle.
CSR (Compressed Sparse Row): A static graph layout of two arrays, the concatenated neighbour lists and an offset per vertex. Compact and cache-friendly; adding an edge means rebuilding.
Cut Property: For any split of a graph’s vertices into two groups, the lightest edge crossing the split belongs to some minimum spanning tree. The reason Kruskal’s and Prim’s greedy choices are safe.
DAG (Directed Acyclic Graph): A directed graph with no cycles. Exactly the graphs that have a topological order.
Negative Cycle: A cycle whose edge weights sum to less than zero. Shortest paths through it are undefined; Bellman-Ford detects one.
Relaxation: Updating a vertex’s tentative distance with dist[v] = min(dist[v], dist[u] + w(u, v)). Every shortest-path algorithm is a strategy for which edges to relax in which order.
Strongly Connected Component (SCC): A maximal set of vertices in a directed graph that can all reach one another. Collapsing each SCC to one vertex always leaves a DAG.
Topological Order: An ordering of a DAG’s vertices in which every edge points forward. Used for build systems, scheduling and dependency resolution.
Techniques
Binary Search on the Answer: Binary searching over candidate answers rather than over an array, using a yes/no test that is monotone in the answer (for example, “can everything ship in d days with capacity c?”).
Fast and Slow Pointers: Walking two pointers through a sequence at different speeds. Finds the middle of a linked list in one pass, and detects cycles (Floyd’s algorithm).
Half-Open Interval: A range written [lo, hi) that includes lo and excludes hi. Using it consistently is the easiest way to write a correct binary search.
Lazy Deletion: Leaving stale entries in a structure and skipping them when they surface, instead of removing them immediately. The usual way to get decrease-key behaviour from Python’s heapq.
Lower Bound / Upper Bound: In a sorted array, the first position whose value is ≥ x and the first whose value is > x. Python’s bisect_left and bisect_right.
Monotonic Stack: A stack kept in increasing or decreasing order by popping everything that would break the order before each push. Finds the next greater or smaller element for every position in O(n) total.
Prefix Sum: An array whose i-th entry is the sum of the first i input values, making any range sum a single subtraction. The inverse of a difference array.
Sliding Window: Maintaining an answer over a contiguous window as one end advances, so each element enters and leaves once and the whole scan is O(n).
Two Pointers: Moving two indices through a sorted array (often from both ends) so that each step rules out a candidate, giving O(n) instead of O(n²).
Appendix D: Network and System Design Quick Reference
D.1 Distributed Consistency Levels
| Level | Guarantees | Use Case |
|---|---|---|
| Linearizability | All operations appear atomic | Financial transactions |
| Sequential | Operations appear in order | Inventory management |
| Causal | Causally related operations in order | Social feeds |
| Eventual | Convergence without guarantees | Caching, logging |
| Read-your-writes | Own writes visible immediately | User sessions |
D.2 CAP and PACELC
CAP says that when a network partition occurs, a distributed system must sacrifice either consistency or availability. Partitions are not optional (they are a fact of networks) so the real choice is only ever between CP and AP:
| Choice | During a partition | Example |
|---|---|---|
| CP | Reject requests rather than serve stale or divergent data | ZooKeeper, etcd, HBase, Spanner |
| AP | Keep serving; reconcile afterwards | Cassandra, DynamoDB, Riak |
“CA” is often listed as a third option with a single-node RDBMS as the example. That is a category error: a non-distributed system has no partitions to tolerate, so CAP does not classify it. There is no CA distributed system.
PACELC is the more useful formulation, because it also describes the normal case when nothing is broken: if Partition, then A or C; Else, then L (latency) or C:
| System | Partition behavior | Normal behavior | Reads as |
|---|---|---|---|
| Spanner | CP | Consistency over latency | PC/EC |
| DynamoDB | AP | Latency over consistency | PA/EL |
| Cassandra | AP | Latency over consistency (tunable) | PA/EL |
| MongoDB | CP | Consistency over latency | PC/EC |
The Else half is where most systems actually spend their time, and it is the half CAP says nothing about, which is why “we chose AP” explains far less about a system than people usually intend by it.
D.3 Caching Patterns
| Pattern | Description | Consistency |
|---|---|---|
| Cache-aside | Application manages cache | Stale reads possible |
| Read-through | Cache fetches on miss | Stale reads possible |
| Write-through | Synchronous cache + store | Strong |
| Write-back | Async cache to store | Weak until sync |
D.4 Load Balancing Algorithms
| Algorithm | State Required | Hot Spot Risk | Session Affinity |
|---|---|---|---|
| Round Robin | None | Yes (variable load) | None |
| Least Connections | Per-node count | Lower | None |
| IP Hash | None | Yes (skewed) | Yes |
| Consistent Hash | Ring state | Lowest | Partial |
| Weighted | Weights | Lower | None |
D.5 Data Structure → System Mapping
| Data Structure | System Application |
|---|---|
| Hash table | Key-value stores (Redis, Memcached) |
| B-tree | Relational databases (PostgreSQL, InnoDB) |
| LSM tree | Time-series, write-heavy (RocksDB, Cassandra) |
| Trie | Routing tables, prefix matching |
| Graph | Social networks, recommendation systems |
| Log | Message queues (Kafka), event sourcing |
| Bloom filter | Cache, membership testing (web, CDNs) |
| Consistent hash | Distributed caching, load balancing |
Every system in Volume V reduces to the building blocks in Volumes I–IV. That is the argument the book makes, and this table is the short version of it.
Everything Data Structures: by Ngoc Anh Khoa Doan. Prose is CC BY 4.0; code is MIT.
Bibliography and Further Reading
Classic Textbooks
-
Knuth, D. E. (1997). The Art of Computer Programming, Volume 1: Fundamental Algorithms (3rd ed.). Addison-Wesley.
-
Knuth, D. E. (1998). The Art of Computer Programming, Volume 3: Sorting and Searching (2nd ed.). Addison-Wesley.
-
Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to Algorithms (4th ed.). MIT Press.
-
Sedgewick, R., & Wayne, K. (2011). Algorithms (4th ed.). Addison-Wesley.
-
Okasaki, C. (1998). Purely Functional Data Structures. Cambridge University Press.
-
Tarjan, R. E. (1983). Data Structures and Network Algorithms. SIAM.
-
Morin, P. (2013). Open Data Structures. Athabasca University Press. Freely available at opendatastructures.org.
By Level
| Book | Author | Level |
|---|---|---|
| Open Data Structures | Morin | Introductory (free) |
| Algorithms (4th ed.) | Sedgewick & Wayne | Introductory |
| Introduction to Algorithms | CLRS | Foundational |
| Guide to Competitive Programming | Laaksonen | Intermediate |
| Competitive Programming Handbook | Halim & Halim | Intermediate |
| The Art of Computer Programming, Vol. 4A | Knuth | Advanced |
| Compact Data Structures | Navarro | Research |
| Purely Functional Data Structures | Okasaki | Research |
| The Art of Multiprocessor Programming | Herlihy & Shavit | Research (concurrency) |
Foundational Papers
Trees and search structures
- Adelson-Velsky, G., & Landis, E. (1962). An algorithm for the organization of information. Soviet Mathematics Doklady, 3, 1259–1263. (AVL trees)
- Bayer, R., & McCreight, E. (1972). Organization and maintenance of large ordered indexes. Acta Informatica, 1(3), 173–189. (B-trees)
- Guibas, L. J., & Sedgewick, R. (1978). A dichromatic framework for balanced trees. FOCS. (Red-black trees)
- Sleator, D. D., & Tarjan, R. E. (1985). Self-adjusting binary search trees. Journal of the ACM, 32(3), 652–686. (Splay trees)
- Pugh, W. (1990). Skip lists: A probabilistic alternative to balanced trees. Communications of the ACM, 33(6), 668–676.
- Seidel, R., & Aragon, C. R. (1996). Randomized search trees. Algorithmica, 16(4/5), 464–497. (Treaps)
Heaps and priority queues
- Williams, J. W. J. (1964). Algorithm 232: Heapsort. Communications of the ACM, 7(6), 347–348.
- Fredman, M. L., & Tarjan, R. E. (1987). Fibonacci heaps and their uses in improved network optimization algorithms. Journal of the ACM, 34(3), 596–615.
- Fredman, M. L., Sedgewick, R., Sleator, D. D., & Tarjan, R. E. (1986). The pairing heap. Algorithmica, 1(1), 111–129.
Hashing and probabilistic structures
- Bloom, B. H. (1970). Space/time trade-offs in hash coding with allowable errors. Communications of the ACM, 13(7), 422–426.
- Carter, J. L., & Wegman, M. N. (1979). Universal classes of hash functions. JCSS, 18(2), 143–154.
- Pagh, R., & Rodler, F. F. (2004). Cuckoo hashing. Journal of Algorithms, 51(2), 122–144.
- Cormode, G., & Muthukrishnan, S. (2005). An improved data stream summary: The count-min sketch. Journal of Algorithms, 55(1), 58–75.
- Flajolet, P., Fusy, É., Gandouet, O., & Meunier, F. (2007). HyperLogLog: The analysis of a near-optimal cardinality estimation algorithm. AOFA.
Spatial structures
- Finkel, R. A., & Bentley, J. L. (1974). Quad trees: A data structure for retrieval on composite keys. Acta Informatica, 4(1), 1–9.
- Bentley, J. L. (1975). Multidimensional binary search trees used for associative searching. Communications of the ACM, 18(9), 509–517. (KD-trees)
- Guttman, A. (1984). R-trees: A dynamic index structure for spatial searching. SIGMOD.
- Malkov, Y. A., & Yashunin, D. A. (2016). Efficient and robust approximate nearest neighbor search using HNSW graphs. arXiv:1603.09320.
Persistence and functional structures
- Driscoll, J. R., Sarnak, N., Sleator, D. D., & Tarjan, R. E. (1986). Making data structures persistent. STOC.
- Okasaki, C. (1996). Purely Functional Data Structures (PhD thesis). Carnegie Mellon University.
- Bagwell, P. (2001). Ideal hash trees. EPFL Technical Report. (HAMTs)
Concurrency
- Lamport, L. (1979). How to make a multiprocessor computer that correctly executes multiprocess programs. IEEE Transactions on Computers, C-28(9), 690–691.
- Herlihy, M., & Wing, J. (1990). Linearizability: A correctness condition for concurrent objects. TOPLAS, 12(3), 463–492.
- Herlihy, M. (1991). Wait-free synchronization. TOPLAS, 13(1), 124–149.
- Michael, M. M., & Scott, M. L. (1996). Simple, fast, and practical non-blocking and blocking concurrent queue algorithms. PODC.
- Michael, M. M. (2004). Hazard pointers: Safe memory reclamation for lock-free objects. IEEE TPDS, 15(6), 491–504.
External memory and cache-obliviousness
- Aggarwal, A., & Vitter, J. S. (1988). The input/output complexity of sorting and related problems. Communications of the ACM, 31(9), 1116–1127.
- Frigo, M., Leiserson, C. E., Prokop, H., & Ramachandran, S. (1999). Cache-oblivious algorithms. FOCS.
- O’Neil, P., Cheng, E., Gawlick, D., & O’Neil, E. (1996). The log-structured merge-tree (LSM-tree). Acta Informatica, 33(4), 351–385.
Succinct and compressed structures
- Jacobson, G. (1989). Space-efficient static trees and graphs. FOCS.
- Munro, J. I., & Raman, V. (1997). Succinct representation of balanced parentheses, static trees and planar graphs. FOCS.
- Ferragina, P., & Manzini, G. (2000). Opportunistic data structures with applications. FOCS. (FM-index)
- Raman, R., Raman, V., & Rao, S. S. (2002). Succinct indexable dictionaries. SODA.
- Grossi, R., Gupta, A., & Vitter, J. S. (2003). High-order entropy-compressed text indexes. SODA. (Wavelet trees)
Distributed structures
- Karger, D., et al. (1997). Consistent hashing and random trees. STOC.
- Stoica, I., et al. (2001). Chord: A scalable peer-to-peer lookup service. SIGCOMM.
- Holm, J., de Lichtenberg, K., & Thorup, M. (2001). Poly-logarithmic deterministic fully-dynamic algorithms. Journal of the ACM, 48(4), 723–760.
- DeCandia, G., et al. (2007). Dynamo: Amazon’s highly available key-value store. SOSP.
- Shapiro, M., Preguiça, N., Baquero, C., & Zawirski, M. (2011). Conflict-free replicated data types. SSS.
- Corbett, J. C., et al. (2012). Spanner: Google’s globally-distributed database. OSDI.
- Kleppmann, M., & Beresford, A. R. (2017). A conflict-free replicated JSON datatype. IEEE TPDS, 28(10), 2733–2746.
Learned and emerging
- Kraska, T., Beutel, A., Chi, E. H., Dean, J., & Polyzotis, N. (2018). The case for learned index structures. SIGMOD.
- Ferragina, P., & Vinciguerra, G. (2020). The PGM-index. VLDB, 13(8), 1162–1175.
Competitive Programming Resources
| Resource | Focus |
|---|---|
| CP-Algorithms | Implementation guides with proofs |
| AtCoder Library | Reference implementations in C++ |
| USACO Guide | Structured curriculum by difficulty |
| Codeforces | Problems, editorials, and blog posts |
| Stanford ICPC Notebook | Competition templates |
Online Resources
- Visualgo. Step-through animations of most structures in this book
- Open Data Structures. Pat Morin’s free textbook, with code in several languages
- Big-O Cheat Sheet. Quick complexity reference
- GeeksforGeeks. Implementation tutorials; verify against a primary source
- Papers We Love. Curated CS papers with discussion