diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3712eac..831138e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -14,6 +14,8 @@ Every page on [the site](https://dnakhoa.github.io/everything-data-structures/)
**Worked examples.** Concrete traces through an algorithm, with real numbers, tend to teach better than prose.
+**Exercises.** Every chapter ends with a `## Exercises` section. New exercises should follow the existing format: a bold number and difficulty (`**12.8 ★★ Title.**`), the question, then a `` block with `Solution` (and optionally one for a hint before it). Leave a blank line after `...` and before ``, or the Markdown inside won't render; CI checks this, and checks that exercises are numbered in order. Solutions should show the working, not just the answer, and any code in them should actually run.
+
**Real-world usage.** If you know a production system that uses a structure in a way the book doesn't mention, that's worth adding, especially with a link to source or a design doc.
## What to check before submitting
diff --git a/README.md b/README.md
index 1e4e5be..9a7a062 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@ A complete, free course on data structures, from asymptotic analysis and pointer
**📖 Read it online: [dnakhoa.github.io/everything-data-structures](https://dnakhoa.github.io/everything-data-structures/)**
-Five volumes · 31 chapters · 4 appendices · ~55,000 words · Python, C, C++, Java and Go examples.
+Five volumes · 31 chapters · 4 appendices · ~155,000 words · 225 exercises with worked solutions · Python, C, C++, Java and Go examples.
Written by [Ngoc Anh Khoa Doan](https://github.com/dnakhoa), with the editorial help of Claude.
@@ -21,7 +21,7 @@ Also by the author: **[Frontier LLM Engineering](https://github.com/dnakhoa/fron
Most data structure resources stop at red-black trees. This one keeps going, through competitive-programming machinery (link-cut trees, wavelet trees, Mo's algorithm), through research-grade structures (FM-indexes, succinct trees, fractional cascading), and out the other side into system design, where the central claim of Volume V is that **a routing table is a trie, consistent hashing is a hash ring, and a message queue is a persistent FIFO**. Systems are data structures composed at scale.
-Every chapter covers the same ground: the idea, the invariants, the operations with complexity analysis, working code, real-world usage, and the historical context of who invented it and why.
+Every chapter covers the same ground: the idea, the invariants, the operations with complexity analysis, working code, real-world usage, and the historical context of who invented it and why. Every chapter then ends with an exercise set (★ check your understanding, ★★ apply it, ★★★ stretch), each with a folded worked solution and, for the harder ones, a hint.
---
@@ -54,7 +54,7 @@ The structures that actually come up, plus the judgment to pick between them.
Track 1, then:
- [Chapter 8: Self-Balancing Trees](src/volume-1/ch08-self-balancing-trees.md). AVL, red-black, splay, treaps
-- [Chapter 11: Graphs](src/volume-2/ch11-graphs-modeling-relationships.md). BFS/DFS, topological sort, MST, shortest paths, union-find
+- [Chapter 11: Graphs](src/volume-2/ch11-graphs-modeling-relationships.md). BFS/DFS, cycle detection, topological sort, strongly connected components, union-find, MST, Dijkstra, Bellman-Ford and Floyd-Warshall
- [Chapter 13: String Data Structures](src/volume-2/ch13-string-data-structures.md). Tries, suffix arrays
- [Chapter 14: Probabilistic Data Structures](src/volume-3/ch14-probabilistic-data-structures.md). Bloom filters come up constantly
- [Chapter 25: Complete Selection Guide](src/volume-4/ch25-complete-selection-guide-and-complexity-reference.md). The decision matrix
diff --git a/book.toml b/book.toml
index a1d2edc..f48a915 100644
--- a/book.toml
+++ b/book.toml
@@ -11,6 +11,7 @@ create-missing = false
[output.html]
additional-css = ["theme/custom.css"]
+additional-js = ["theme/print-details.js"]
default-theme = "rust"
preferred-dark-theme = "navy"
git-repository-url = "https://github.com/dnakhoa/everything-data-structures"
diff --git a/scripts/check_book.py b/scripts/check_book.py
index 0c6fbf4..578defc 100644
--- a/scripts/check_book.py
+++ b/scripts/check_book.py
@@ -6,6 +6,9 @@
3. Every chapter page starts with a single H1.
4. Code fences are balanced.
5. SVG files contain no blank lines (a blank line ends the raw-HTML block in Markdown).
+6. Every chapter has an Exercises section, numbered for that chapter, and every
+ hint/solution block is balanced and padded with the blank lines
+ mdBook needs to render the Markdown inside it.
"""
import ast
import glob
@@ -100,6 +103,51 @@ def check_svgs():
print(" svgs checked")
+def check_exercises():
+ chapters = [p for p in iter_md() if re.match(r"ch\d+-", os.path.basename(p))]
+ total = 0
+ for path in chapters:
+ num = int(re.match(r"ch(\d+)-", os.path.basename(path)).group(1))
+ lines = open(path, encoding="utf-8").read().split("\n")
+ if "## Exercises" not in lines:
+ fail("%s: no '## Exercises' section" % path)
+ continue
+ found = re.findall(r"^\*\*(\d+)\.(\d+) ", "\n".join(lines), re.M)
+ if not found:
+ fail("%s: Exercises section has no numbered exercises" % path)
+ for ch, n in found:
+ if int(ch) != num:
+ fail("%s: exercise %s.%s is misnumbered (chapter %d)" % (path, ch, n, num))
+ nums = [int(n) for _, n in found]
+ if nums != list(range(1, len(nums) + 1)):
+ fail("%s: exercises are not numbered 1..%d in order" % (path, len(nums)))
+ total += len(found)
+
+ depth, in_code = 0, False
+ for i, ln in enumerate(lines):
+ if ln.lstrip().startswith("```"):
+ in_code = not in_code
+ if in_code:
+ continue
+ s = ln.strip()
+ if s == "":
+ depth += 1
+ if depth > 1:
+ fail("%s:%d nested " % (path, i + 1))
+ elif s == "":
+ depth -= 1
+ if depth < 0:
+ fail("%s:%d without " % (path, i + 1))
+ if i > 0 and lines[i - 1].strip():
+ fail("%s:%d needs a blank line before " % (path, i + 1))
+ elif s.startswith(""):
+ if i + 1 < len(lines) and lines[i + 1].strip():
+ fail("%s:%d needs a blank line after " % (path, i + 1))
+ if depth != 0:
+ fail("%s: unbalanced blocks" % path)
+ print(" %d exercises in %d chapters checked" % (total, len(chapters)))
+
+
if __name__ == "__main__":
print("Checking book integrity...")
check_python_blocks()
@@ -107,6 +155,7 @@ def check_svgs():
check_headings()
check_internal_links()
check_svgs()
+ check_exercises()
if errors:
print("\n%d problem(s) found:\n" % len(errors))
diff --git a/src/images/bst-successor.svg b/src/images/bst-successor.svg
new file mode 100644
index 0000000..60590ec
--- /dev/null
+++ b/src/images/bst-successor.svg
@@ -0,0 +1,59 @@
+
diff --git a/src/images/btree-borrow-merge.svg b/src/images/btree-borrow-merge.svg
new file mode 100644
index 0000000..1d25225
--- /dev/null
+++ b/src/images/btree-borrow-merge.svg
@@ -0,0 +1,72 @@
+
diff --git a/src/images/dijkstra-trace.svg b/src/images/dijkstra-trace.svg
new file mode 100644
index 0000000..20474cb
--- /dev/null
+++ b/src/images/dijkstra-trace.svg
@@ -0,0 +1,40 @@
+
diff --git a/src/images/floyd-cycle.svg b/src/images/floyd-cycle.svg
new file mode 100644
index 0000000..b1f59e2
--- /dev/null
+++ b/src/images/floyd-cycle.svg
@@ -0,0 +1,52 @@
+
diff --git a/src/images/heap-array-mapping.svg b/src/images/heap-array-mapping.svg
new file mode 100644
index 0000000..34586f0
--- /dev/null
+++ b/src/images/heap-array-mapping.svg
@@ -0,0 +1,59 @@
+
diff --git a/src/images/path-copying.svg b/src/images/path-copying.svg
index 7f70e1b..a8ce402 100644
--- a/src/images/path-copying.svg
+++ b/src/images/path-copying.svg
@@ -12,7 +12,7 @@
.note { fill: currentColor; font: 11px system-ui, sans-serif; opacity: .74; }
.lg { fill: currentColor; font: 11px system-ui, sans-serif; }
- Inserting 25 into a persistent BST. Version 1 stays valid
+ Inserting 35 into a persistent BST. Version 1 stays validv1 rootv2 root
@@ -34,7 +34,7 @@
30′7010
- 25
+ 35
@@ -49,5 +49,5 @@
Shared with v1: nothing about it changedCost per update: O(log n) copied nodes, not O(n).
- Node 30 must be copied. Its right pointer now points to 25.
+ Node 30 must be copied. Its right pointer now points to 35.
diff --git a/src/index.md b/src/index.md
index 5d108a6..5e48a34 100644
--- a/src/index.md
+++ b/src/index.md
@@ -2,7 +2,7 @@
**A complete course on data structures: from asymptotic analysis to the storage engines behind Spanner and Kafka.**
-Five volumes · 31 chapters · 4 appendices · ~55,000 words · Python, C, C++, Java, and Go
+Five volumes · 31 chapters · 4 appendices · ~155,000 words · 225 exercises with worked solutions · Python, C, C++, Java, and Go
By **Ngoc Anh Khoa Doan**, with the editorial help of Claude.
@@ -26,12 +26,14 @@ The full syllabus with chapter-by-chapter reading lists is in the [repository RE
## 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.
+**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.
---
diff --git a/src/volume-1/ch01-the-philosophy-and-mathematics-of-data-structures.md b/src/volume-1/ch01-the-philosophy-and-mathematics-of-data-structures.md
index ca56feb..2ddecc2 100644
--- a/src/volume-1/ch01-the-philosophy-and-mathematics-of-data-structures.md
+++ b/src/volume-1/ch01-the-philosophy-and-mathematics-of-data-structures.md
@@ -55,7 +55,7 @@ O(f(n)) describes an upper bound on running time. f(n) = O(g(n)) means that f gr
∃ c > 0, ∃ n₀ > 0, such that ∀ n ≥ n₀: 0 ≤ f(n) ≤ c·g(n)
-When we say a hash table has O(1) lookup, we mean the lookup time is bounded by a constant, regardless of how many elements are stored. This is an upper bound, we're saying lookup will never be worse than constant time.
+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
@@ -117,7 +117,7 @@ Logarithmic growth is remarkably slow. Even at n = 1 billion, log₂(n) ≈ 30.
**Linearithmic Time: O(n log n)**
- Comparison-based sorting (merge sort, heap sort, quicksort average case)
-- Building a heap
+- 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)**
@@ -142,9 +142,9 @@ Sometimes we care less about individual operation cost and more about total cost
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 ≤ 2n
+n + (1 + 2 + 4 + 8 + ... + n) ≤ n + 2n = 3n
-So the amortized cost per insert is O(2n/n) = O(1). Each individual insert is O(1) on average, even though occasional inserts are O(n).
+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:
@@ -154,7 +154,7 @@ Simply sum the costs of all operations and divide by n. If the total cost of any
**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 for future copying, and 1 unit for the eventual deallocation.
+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:
@@ -163,7 +163,7 @@ 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. When the array is full, Φ = 0. When half-full, Φ = n (maximum).
+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
@@ -193,10 +193,10 @@ A lower bound establishes that no algorithm can do better than a certain complex
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), the cell probe model proves that any data structure answering membership queries needs Ω(log n) time if it uses O(n) space. This is why balanced binary trees are optimal for static ordered sets.
+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 potential false positives and worst-case degradation.
+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
@@ -208,6 +208,162 @@ The mathematical foundations of data structures draw from several disciplines:
- **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
diff --git a/src/volume-1/ch02-primitive-types-and-memory-organization.md b/src/volume-1/ch02-primitive-types-and-memory-organization.md
index fa3b7a2..6f0f168 100644
--- a/src/volume-1/ch02-primitive-types-and-memory-organization.md
+++ b/src/volume-1/ch02-primitive-types-and-memory-organization.md
@@ -34,8 +34,8 @@ The "long" type illustrates how naming varies across languages:
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
-- Xbox 360 "red ring of death": Integer overflow in timer
-- Knights of the Round Table bug: Division by zero from 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
@@ -105,9 +105,9 @@ struct Example {
// 3 bytes padding
int b; // 4 bytes, offset 4
char c; // 1 byte, offset 8
- // 7 bytes padding (typically)
+ // 3 bytes padding (struct alignment is 4, from int)
};
-// sizeof(Example) = 16 (on 64-bit system)
+// 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.
@@ -284,6 +284,245 @@ class Stack:
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 `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.
+
+```c
+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.
+
+```c
+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 + 1` points at `arr[1]` (20).
+- `q = p + 3` points at `arr[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:
+
+```python
+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)**
+
+```python
+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.
+
+
+
---
## Where this connects
diff --git a/src/volume-1/ch03-arrays-the-foundation-of-contiguous-storage.md b/src/volume-1/ch03-arrays-the-foundation-of-contiguous-storage.md
index 9347888..3194505 100644
--- a/src/volume-1/ch03-arrays-the-foundation-of-contiguous-storage.md
+++ b/src/volume-1/ch03-arrays-the-foundation-of-contiguous-storage.md
@@ -91,18 +91,18 @@ After inserting 5 (capacity exceeded):
### Amortized Analysis of Dynamic Arrays
-With capacity doubling:
-- Insert 1: Copy 1 element
-- Insert 2: Copy 2 elements
-- Insert 4: Copy 4 elements
-- Insert 8: Copy 8 elements
+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: Copy 2^k elements
+- Insert 2^k + 1: Copy 2^k elements
Total copies for n insertions:
-1 + 2 + 4 + ... + 2^k where 2^k ≥ n
-≤ 2 × 2^k (geometric series)
-≤ 2n (since 2^k ≤ 2n)
+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)
@@ -182,15 +182,14 @@ if (bits[i / 8] & (1 << (i % 8))) { ... }
A circular buffer wraps around at the end, ideal for queues:
```
- front rear
- │ │
- ▼ ▼
+ rear front
+ │ │
+ ▼ ▼
┌────┬────┬────┬────┬────┬────┬────┬────┐
│ 30 │ 40 │ 50 │ -- │ -- │ -- │ 10 │ 20 │
└────┴────┴────┴────┴────┴────┴────┴────┘
- ▲ ▲
- empty full
- slots slots
+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:
@@ -206,8 +205,8 @@ Original: [10, 20, 25, 30, 35]
Difference: [10, 10, 5, 5, 5]
Range update [1,3) += 3:
-Original becomes: [10, 23, 28, 33, 35]
-Difference becomes: [10, 13, 5, 5, 5]
+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).
@@ -225,7 +224,250 @@ vector sparse;
Only non-default values stored, with index for position.
-## 3.7 Performance Characteristics
+## 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.
+
+```python
+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`, not `mid - 1`: a[mid] ≥ x, so it belongs to the "≥ x" region that starts at hi. Setting `hi = mid - 1` would claim a[mid − 1] ≥ x, which nobody checked.
+- `lo < hi`, not `lo <= hi`: when lo = hi the interval is empty. With `<=` the loop would read `a[mid]` with lo = hi = n, one past the end.
+- `(lo + hi) // 2` rounds 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.
+
+```python
+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.
+
+```python
+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:
+
+```python
+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:
+
+```python
+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.
+
+```python
+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.
+
+```python
+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](../volume-4/ch23-advanced-competitive-programming-data-structures.md)) 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.
+
+```python
+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 |
|-----------|-------------|---------------|-----------|
@@ -237,7 +479,15 @@ Only non-default values stored, with index for position.
| Memory | Fixed | 1× to 2× | 1/bit_size |
| Cache Efficiency | Excellent | Excellent | Good |
-## 3.8 Real-World Applications
+*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](../volume-3/ch16-external-memory-and-cache-oblivious-structures.md) 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](ch10-multiway-search-trees-and-b-trees.md)).
+
+## 3.9 Real-World Applications
**Database Systems**: Column stores use columnar arrays for analytical queries
**Scientific Computing**: Dense matrix operations (BLAS, LAPACK)
@@ -246,11 +496,383 @@ Only non-default values stored, with index for position.
**Compilers**: Symbol tables using open addressing
**Networking**: Packet buffers, ring buffers in device drivers
-## 3.9 Historical Context
+## 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. The Ruby language introduced the "push" and "pop" terminology that spread to Python and JavaScript.
+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).
+
+## 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
+
+```python
+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.
+
+```c
+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
+
+```c
+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:
+
+```c
+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.
+
+```python
+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.
+
+```python
+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`:
+
+```python
+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:
+
+```python
+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.
+
+```python
+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.
+
+
---
diff --git a/src/volume-1/ch04-linked-lists-the-art-of-distributed-storage.md b/src/volume-1/ch04-linked-lists-the-art-of-distributed-storage.md
index e9e0289..414572c 100644
--- a/src/volume-1/ch04-linked-lists-the-art-of-distributed-storage.md
+++ b/src/volume-1/ch04-linked-lists-the-art-of-distributed-storage.md
@@ -210,7 +210,172 @@ Common sentinel patterns:
- **Tail sentinel**: Dummy node after last real element
- **Both**: Simplifies all operations to "insert after/before"
-## 4.6 XOR Linked Lists
+## 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:
+
+```python
+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:
+
+```python
+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:
+
+```python
+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.
+
+1. 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 λ**.
+2. Slow is in the cycle, k − μ steps past its start.
+3. 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**.
+4. 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:
+
+```python
+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
+```
+
+
+{{#include ../images/floyd-cycle.svg}}
+The meeting point is k − μ steps into the cycle, so μ more steps complete a whole number of laps and land on the start, which is also μ steps from the head.
+
+
+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`:
+
+```python
+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:
+
+```python
+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 `<=` in `merge`) 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:
@@ -240,13 +405,13 @@ while (current != NULL) {
**Advantages**: 50% space reduction for pointers
**Disadvantages**: Can't traverse backwards without storing previous pointer, debugging is harder
-## 4.7 Unrolled Linked Lists
+## 4.8 Unrolled Linked Lists
Each node contains multiple elements in a small array:
```
┌────────┬───────┐ ┌────────┬───────┐
-│ 4 │ A │ B │ C │ ──┼─→│ 2 │ D │ E │ ──┼─→ NULL
+│ 3 │ A │ B │ C │ ──┼─→│ 2 │ D │ E │ ──┼─→ NULL
│ elements│ │ │ elements│ │
└────────┴───────┘ └────────┴───────┘
```
@@ -257,9 +422,9 @@ Each node contains multiple elements in a small array:
- Faster iteration
- Still O(1) insertion at arbitrary positions (with smaller shift)
-**Used in**: CD-ROM filesystems (directory entries), Kyoto Cabinet database, Lua's table implementation
+**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.8 Performance Characteristics
+## 4.9 Performance Characteristics
| Operation | Singly | Doubly | Circular | Unrolled |
|-----------|--------|--------|----------|----------|
@@ -274,7 +439,7 @@ Each node contains multiple elements in a small array:
*With tail pointer or other augmentation
-## 4.9 When to Use Linked Lists
+## 4.10 When to Use Linked Lists
**Use Linked Lists When:**
- Frequent insertions/deletions at arbitrary positions
@@ -289,7 +454,7 @@ Each node contains multiple elements in a small array:
- Memory overhead is a concern (pointers take space)
- Simple iteration is the primary operation (vectors are faster)
-## 4.10 Real-World Applications
+## 4.11 Real-World Applications
**Operating Systems**:
- Process scheduling queues
@@ -312,14 +477,492 @@ Each node contains multiple elements in a small array:
- Undo/redo functionality
- Text buffer implementation (lines as linked list)
-## 4.11 Historical Context
+## 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 introduced the concept of "linked list" and "car/cdr" (contents of address/register and contents of decrement/register) in LISP (1958), where lists are the fundamental data structure.
+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.
+
+```c
+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->next` is the node holding 7, so 5 goes between 7 and 3.
+- `delete_node(&head, 1)`: the key is in the head node, so the first `if` handles it by moving `*head_ref` to the second node. This is why the function takes `Node **`: it has to be able to change the caller's `head`.
+- `delete_node(&head, 3)`: the `while` loop walks with `prev` one step behind `temp` (7, then 5) until `temp` reaches 3, then `prev->next = temp->next` unlinks it. `prev` is the 5 node, whose `next` becomes NULL.
+- `delete_node(&head, 9)`: the loop runs off the end, `temp` is NULL, and the `if (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.
+
+```python
+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:
+
+```python
+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
+
+```python
+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
+
+```python
+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.
+
+```python
+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`:
+
+```python
+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
+
+```python
+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
diff --git a/src/volume-1/ch05-stacks-and-queues-ordered-access-patterns.md b/src/volume-1/ch05-stacks-and-queues-ordered-access-patterns.md
index adc0d52..32d8efc 100644
--- a/src/volume-1/ch05-stacks-and-queues-ordered-access-patterns.md
+++ b/src/volume-1/ch05-stacks-and-queues-ordered-access-patterns.md
@@ -141,9 +141,10 @@ Result: 1
**Infix to Postfix Conversion** (Shunting-yard algorithm):
- Numbers: output immediately
-- Operators: pop operators with higher precedence, then push
+- 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
@@ -297,15 +298,18 @@ int dequeue(CircularQueue *q) {
```
```
+MAX_SIZE = 6, starting from front = rear = 4.
Enqueue 4, 5, 6, then dequeue twice, then enqueue 7:
- front
- │
- ▼
+front
+ │
+ ▼
┌────┬────┬────┬────┬────┬────┐
│ 6 │ 7 │ -- │ -- │ 4 │ 5 │
└────┴────┴────┴────┴────┴────┘
- │
- rear
+ ▲
+ rear
+4 and 5 have been dequeued; their slots still hold the old
+values but are free and will be overwritten.
```
### Linked List Queue
@@ -385,7 +389,7 @@ typedef struct {
- Insert: O(log n)
- Extract min/max: O(log n)
- Peek: O(1)
-- Decrease/increase key: O(log n) or O(1) with index
+- 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
@@ -444,7 +448,7 @@ def consumer(queue):
process(item)
queue.task_done()
-queue = Queue()
+queue = Queue(maxsize=4) # bounded, so put() can block
threading.Thread(target=producer, args=(queue,)).start()
threading.Thread(target=consumer, args=(queue,)).start()
```
@@ -457,6 +461,306 @@ The term "stack" became standard in the 1960s, replacing earlier terms like "pus
Edsger Dijkstra's 1968 paper on " cooperating sequential processes" introduced semaphores and discussed bounded buffers (producer-consumer) as fundamental synchronization problems.
+## 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.
+
+```python
+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:
+
+```python
+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
+
+```python
+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 `rear` and, if the buffer is full, advances `front` to drop the oldest; undo steps `rear` back 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:
+
+```python
+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 ★★★ Sliding window maximum.** Given an array `a` of n numbers and a window size k, output the maximum of every window `a[i : i + k]`. The obvious approach is O(nk). Use a deque to do it in O(n) total.
+
+For example, `a = [1, 3, -1, -3, 5, 3, 6, 7]` and k = 3 gives `[3, 3, 5, 5, 6, 7]`.
+
+
+Hint
+
+Store indices in the deque. If a newer element is at least as large as an older one, the older one can never be the maximum of any future window, so it can be thrown away.
+
+
+
+
+Solution
+
+Keep a deque of indices whose values are strictly decreasing from front to back. The front is always the maximum of the current window.
+
+For each new index i:
+
+1. Pop from the back every index whose value is ≤ `a[i]`: those elements are older and no larger, so they can never be a window maximum again.
+2. Push i at the back.
+3. If the front index has slid out of the window (≤ i − k), pop it from the front.
+4. Once the first full window is reached (i ≥ k − 1), output `a[front]`.
+
+```python
+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 of the example (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 |
+
+**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. Each deque operation is O(1) at either end, which is what a deque (Section 5.6) is for. At most one front pop is needed per step, because the window advances by one index at a time. This is one of the standard uses of a deque that is neither a stack nor a queue: elements leave from both ends.
+
+
+
---
## Where this connects
diff --git a/src/volume-1/ch06-tree-fundamentals-and-binary-trees.md b/src/volume-1/ch06-tree-fundamentals-and-binary-trees.md
index fafec52..7addd3c 100644
--- a/src/volume-1/ch06-tree-fundamentals-and-binary-trees.md
+++ b/src/volume-1/ch06-tree-fundamentals-and-binary-trees.md
@@ -20,8 +20,8 @@ A tree T is a connected acyclic graph. Equivalently, a tree is a set of nodes wh
/| | \
/ | | \
E F G H
- / |
- I J
+ / |
+ I J
|
(I is descendant of E, B, A; ancestor of itself)
```
@@ -32,7 +32,7 @@ A tree T is a connected acyclic graph. Equivalently, a tree is a set of nodes wh
- **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, F)
+- **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
@@ -43,7 +43,7 @@ A tree T is a connected acyclic graph. Equivalently, a tree is a set of nodes wh
For a tree with n nodes:
- Exactly n-1 edges (each node except root has one edge to its parent)
-- A tree with maximum nodes for a given height is "complete"
+- 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:**
@@ -209,6 +209,70 @@ def level_order(root):
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.
+
+```python
+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:
+
+```python
+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:
+
+```python
+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:
@@ -235,7 +299,125 @@ def morris_inorder(root):
current = current.right
```
-## 6.7 Expression Trees
+## 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:
+
+1. Decide what the parent needs to know about a subtree. Sometimes that is more than the final answer.
+2. Return that tuple for the empty tree (the base case).
+3. 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).
+
+```python
+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):
+
+```python
+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:**
+
+```python
+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:
@@ -253,7 +435,7 @@ Inorder (infix): 3 + 4 * 2 - 1 (needs parentheses for correctness)
Postorder (postfix): 3 4 + 2 1 - *
```
-## 6.8 Binary Space Partitioning Trees
+## 6.11 Binary Space Partitioning Trees
BSP trees recursively divide space with hyperplanes:
@@ -271,9 +453,9 @@ Used in:
- Collision detection
- CAD systems
-## 6.9 Historical Context
+## 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, establishing what we now call "Cayley's formula": there are n^(n-1) labeled trees on n nodes.
+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)
@@ -281,6 +463,314 @@ The binary tree became central to computer science through:
- 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. Inorder `4 7` lies left of 2, so 2 has only a left subtree, with postorder `7 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. Inorder `5` is left of 3 and `8 6` is right. So 5 is 3's left child; the right subtree has postorder `8 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:
+
+```python
+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:
+
+```python
+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:
+
+```python
+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
+
+```python
+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:
+
+```python
+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
+
+```python
+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
diff --git a/src/volume-1/ch07-binary-search-trees.md b/src/volume-1/ch07-binary-search-trees.md
index f666f5d..f3e6440 100644
--- a/src/volume-1/ch07-binary-search-trees.md
+++ b/src/volume-1/ch07-binary-search-trees.md
@@ -78,6 +78,32 @@ def bst_delete(node, 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
```python
@@ -105,7 +131,7 @@ def max_value(node):
| Successor/Predecessor | O(log n) | O(n) |
| Traversal | O(n) | O(n) |
-**Average case** assumes randomly inserted keys, yielding approximately balanced trees with height ~log 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:
```
@@ -124,7 +150,292 @@ Inserting: 1, 2, 3, 4, 5
Height = n, operations = O(n)
```
-## 7.4 Self-Balancing BSTs
+### 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:
+
+1. **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.
+2. **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.
+
+
+{{#include ../images/bst-successor.svg}}
+The two successor cases on the example tree: a short walk down when a right subtree exists, otherwise a walk up that stops at the first ancestor reached from its left side.
+
+
+**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):
+
+```python
+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:
+
+```python
+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:
+
+```python
+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:
+
+```python
+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:
+
+```python
+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:
+
+```python
+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:
+
+```python
+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)
+```
+
+```python
+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.
+
+```python
+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:
+
+```python
+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.
@@ -139,7 +450,7 @@ Different balancing criteria define different tree families:
| Splay | No explicit criterion, amortized O(log n) |
| Weight-balanced | Size of subtrees within factor |
-## 7.5 Threaded Binary Trees
+## 7.9 Threaded Binary Trees
Threaded trees store threads (pointers) to inorder predecessor/successor instead of null pointers:
@@ -168,7 +479,7 @@ Threads shown as dashed:
Advantage: O(1) space for traversal (no stack)
Disadvantage: More complex insert/delete
-## 7.6 BST Variants
+## 7.10 BST Variants
### Treaps (BST + Heap)
@@ -176,14 +487,14 @@ Combine BST property with random heap priorities:
```
Treap example (priorities in parentheses):
- (50)8
+ (10)8
/ \
- (30)3 (70)10
+ (30)3 (20)10
/ \ \
- (20)1 (40)6 (80)14
+ (50)1 (40)6 (70)14
```
-The BST property holds on keys; heap property holds on priorities. Random priorities ensure expected O(log n) height.
+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
@@ -196,15 +507,15 @@ Simplified red-black tree that only allows right children to be red:
- Simpler delete (no complex cases)
- O(log n) guaranteed
-## 7.7 Applications of BSTs
+## 7.11 Applications of BSTs
- **Ordered maps**: Python dict (but actually hash-based), C++ map, Java TreeMap
-- **Ordered sets**: Python set, C++ set, Java TreeSet
+- **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.8 Choosing BST vs Alternatives
+## 7.12 Choosing BST vs Alternatives
**Use BST When:**
- Need ordered iteration
@@ -217,6 +528,248 @@ Simplified red-black tree that only allows right children to be red:
- 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 where `bst_insert` would 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
+
+1. **Delete 20.** It is a leaf (case 1): 30's left pointer becomes `None`.
+2. **Delete 30.** It now has only a right child, 40 (case 2). `bst_delete` returns `node.right`, so the subtree rooted at 40 (with 35 and 45) moves up to become 50's left child.
+3. **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.
+
+```python
+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
+
+```python
+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 `best` is 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)
+
+```python
+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
diff --git a/src/volume-1/ch08-self-balancing-trees.md b/src/volume-1/ch08-self-balancing-trees.md
index ed84fd0..b20b6ed 100644
--- a/src/volume-1/ch08-self-balancing-trees.md
+++ b/src/volume-1/ch08-self-balancing-trees.md
@@ -65,9 +65,8 @@ AVL Tree (balanced): Not AVL (unbalanced):
2 5 2
/ \ \
1 3 3
- /
- 1
-Height: -1 -2
+
+Balance factor of root: +1 +2
```
### Rotations
@@ -83,7 +82,7 @@ Before: After:
/ \ / \ / \
x T3 T1 T2 T3 T4
-Node z has balance factor -2 (left-heavy)
+Node z has balance factor +2 (left-heavy)
```
```c
@@ -199,15 +198,15 @@ Valid Red-Black Tree:
B(5) B(20) B(35) B(50)
Path black counts (from any node):
-30→5: B,R,B = 3 black nodes
-30→20: B,R,B = 3 black nodes
-30→35: B,R,B = 3 black nodes
-30→50: B,R,B = 3 black nodes
+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. Since shortest path has at least log₂(n+1) black nodes, the tree height is at most 2 × log₂(n+1) = O(log n).
+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
@@ -236,11 +235,9 @@ void insert_rb(Node **root, int key) {
}
void fix_violation(Node **root, Node *z) {
- Node *parent = NULL, *grandparent = NULL;
-
- while (z != *root && is_red(z) && parent != NULL) {
- parent = z->parent;
- grandparent = parent->parent;
+ 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) {
@@ -253,8 +250,9 @@ void fix_violation(Node **root, Node *z) {
z = grandparent;
} else {
if (z == parent->right) { // Case 2
+ rotate_left(root, parent);
z = parent;
- rotate_left(root, z);
+ parent = z->parent;
}
// Case 3
parent->color = BLACK;
@@ -277,7 +275,7 @@ void fix_violation(Node **root, Node *z) {
| Tree height | ≤ 1.44 log₂(n) | ≤ 2 log₂(n) |
| Search performance | Better | Slightly worse |
| Insert performance | More rotations | Fewer rotations |
-| Delete performance | More rotations | More 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 |
@@ -321,7 +319,7 @@ Key property: Recently accessed elements are near the root (temporal locality).
### Splay Tree Properties
- O(log n) amortized for insert, delete, search
-- O(log n) worst-case per operation
+- 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)
@@ -336,7 +334,7 @@ Scapegoat trees maintain balance by rebuilding subtrees when they become too unb
A tree is α-weight-balanced if for every node:
size(child) ≤ α × size(node)
-Typical α = 0.5 to 1 (0.5 = AVL-like strictness)
+Typical α is strictly between 0.5 and 1 (α = 0.5 demands near-perfect balance; α close to 1 allows almost any shape)
### Insertion
@@ -413,11 +411,268 @@ def treap_insert(root, node):
| Tree Type | Real-World Uses |
|-----------|----------------|
-| Red-Black | Linux kernel (completely fair scheduler), Java's TreeMap/TreeSet, C++ STL (typically), Lua tables |
+| 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 |
+## 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, then `rotate_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.4, 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.
+
+
+
---
## Where this connects
diff --git a/src/volume-1/ch09-heaps-and-priority-queues.md b/src/volume-1/ch09-heaps-and-priority-queues.md
index 3d9443f..1ef13c3 100644
--- a/src/volume-1/ch09-heaps-and-priority-queues.md
+++ b/src/volume-1/ch09-heaps-and-priority-queues.md
@@ -43,6 +43,11 @@ RightChild(i) = 2 * i + 2
The complete tree property guarantees no "holes" in the array.
+
+{{#include ../images/heap-array-mapping.svg}}
+Index i's children sit at 2i + 1 and 2i + 2, so level L occupies indices 2^L − 1 through 2^(L+1) − 2 and no pointers are needed.
+
+
## 9.3 Heap Operations
### Maintaining the Heap Property: Heapify
@@ -68,13 +73,13 @@ void heapify(int arr[], int n, int i) {
```
```
-Heapify at index 1 (value 80):
+Heapify at index 1 (value 30):
Before: After:
90 90
/ \ / \
- [80] 70 → 50 70
+ [30] 70 → 50 70
/ \ / \
- 50 40 80 40
+ 50 40 30 40
```
### Building a Heap
@@ -139,6 +144,19 @@ void heap_sort(int arr[], int n) {
}
```
+**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)
@@ -147,10 +165,12 @@ Properties:
## 9.5 Priority Queue Implementation
-Heaps implement priority queues efficiently:
+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.
```python
class PriorityQueue:
+ """Min-priority queue: pop returns the item with the smallest priority."""
+
def __init__(self):
self.heap = []
@@ -161,18 +181,317 @@ class PriorityQueue:
def pop(self):
if not self.heap:
return None
- max_item = self.heap[0][1]
+ top = self.heap[0][1]
last = self.heap.pop()
if self.heap:
self.heap[0] = last
self._sift_down(0)
- return max_item
+ 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`:
+
+```python
+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
```
-## 9.6 Binomial Heaps
+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:
+
+```python
+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](../volume-2/ch11-graphs-modeling-relationships.md) 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++'s `std::priority_queue` and Java's `PriorityQueue` have no decrease-key (Java's `remove(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):
+
+```python
+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](../volume-3/ch16-external-memory-and-cache-oblivious-structures.md) covers why misses dominate). LaMarca and Ladner measured this effect in 1996. Production libraries agree: .NET's `PriorityQueue` 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:
+
+```python
+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](../volume-3/ch16-external-memory-and-cache-oblivious-structures.md)), 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:
+
+1. **Order:** every value in `low` is ≤ every value in `high`, that is, max(low) ≤ min(high).
+2. **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).
+
+```python
+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](../volume-3/ch14-probabilistic-data-structures.md)).
+
+### 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 `-x` and read `-h[0]`. This works for numbers; for (priority, item) tuples, negate only the priority. Python 3.14 added `heappush_max`, `heappop_max`, `heapify_max` and related functions; on earlier versions, negate.
+- **`heapq.nlargest(k, iterable, key=None)`** and **`nsmallest`** are the top-k pattern above, O(n log k). For k = 1, `max` and `min` are 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:
+
+```python
+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.
@@ -191,14 +510,18 @@ B_1: ○ (2 nodes)
○
B_2: ○ (4 nodes)
- /│\
- ○ ○ ○
+ /│
+ ○ ○
+ │
+ ○
B_3: ○ (8 nodes)
/│\
○ ○ ○
- /│││\
- ○○○○○○○
+ /│ │
+ ○ ○ ○
+ │
+ ○
```
### Binomial Heap Structure
@@ -214,19 +537,22 @@ Binomial Heap (7 nodes):
- B_1 tree (2 nodes)
- B_0 tree (1 node)
-Root list:
-○4 → ○2 → ○1 → NULL
- │ │
- └─○───┘ └─○─→ NULL
+Root list, by increasing order:
+B_0 B_1 B_2
+ ○ → ○ → ○ → NULL
+ │ /│
+ ○ ○ ○
+ │
+ ○
```
Operations:
-- Insert: O(1) (create new B_0, merge)
+- 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.7 Fibonacci Heaps
+## 9.10 Fibonacci Heaps
Fibonacci heaps achieve O(1) amortized insert and decrease-key, making them ideal for algorithms like Dijkstra's.
@@ -259,17 +585,17 @@ Potential function: Φ = number of trees + 2 × marked nodes
| Insert | O(1) | O(1) |
| Union | O(1) | O(1) |
| Find-min | O(1) | O(1) |
-| Extract-min | O(log n) | O(log n) |
+| Extract-min | O(n) | O(log n) |
| Decrease-key | O(1)* | O(1) |
-| Delete | O(log n) | O(log n) |
+| Delete | O(n) | O(log n) |
-*The degree bound ensures actual cost is bounded
+*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"?
-The degree of any node is bounded by about φ × n (golden ratio), leading to the name. Each node can have at most O(log n) children.
+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.8 Pairing Heaps
+## 9.11 Pairing Heaps
Pairing heaps are simpler than Fibonacci heaps with similar (often better) practical performance.
@@ -282,53 +608,59 @@ Pairing heaps are simpler than Fibonacci heaps with similar (often better) pract
### Operations
```python
-def link(pq1, pq2):
- # Link two heaps, return larger root
- if pq1.value < pq2.value:
- pq2.left = pq1.left
- pq1.left = pq2
- return pq1
- else:
- pq1.left = pq2.left
- pq2.left = pq1
- return pq2
-
-def extract_min(pq):
- # Remove root, merge children two-by-two
- children = pq.children # linked list
+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 = []
- while children:
- pair = children
- children = children.next
- if children:
- pair.next = children.next
- children = children.next
- pairs.append(link(pair[0], pair[1]))
+ 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 pairs:
- result = link(result, p) if result else p
+ for p in reversed(pairs):
+ result = link(p, result)
return result
```
### Empirical Performance
-Despite lack of theoretical guarantees, pairing heaps:
+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.9 Applications of Heaps
+## 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**: Memory allocation, CPU scheduling
+**Operating systems**: Timer queues, CPU scheduling
**Statistics**: Kth largest/smallest elements
**Stream processing**: Sliding window median
-## 9.10 Historical Context
+## 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.
@@ -336,9 +668,312 @@ Fibonacci heaps were introduced by Fredman and Tarjan in 1987, revolutionizing g
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:
+
+```python
+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. But `sift_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:
+
+```python
+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
+
+```python
+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:
+
+```python
+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:
+
+```python
+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](../volume-2/ch11-graphs-modeling-relationships.md). Dijkstra and Prim with lazy deletion, the main consumers of decrease-key
- [Chapter 19: Emerging and Specialized Structures](../volume-3/ch19-emerging-and-specialized-structures.md). Why Fibonacci heaps win on paper and lose in practice
- [Chapter 21: Algorithm Design Using Data Structures](../volume-3/ch21-algorithm-design-using-data-structures.md). The greedy algorithms that are built on this structure
diff --git a/src/volume-1/ch10-multiway-search-trees-and-b-trees.md b/src/volume-1/ch10-multiway-search-trees-and-b-trees.md
index 460f1c8..05bcfd8 100644
--- a/src/volume-1/ch10-multiway-search-trees-and-b-trees.md
+++ b/src/volume-1/ch10-multiway-search-trees-and-b-trees.md
@@ -37,6 +37,18 @@ B-tree of order 5 (max 4 keys, 5 children):
[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
@@ -75,7 +87,8 @@ def btree_insert(root, key):
new_root = split_root(root)
root = new_root
- return _insert(root, key)
+ _insert(root, key)
+ return root
def _insert(node, key):
i = 0
@@ -97,7 +110,7 @@ def _insert(node, key):
When a node is full, split it:
```
-Full node with 4 keys (max):
+Overflowing node with 5 keys (order 5 allows at most 4):
┌─────────────────┐
│10│20│30│40│50│ ← Split into:
└─────────────────┘
@@ -111,7 +124,304 @@ Full node with 4 keys (max):
└───────┘
```
-## 10.4 B+ Trees
+## 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]`.
+
+
+{{#include ../images/btree-borrow-merge.svg}}
+The first two deletions. A borrow moves one key through the parent and leaves the parent's key count alone; a merge pulls the separator down, so the parent loses a key.
+
+
+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.
+
+```python
+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_KEYS` and `MAX_KEYS` keys, 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.
+
+```python
+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.
@@ -130,9 +440,9 @@ B+ Tree (internal nodes):
[0-20) [20-40) [40-60) [60+)
Leaves (linked for range queries):
-┌──────┬──────┬──────┐ ┌──────┬──────┐
-│10│15│25│30│35│ → │40│50│ → NULL
-└──────┴──────┴──────┘ └──────┴──────┘
+┌──┬──┐ ┌──┬──┬──┐ ┌──┬──┐ ┌──┬──┐
+│10│15│ → │25│30│35│ → │40│50│ → │60│70│ → NULL
+└──┴──┘ └──┴──┴──┘ └──┴──┘ └──┴──┘
```
Advantages:
@@ -140,14 +450,117 @@ Advantages:
- Leaves linked for efficient range scans
- All data at same depth (predictable I/O)
-## 10.5 B* Trees
+### 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):
+
+```python
+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:
+
+1. Sort the keys (with an external merge sort if they do not fit in memory).
+2. Fill leaves left to right, each as full as desired, and link each to the next.
+3. 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.
+
+```python
+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.6 2-3 Trees and 2-3-4 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
@@ -163,7 +576,7 @@ B* trees modify B-trees to keep nodes at least 2/3 full:
These are conceptual foundations for understanding B-trees and for implementing in-memory balanced trees.
-## 10.7 Real-World Applications
+## 10.9 Real-World Applications
**Database Systems**:
- MySQL (InnoDB): B+ trees
@@ -180,9 +593,9 @@ These are conceptual foundations for understanding B-trees and for implementing
**Key-Value Stores**:
- LevelDB: Skip list + SSTable with B-tree-like index
- RocksDB: LSM trees (log-structured merge)
-- Cassandra: B+ trees (local), distributed indexes
+- Cassandra: LSM trees (memtable + SSTables), partitioned across nodes
-## 10.8 Performance Characteristics
+## 10.10 Performance Characteristics
| Aspect | Binary Tree | B-Tree (m=100) | B+ Tree |
|--------|-------------|----------------|---------|
@@ -192,7 +605,7 @@ These are conceptual foundations for understanding B-trees and for implementing
| Range scan | Inefficient | Efficient | Most efficient |
| Fan-out | 2 | ~50-200 | ~50-200 |
-## 10.9 Variations and Extensions
+## 10.11 Variations and Extensions
**B+-tree variants**:
- B*-tree: Higher utilization
@@ -204,11 +617,12 @@ These are conceptual foundations for understanding B-trees and for implementing
- Used in Cassandra, RocksDB, LevelDB
- Components: memtable (in-memory), SSTables (disk)
-**RD-tree** (Recursive Decomposition):
+**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.10 Historical Context
+## 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).
@@ -216,6 +630,267 @@ 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_insert` splits 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, so `split_child` moves 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:
+
+```python
+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
+
+```python
+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
diff --git a/src/volume-1/index.md b/src/volume-1/index.md
index b3cdabd..4b964fb 100644
--- a/src/volume-1/index.md
+++ b/src/volume-1/index.md
@@ -1,20 +1,38 @@
# 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 1: The Philosophy and Mathematics of Data Structures](ch01-the-philosophy-and-mathematics-of-data-structures.md)
-- [Chapter 2: Primitive Types and Memory Organization](ch02-primitive-types-and-memory-organization.md)
+| Chapter | After it you can |
+|---------|------------------|
+| [1: The Philosophy and Mathematics of Data Structures](ch01-the-philosophy-and-mathematics-of-data-structures.md) | 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](ch02-primitive-types-and-memory-organization.md) | Explain what a pointer is, why integers overflow, how structs are padded, and why memory layout affects speed |
## Part 2: Fundamental Linear Structures
-- [Chapter 3: Arrays—The Foundation of Contiguous Storage](ch03-arrays-the-foundation-of-contiguous-storage.md)
-- [Chapter 4: Linked Lists—The Art of Distributed Storage](ch04-linked-lists-the-art-of-distributed-storage.md)
-- [Chapter 5: Stacks and Queues—Ordered Access Patterns](ch05-stacks-and-queues-ordered-access-patterns.md)
+| Chapter | After it you can |
+|---------|------------------|
+| [3: Arrays: The Foundation of Contiguous Storage](ch03-arrays-the-foundation-of-contiguous-storage.md) | Implement a growable array, address multi-dimensional data, use binary search, two pointers, sliding windows and prefix sums |
+| [4: Linked Lists: The Art of Distributed Storage](ch04-linked-lists-the-art-of-distributed-storage.md) | 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](ch05-stacks-and-queues-ordered-access-patterns.md) | Build both on arrays or lists, evaluate expressions with a stack, and use circular buffers and deques |
+
+## Part 3: Hierarchical Structures and Trees
+
+| Chapter | After it you can |
+|---------|------------------|
+| [6: Tree Fundamentals and Binary Trees](ch06-tree-fundamentals-and-binary-trees.md) | Use tree vocabulary precisely, traverse a tree four ways (recursively and with an explicit stack), and write recursive tree functions |
+| [7: Binary Search Trees](ch07-binary-search-trees.md) | 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](ch08-self-balancing-trees.md) | Perform rotations, state the AVL and red-black invariants, and choose between AVL, red-black, splay trees and treaps |
+| [9: Heaps and Priority Queues](ch09-heaps-and-priority-queues.md) | 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](ch10-multiway-search-trees-and-b-trees.md) | 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
-## Part 3: Hierarchical Structures, Trees
+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.
-- [Chapter 6: Tree Fundamentals and Binary Trees](ch06-tree-fundamentals-and-binary-trees.md)
-- [Chapter 7: Binary Search Trees](ch07-binary-search-trees.md)
-- [Chapter 8: Self-Balancing Trees](ch08-self-balancing-trees.md)
-- [Chapter 9: Heaps and Priority Queues](ch09-heaps-and-priority-queues.md)
-- [Chapter 10: Multiway Search Trees and B-Trees](ch10-multiway-search-trees-and-b-trees.md)
+Each chapter ends with exercises. Do at least the ★ ones before moving on: they are short and check the ideas the next chapter assumes.
diff --git a/src/volume-2/ch11-graphs-modeling-relationships.md b/src/volume-2/ch11-graphs-modeling-relationships.md
index 4f8648d..b2dc547 100644
--- a/src/volume-2/ch11-graphs-modeling-relationships.md
+++ b/src/volume-2/ch11-graphs-modeling-relationships.md
@@ -1,45 +1,77 @@
# 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 connecting pairs of vertices
+- 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
+ 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:
+
+1. **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.
+2. **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)
-- Directed: Edges have direction (A → B ≠ B → A)
+**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
-**Weighted vs. Unweighted:**
-- Weighted: Edges have weights (distances, costs)
-- Unweighted: All edges equal weight 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)
-**Simple vs. Multi:**
-- Simple: No loops, no parallel edges
-- Multi: Parallel edges allowed
+**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**.
-**Cyclic vs. Acyclic:**
-- Cyclic: Contains cycles
-- Acyclic: No cycles (DAGs if directed)
+**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:
+
+```python
+graph = {
+ 'A': ['B', 'C'],
+ 'B': ['A', 'D'],
+ 'C': ['A', 'D'],
+ 'D': ['B', 'C', 'E'],
+ 'E': ['D'],
+}
+```
+
### Adjacency Matrix
-A V×V matrix where matrix[i][j] indicates edge presence:
+A V×V matrix where `adj[i][j]` records whether (or with what weight) an edge i → j exists:
```c
// For weighted graph
@@ -49,22 +81,22 @@ int adj[V][V];
```
Undirected Graph:
- A B C D
- ┌──────────────
- A │ 0 1 1 0
- B │ 1 0 0 1
- C │ 1 0 0 1
- D │ 0 1 1 0
+ 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²)
```
-**Pros**: O(1) edge queries, simple
-**Cons**: O(V²) space even for sparse graphs
+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
-Store neighbors in linked lists or arrays:
+Each vertex stores the list of its neighbours:
```c
struct Node {
@@ -89,253 +121,780 @@ E → [D] → NULL
Space: O(V + E)
```
-**Pros**: O(V + E) space, good for sparse graphs
-**Cons**: Edge lookup is O(degree)
+**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 order of distance from source:
+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:
```python
from collections import deque
-def bfs(graph, start):
- visited = {start}
- queue = deque([start])
-
+def bfs(graph, source):
+ """Return (dist, parent) for every vertex reachable from source."""
+ dist = {source: 0}
+ parent = {source: None}
+ queue = deque([source])
while queue:
- vertex = queue.popleft()
- print(vertex)
-
- for neighbor in graph[vertex]:
- if neighbor not in visited:
- visited.add(neighbor)
- queue.append(neighbor)
+ 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 queue (FIFO)
-- Produces shortest path in unweighted graphs
-- Time: O(V + E)
+- 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 explores deeply before backtracking:
+DFS follows one path as deep as it can, then backtracks:
```python
-def dfs_recursive(graph, vertex, visited=None):
+def dfs_recursive(graph, u, visited=None, order=None):
if visited is None:
- visited = set()
+ 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
- visited.add(vertex)
- print(vertex)
-
- for neighbor in graph[vertex]:
- if neighbor not in visited:
- dfs_recursive(graph, neighbor, visited)
def dfs_iterative(graph, start):
- visited = set()
+ visited, order = set(), []
stack = [start]
-
while stack:
- vertex = stack.pop()
- if vertex not in visited:
- visited.add(vertex)
- print(vertex)
- stack.extend(graph[vertex])
+ 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 stack (LIFO) or recursion
-- Produces discovery/exploration order
-- Time: O(V + E)
-- Space: O(V)
+- 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.
-## 11.5 Topological Sort
+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.
-Topological sort orders vertices of a DAG so all edges go forward:
+## 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.
```python
-def topological_sort(graph):
- in_degree = {v: 0 for v in graph}
- for v in graph:
- for u in graph[v]:
- in_degree[u] += 1
+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.
- queue = [v for v in graph if in_degree[v] == 0]
- result = []
+(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.
+
+```python
+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:
+
+```python
+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:
- v = queue.pop(0)
- result.append(v)
- for u in graph[v]:
- in_degree[u] -= 1
- if in_degree[u] == 0:
- queue.append(u)
-
- return result
+ 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
```
-Applications:
-- Build systems (make)
-- Course scheduling
-- Task dependencies
-- Assembly instructions
+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.
-## 11.6 Minimum Spanning Trees
+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.
-A spanning tree connects all vertices with minimum total edge weight.
+**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.
+
+```python
+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):
+
+```python
+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:
+
+1. Run DFS on G and record vertices in order of finishing time.
+2. Build the **transpose** Gᵀ (every edge reversed).
+3. Run DFS on Gᵀ, starting each new search from the unassigned vertex that finished *latest* in pass 1. Each search collects exactly one SCC.
+
+```python
+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.
+
+```python
+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 `find` path 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
-Greedy edge-by-edge:
+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.
```python
-def kruskal(graph):
- edges = sorted(graph.edges, key=lambda e: e.weight)
- uf = UnionFind(V)
+def kruskal(n, edges):
+ """n vertices numbered 0..n-1; edges is a list of (weight, u, v)."""
+ uf = UnionFind(n)
mst = []
-
- for edge in edges:
- u, v = edge.u, edge.v
- if uf.find(u) != uf.find(v):
- uf.union(u, v)
- mst.append(edge)
- if len(mst) == V - 1:
+ 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
```
-Time: O(E log E) or O(E log V)
+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 MST from a vertex:
+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:
```python
+import heapq
+
def prim(graph, start):
+ """graph[u] is a list of (v, weight) pairs, undirected."""
visited = {start}
- edges = []
+ 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
-
+ continue # stale entry: v was reached more cheaply
visited.add(v)
- edges.append((u, v, w))
+ mst.append((u, v, w))
+ for x, wx in graph[v]:
+ if x not in visited:
+ heapq.heappush(heap, (wx, v, x))
+ return mst
+```
- for w2, v2 in graph[v]:
- if v2 not in visited:
- heapq.heappush(heap, (w2, v, v2))
+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.
- return edges
-```
+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.
-Time: O(E log V) with binary heap
+## 11.10 Shortest Paths
-## 11.7 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: Dijkstra's Algorithm
+### Single-Source, Non-Negative Weights: Dijkstra's Algorithm
-For non-negative weights:
+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.
```python
import heapq
def dijkstra(graph, source):
- dist = {v: float('inf') for v in graph}
+ """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
-
+ continue # stale entry (lazy deletion)
for v, w in graph[u]:
- if dist[u] + w < dist[v]:
- dist[v] = dist[u] + w
+ 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 |
+
+
+{{#include ../images/dijkstra-trace.svg}}
+The graph from the trace. Blue edges are the parent pointers Dijkstra leaves behind; together they form a tree of shortest paths from S.
+
+
+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:
+
+```python
+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
```
-Time: O((V + E) log V)
+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
-Dynamic programming for all pairs:
+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.
```python
-def floyd_warshall(graph):
- n = len(graph)
- dist = [[float('inf')] * n for _ in range(n)]
-
+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 in range(n):
- for v, w in graph[u]:
- dist[u][v] = w
+ for u, v, w in edges:
+ dist[u][v] = min(dist[u][v], w) # keep the cheapest parallel edge
- for k in range(n):
+ for k in range(n): # allow k as an intermediate vertex
for i in range(n):
for j in range(n):
- dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
+ 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.
+
+```python
+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
+
+```python
+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
```
-Time: O(V³), Space: O(V²)
+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).
-## 11.8 Union-Find (Disjoint Set Union)
+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.
```python
-class UnionFind:
- def __init__(self, n):
- self.parent = list(range(n))
- self.rank = [0] * n
+from collections import defaultdict, deque
- def find(self, x):
- if self.parent[x] != x:
- self.parent[x] = self.find(self.parent[x]) # Path compression
- return self.parent[x]
+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)
- def union(self, x, y):
- px, py = self.find(x), self.find(y)
- if px == py:
- return False
-
- if self.rank[px] < self.rank[py]:
- px, py = py, px
- self.parent[py] = px
- if self.rank[px] == self.rank[py]:
- self.rank[px] += 1
- return True
+ 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
```
-Time: O(α(n)) amortized (inverse Ackermann, effectively constant)
+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.
-## 11.9 Applications
+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.
-**Social Networks**: Friend suggestions, degrees of separation
-**GPS/Maps**: Shortest routes, point-to-point navigation
-**Internet**: Routing protocols (link-state, distance-vector)
-**Web**: PageRank, web crawling
-**Biology**: Protein interaction networks, evolutionary trees
-**Finance**: Transaction graphs, fraud detection
-**Recommendation Systems**: Collaborative filtering
+
---
## Where this connects
+- [Chapter 5: Stacks and Queues](../volume-1/ch05-stacks-and-queues-ordered-access-patterns.md). The two containers that turn into DFS and BFS
+- [Chapter 9: Heaps and Priority Queues](../volume-1/ch09-heaps-and-priority-queues.md). The structure inside Dijkstra and Prim, and why decrease-key matters
- [Chapter 21: Algorithm Design Using Data Structures](../volume-3/ch21-algorithm-design-using-data-structures.md). The greedy and DP paradigms behind these algorithms
+- [Chapter 23: Advanced Competitive Programming Data Structures](../volume-4/ch23-advanced-competitive-programming-data-structures.md). 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](../volume-5/ch28-network-topology-and-routing-data-structures.md). The same graph structures applied to network routing
diff --git a/src/volume-2/ch12-hash-tables.md b/src/volume-2/ch12-hash-tables.md
index c7536f0..4d53163 100644
--- a/src/volume-2/ch12-hash-tables.md
+++ b/src/volume-2/ch12-hash-tables.md
@@ -281,6 +281,272 @@ The first published description is Arnold Dumey's in 1956, though Hans Peter Luh
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.
+## 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:
+
+```python
+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.
+
+```python
+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:
+
+```python
+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.6 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
+
+```python
+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.
+
+
+
---
## Where this connects
diff --git a/src/volume-2/ch13-string-data-structures.md b/src/volume-2/ch13-string-data-structures.md
index e04de12..b555d5f 100644
--- a/src/volume-2/ch13-string-data-structures.md
+++ b/src/volume-2/ch13-string-data-structures.md
@@ -135,7 +135,7 @@ root
│ └── "na"
│ ├── "$" → 3
│ └── "na$" → 1
- └── "banana$" → 0
+ ├── "banana$" → 0
└── "na"
├── "$" → 4
└── "na$" → 2
@@ -267,6 +267,311 @@ Udi Manber and Gene Myers introduced suffix arrays in 1990 explicitly as the spa
Alfred Aho and Margaret Corasick published their multi-pattern algorithm in 1975 while at Bell Labs, where it went straight into `fgrep`.
+## 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
+
+```python
+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.5, 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.
+
+```python
+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")`: the `r` node is no longer a word, so it is cut, taking `card` with it. Then `a` is cut (it is not a word), which also removes `cat`. Then `c` is cut. The trie now holds only `do`, `dog`, `done`.
+- `delete("do")`: the `o` node is cut along with `dog` and `done` below it, then `d`. The trie holds only `cat`, `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.
+
+```python
+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
+
+```python
+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.
+
+
+
---
## Where this connects
diff --git a/src/volume-2/index.md b/src/volume-2/index.md
index bdf6f71..dc25b06 100644
--- a/src/volume-2/index.md
+++ b/src/volume-2/index.md
@@ -1,7 +1,17 @@
# Volume II: Advanced Structures and Algorithms
-## Chapters
+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:
-- [Chapter 11: Graphs—Modeling Relationships](ch11-graphs-modeling-relationships.md)
-- [Chapter 12: Hash Tables](ch12-hash-tables.md)
-- [Chapter 13: String Data Structures](ch13-string-data-structures.md)
+- **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](ch11-graphs-modeling-relationships.md) | 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](ch12-hash-tables.md) | Explain chaining versus open addressing, reason about load factor and resizing, choose a hash function, and build an LRU cache from a hash table and a linked list |
+| [13: String Data Structures](ch13-string-data-structures.md) | Build tries and radix trees, explain suffix trees and suffix arrays, and search for many patterns at once with Aho-Corasick |
+
+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.
diff --git a/src/volume-3/ch14-probabilistic-data-structures.md b/src/volume-3/ch14-probabilistic-data-structures.md
index 15e8074..83b0c3e 100644
--- a/src/volume-3/ch14-probabilistic-data-structures.md
+++ b/src/volume-3/ch14-probabilistic-data-structures.md
@@ -256,6 +256,205 @@ Philippe Flajolet spent much of his career on this family. Probabilistic countin
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:
+
+```python
+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)
+
+```python
+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
diff --git a/src/volume-3/ch15-spatial-and-geometric-data-structures.md b/src/volume-3/ch15-spatial-and-geometric-data-structures.md
index df4f7ed..5e6d112 100644
--- a/src/volume-3/ch15-spatial-and-geometric-data-structures.md
+++ b/src/volume-3/ch15-spatial-and-geometric-data-structures.md
@@ -160,7 +160,7 @@ This gives R-trees B-tree virtues: balanced by construction, high fanout, tuned
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** by sorting along a space-filling curve (Sort-Tile-Recursive packing) produces far better trees than repeated insertion.
+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
@@ -213,6 +213,229 @@ Jon Bentley introduced KD-trees in 1975 while a graduate student at Stanford, as
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
+
+1. **(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).
+2. **(9,6)**, axis y. Distance 4.000, not better. diff = 2 − 6 = −4 < 0, so near = left (8,1), far = right (empty).
+3. **(8,1)**, axis x. Distance √(1 + 1) ≈ 1.414; best = (8,1). Both children are empty.
+4. Back at (9,6): is |−4| < 1.414? No. Its (empty) far side is skipped.
+5. 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:
+
+```python
+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.
+
+```python
+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
+
+1. **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.
+2. **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.
+3. **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
diff --git a/src/volume-3/ch16-external-memory-and-cache-oblivious-structures.md b/src/volume-3/ch16-external-memory-and-cache-oblivious-structures.md
index 0cec96e..642411a 100644
--- a/src/volume-3/ch16-external-memory-and-cache-oblivious-structures.md
+++ b/src/volume-3/ch16-external-memory-and-cache-oblivious-structures.md
@@ -76,9 +76,9 @@ The **van Emde Boas layout** is the foundational trick. Take a complete binary t
```
Tree: Layout in memory:
- 1 [1 | 2 3 | 4 5 | 6 7 ...]
- / \ ↑ ↑ ↑
- 2 3 top sub1 sub2 ← each recursively vEB-laid-out
+ 1 [1 | 2 4 5 | 3 6 7]
+ / \ ↑ ↑ ↑
+ 2 3 top sub1 sub2 ← each recursively vEB-laid-out
/| |\
4 5 6 7
```
@@ -131,6 +131,168 @@ Cache-oblivious algorithms arrived much later. Harald Prokop's 1999 MIT master's
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
+
+```python
+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
diff --git a/src/volume-3/ch17-persistent-data-structures.md b/src/volume-3/ch17-persistent-data-structures.md
index 55d212f..7b27148 100644
--- a/src/volume-3/ch17-persistent-data-structures.md
+++ b/src/volume-3/ch17-persistent-data-structures.md
@@ -32,23 +32,23 @@ Confluent persistence is genuinely harder than the other two. When versions can
Path copying: only the root-to-insertion path is duplicated.
-Share unchanged nodes on modification. Inserting 25 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:
+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 25:
+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(25) │
+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(25). Shared: D(10), C(70).
+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.
@@ -65,7 +65,7 @@ def insert(node, key):
return node # already present
v1 = build_tree([50, 30, 70, 10])
-v2 = insert(v1, 25) # v1 still queryable, unchanged
+v2 = insert(v1, 35) # v1 still queryable, unchanged
v3 = insert(v2, 60) # three coexisting versions
```
@@ -145,6 +145,221 @@ Chris Okasaki's *Purely Functional Data Structures* (1998), which grew out of hi
Phil Bagwell introduced the Hash Array Mapped Trie in 2001. Rich Hickey built Clojure's collections on it in 2007, which more than anything else moved persistent structures from a functional-programming specialty into general practice.
+## 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).
+
+1. PostgreSQL MVCC, as described in 17.4: a transaction reads the snapshot that existed when it started, and writers only ever modify the current state.
+2. 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.
+3. Git, including merge commits.
+4. 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:
+
+```python
+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']`.
+
+1. Which logical slots are occupied, and which child is in each?
+2. Look up slot 5 and slot 6.
+3. Write `physical_index(bitmap, slot)`, `lookup(bitmap, children, slot)`, and `with_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
+
+1. Bits 1, 4, 5, and 7 are set, so slot 1 → `'a'`, slot 4 → `'b'`, slot 5 → `'c'`, slot 7 → `'d'`.
+2. Slot 5: bit 5 is set. The bits below it are `0b10010` (bits 1 and 4), popcount 2, so the answer is `children[2] == 'c'`. Slot 6: bit 6 is clear, so the slot is empty and the lookup fails without touching the array.
+3. The three functions:
+
+```python
+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.
+
+```python
+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 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 `front` holds the rest. The next n−1 dequeues pop from that `front` with no reversal. Total: **n steps**, O(1) amortized, exactly as in the ephemeral analysis.
+- **(b) Replay:** every call receives the same `q` with an empty `front`, 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. This is the "lazy evaluation and memoization" from 17.5.
+
+
+
---
## Where this connects
diff --git a/src/volume-3/ch18-concurrent-data-structures.md b/src/volume-3/ch18-concurrent-data-structures.md
index 7203f41..49dfcda 100644
--- a/src/volume-3/ch18-concurrent-data-structures.md
+++ b/src/volume-3/ch18-concurrent-data-structures.md
@@ -158,6 +158,226 @@ Herlihy's 1991 paper "Wait-Free Synchronization" is the theoretical foundation:
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.
+
+1. A counter protected by a mutex.
+2. `lock_free_push` from 18.2.
+3. A spinlock built from CAS: `int zero = 0; while (!atomic_compare_exchange_weak(&lock, &zero, 1)) { zero = 0; }`, followed by a critical section and `atomic_store(&lock, 0)`.
+4. An RCU reader that loads the current pointer and reads through it.
+
+
+Solution
+
+1. **Blocking.** If the holder is descheduled inside the critical section, every other thread waits.
+2. **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.
+3. **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.
+4. **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):
+
+```c
+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.
+
+1. Which buckets share a lock with bucket 37?
+2. 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?
+3. With 8 threads writing simultaneously, what is the probability that at least two of them contend under 16-way striping?
+4. Why must a resize from 256 to 512 buckets acquire all 16 locks?
+
+
+Solution
+
+1. 37 mod 16 = 5, so lock 5 guards buckets 5, 21, 37, 53, ..., 245: the 16 buckets congruent to 5 mod 16.
+2. Global lock: 1 (they always contend). Striping: 1/16 ≈ 6%. Per-bucket: 1/256 ≈ 0.4%.
+3. 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.
+4. 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.
+- **`ConcurrentHashMap`** works 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
+
+```python
+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.
+
+```python
+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
diff --git a/src/volume-3/ch19-emerging-and-specialized-structures.md b/src/volume-3/ch19-emerging-and-specialized-structures.md
index fb6c08a..c8fde3d 100644
--- a/src/volume-3/ch19-emerging-and-specialized-structures.md
+++ b/src/volume-3/ch19-emerging-and-specialized-structures.md
@@ -45,12 +45,12 @@ 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 100μs seek, and the virtue becomes the defect, which is why disk-resident indexes are overwhelmingly B-trees rather than hash tables, as [Chapter 16](ch16-external-memory-and-cache-oblivious-structures.md) explains.
+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](ch16-external-memory-and-cache-oblivious-structures.md) 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: extendible 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 100μs than when it is 100ns. The cost is expensive insertions when eviction chains grow long.
+- **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.
@@ -129,6 +129,206 @@ A few honest heuristics for evaluating structures like these, since most novel s
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
+```
+
+1. Compute `rank(4)`, `rank(7)`, and `rank(10)`.
+2. Compute `select(1)`, `select(4)`, and `select(6)`.
+3. Check that `rank(select(k)) = k − 1` for those three values of k, and say why it holds in general.
+4. 19.2 compares 2n bits against 128n bits for a binary tree. Put numbers on that for a tree of 100 million nodes.
+
+
+Solution
+
+1. `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**.
+2. The 1s sit at positions 0, 2, 3, 6, 8, 9. So `select(1) = 0`, `select(4) = 6`, `select(6) = 9`.
+3. `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.
+4. 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.
+
+1. Compute the predicted position of every key and the maximum error ε.
+2. Describe a lookup for 23 and for 24 (absent) using the prediction plus a bounded local search.
+3. 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
+
+1. 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**.
+
+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.
+
+3. 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
+
+```python
+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.
+
+```python
+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
diff --git a/src/volume-3/ch20-data-structure-design-patterns.md b/src/volume-3/ch20-data-structure-design-patterns.md
index 7c98461..4d884e5 100644
--- a/src/volume-3/ch20-data-structure-design-patterns.md
+++ b/src/volume-3/ch20-data-structure-design-patterns.md
@@ -142,7 +142,7 @@ def in_order(node):
first_five = list(itertools.islice(in_order(root), 5))
```
-**Iterator invalidation** is the classic hazard: mutating a structure while iterating it. Growing 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.
+**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
@@ -172,7 +172,7 @@ class BSTBuilder:
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. 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 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:
@@ -230,6 +230,392 @@ Also: a deque adapted to a stack or a queue, and a `Set` adapted from a `Map` wi
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`?
+
+```python
+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:
+
+```python
+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:
+
+```python
+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:
+
+```python
+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
+```
+
+1. List the values `TreeIterator` yields, and the contents of its stack (bottom to top, as values) after each of the first three calls to `next()`.
+2. List the values `in_order` yields.
+3. `list(itertools.islice(in_order(root), 3))` returns three values. Which nodes have been pushed onto the generator's stack by then?
+
+
+Solution
+
+1. 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 |
+
+2. In-order: **1, 3, 4, 6, 7, 8, 10, 13, 14**, the sorted keys.
+
+3. 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:
+
+```python
+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:
+
+```python
+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:
+
+```python
+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).
+
+```python
+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
+
+```python
+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
diff --git a/src/volume-3/ch21-algorithm-design-using-data-structures.md b/src/volume-3/ch21-algorithm-design-using-data-structures.md
index acb6051..08a1140 100644
--- a/src/volume-3/ch21-algorithm-design-using-data-structures.md
+++ b/src/volume-3/ch21-algorithm-design-using-data-structures.md
@@ -21,7 +21,7 @@ Use data structures to divide problems:
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](../volume-1/ch05-stacks-and-queues-ordered-access-patterns.md) 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). The three sorts above are the three cases in miniature. 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).
+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.
@@ -174,6 +174,227 @@ The diagnostic question for each:
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.
+
+1. Karatsuba: T(n) = 3T(n/2) + O(n)
+2. Strassen: T(n) = 7T(n/2) + O(n²)
+3. Naive divide-and-conquer matrix multiplication: T(n) = 8T(n/2) + O(n²)
+4. 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):
+
+```python
+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
+
+```python
+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
+
+```python
+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
diff --git a/src/volume-3/ch22-practical-considerations.md b/src/volume-3/ch22-practical-considerations.md
index 71b3348..92b032d 100644
--- a/src/volume-3/ch22-practical-considerations.md
+++ b/src/volume-3/ch22-practical-considerations.md
@@ -190,6 +190,311 @@ def to_dot(node, out):
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.
+
+1. 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.
+2. A session store maps random session ids to user records. Nobody ever iterates it in order.
+3. A trading system must answer "all orders placed between 10:00:00 and 10:05:00" while orders keep arriving.
+4. A job scheduler repeatedly runs whichever pending job has the earliest deadline.
+5. A service checks 30 feature flags by name on each request.
+
+
+Solution
+
+1. **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.
+2. **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.
+3. **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.
+4. **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.
+5. **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
+
+```python
+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
+
+```python
+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
+
+```python
+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:
+
+```python
+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
+
+```python
+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:
+
+```python
+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
diff --git a/src/volume-3/index.md b/src/volume-3/index.md
index 881dcb8..6f071db 100644
--- a/src/volume-3/index.md
+++ b/src/volume-3/index.md
@@ -1,13 +1,22 @@
# Volume III: Specialized and Modern Structures
-## Chapters
-
-- [Chapter 14: Probabilistic Data Structures](ch14-probabilistic-data-structures.md)
-- [Chapter 15: Spatial and Geometric Data Structures](ch15-spatial-and-geometric-data-structures.md)
-- [Chapter 16: External Memory and Cache-Oblivious Structures](ch16-external-memory-and-cache-oblivious-structures.md)
-- [Chapter 17: Persistent Data Structures](ch17-persistent-data-structures.md)
-- [Chapter 18: Concurrent Data Structures](ch18-concurrent-data-structures.md)
-- [Chapter 19: Emerging and Specialized Structures](ch19-emerging-and-specialized-structures.md)
-- [Chapter 20: Data Structure Design Patterns](ch20-data-structure-design-patterns.md)
-- [Chapter 21: Algorithm Design Using Data Structures](ch21-algorithm-design-using-data-structures.md)
-- [Chapter 22: Practical Considerations](ch22-practical-considerations.md)
+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](ch14-probabilistic-data-structures.md) | 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](ch15-spatial-and-geometric-data-structures.md) | KD-trees, quadtrees, R-trees and geohashes answer "what is near this point?" |
+| Memory access is uniform | [16: External Memory and Cache-Oblivious Structures](ch16-external-memory-and-cache-oblivious-structures.md) | 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](ch17-persistent-data-structures.md) | Path copying and structural sharing keep every version alive cheaply, the basis of functional languages and MVCC |
+| One thread at a time | [18: Concurrent Data Structures](ch18-concurrent-data-structures.md) | 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](ch19-emerging-and-specialized-structures.md) | 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](ch20-data-structure-design-patterns.md) | Wrappers, iterators, adapters and builders: the recurring ways structures are composed and exposed |
+| [21: Algorithm Design Using Data Structures](ch21-algorithm-design-using-data-structures.md) | Divide and conquer, dynamic programming, greedy, backtracking and randomization, and the structure each paradigm leans on |
+| [22: Practical Considerations](ch22-practical-considerations.md) | 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.
diff --git a/src/volume-4/ch23-advanced-competitive-programming-data-structures.md b/src/volume-4/ch23-advanced-competitive-programming-data-structures.md
index fb0f71b..c0673c1 100644
--- a/src/volume-4/ch23-advanced-competitive-programming-data-structures.md
+++ b/src/volume-4/ch23-advanced-competitive-programming-data-structures.md
@@ -278,6 +278,12 @@ class LinkCutTree:
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
@@ -287,18 +293,19 @@ class LinkCutTree:
def _update(self, x):
x.sum = x.val
- if x.left: x.sum ^= x.left.sum
- if x.right: x.sum ^= x.right.sum
+ 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 p == p.parent.left:
- p.parent.left = x
- else:
- p.parent.right = x
- x.parent = g.parent
- if x == p.left:
+ 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
@@ -311,24 +318,22 @@ class LinkCutTree:
self._update(x)
def _splay(self, x):
- stack = []
+ stack = [x]
y = x
- stack.append(y)
- while y.parent:
- stack.append(y.parent)
+ while not self._is_root(y):
y = y.parent
+ stack.append(y)
while stack:
self._push(stack.pop())
- while x.parent:
- self._push(x.parent)
- if x == x.parent.left:
- if x.parent.parent and x.parent == x.parent.parent.left:
- self._rotate(x.parent)
- self._rotate(x)
- else:
- if x.parent.parent and x.parent == x.parent.parent.right:
- self._rotate(x.parent)
- self._rotate(x)
+ 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
@@ -353,8 +358,9 @@ class LinkCutTree:
self.make_root(x)
self.access(y)
self._splay(y)
- if y.left == x:
- y.left.parent = None
+ self._push(x)
+ if y.left is x and x.right is None:
+ x.parent = None
y.left = None
self._update(y)
@@ -425,7 +431,7 @@ class MoSolver:
**3D Mo's:** Add time dimension for updates.
-**Mo's with Rollback:** For parallel binary search.
+**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
@@ -593,21 +599,22 @@ class WaveletTree:
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
- in_left = self.b[r] - (self.b[l - 1] if l > 0 else 0)
- left_l = 1 if l == 0 else self.b[l - 1] + 1
- left_r = left_l + in_left - 1
+ 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_l, left_r, k)
+ return self.left.kth(left_before, left_before + in_left - 1, k)
else:
- right_l = r - (self.b[r] - self.b[r - 1] if r > 0 else 0) - in_left + 1
- right_r = r - in_left
- return self.right.kth(right_l, right_r, k - in_left)
+ 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
@@ -692,6 +699,7 @@ Sparse tables answer static range queries in O(1) after O(n log n) preprocessing
```python
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):
@@ -708,7 +716,7 @@ class SparseTable:
def query(self, l, r):
j = self.log[r - l + 1]
- return min(self.st[j][l], self.st[j][r - (1 << j) + 1])
+ return self.op(self.st[j][l], self.st[j][r - (1 << j) + 1])
```
## 23.12 Cartesian Trees
@@ -833,6 +841,243 @@ class DSU:
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:
+
+```python
+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
+
+```python
+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
diff --git a/src/volume-4/ch24-research-grade-data-structures.md b/src/volume-4/ch24-research-grade-data-structures.md
index 9d9a534..1106065 100644
--- a/src/volume-4/ch24-research-grade-data-structures.md
+++ b/src/volume-4/ch24-research-grade-data-structures.md
@@ -10,10 +10,11 @@ Research-grade data structures push the boundaries of what is theoretically poss
Succinct data structures store information in space close to the theoretical minimum while supporting efficient operations. They achieve entropy-compressed space.
-**Space Bounds:**
-- **Succinct:** n·H₀ + O(n / log n) bits
-- **Compact:** O(n log σ) bits
-- **Implicit:** n + O(1) bits
+**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
@@ -35,12 +36,11 @@ class SuccinctBitVector:
def rank(self, i):
"""Count of 1s in [0, i]"""
block = i // 64
- return self.rank_block[block] + bin(
- self.bits[block * 64: i + 1]
- ).count('1')
+ 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 k-th 1"""
+ """Position of the k-th 1 (k counts from 0)"""
lo, hi = 0, self.n - 1
while lo < hi:
mid = (lo + hi) // 2
@@ -60,19 +60,19 @@ Tree → balanced parentheses string where "(" means enter node, ")" means exit.
```python
def find_close(bp, i):
"""Find matching ')' for '(' at i"""
- delta = -1
- while delta < 0:
+ depth = 1
+ while depth > 0:
i += 1
- delta += 1 if bp[i] == '(' else -1
+ depth += 1 if bp[i] == '(' else -1
return i
def find_open(bp, i):
"""Find matching '(' for ')' at i"""
- delta = 1
- while delta > 0:
- i += 1
- delta += 1 if bp[i] == '(' else -1
- return i - 1
+ depth = 1
+ while depth > 0:
+ i -= 1
+ depth += 1 if bp[i] == ')' else -1
+ return i
```
### LOUDS (Level-Order Unary Degree Sequence)
@@ -82,15 +82,15 @@ Level-order traversal with unary degree encoding. Each node: (degree times '(')
| Operation | Complexity |
|-----------|------------|
| Root | O(1) |
-| Parent | O(log n) |
+| Parent | O(1) with O(1) rank/select |
| Children | O(d) |
-| Subtree size | O(1) |
+| Subtree size | Not supported efficiently (use BP or DFUDS) |
## 24.4 Wavelet Matrices
### Conceptual Foundation
-Wavelet matrices extend wavelet trees with better space utilization and dynamic alphabet support using bitmaps with rank/select.
+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
@@ -129,10 +129,12 @@ Cache-oblivious structures achieve optimal performance without knowing cache siz
```
Tree layout recursively:
-VEB Layout of tree with height h:
-- If h = 0: single node
-- If h > 0: layout of left subtree of size 2^(h-1),
- then layout of right subtree of size 2^(h-1)
+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.
@@ -141,7 +143,7 @@ VEB Layout of tree with height h:
### External Memory Model
-Parameters: B (block size), M (memory size), D (disk latency).
+Parameters: N (problem size), B (block size), M (memory size), and in the parallel disk model D (number of disks).
| Structure | I/O Complexity |
|-----------|----------------|
@@ -198,13 +200,14 @@ CRDTs achieve eventual consistency in distributed systems without coordination.
```python
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.items():
+ for node, count in other.counts.items():
self.counts[node] = max(self.counts.get(node, 0), count)
def value(self):
@@ -216,7 +219,7 @@ class GCounter:
| CRDT | Operations | Semantics |
|------|------------|-----------|
| G-Set | Add | Grow-only |
-| 2P-Set | Add, Remove | Add-wins |
+| 2P-Set | Add, Remove | Remove-wins (no re-add) |
| LWW-Register | Assign | Last-write-wins |
| OR-Set | Add with tag, Remove | Tag-based |
@@ -224,7 +227,7 @@ class GCounter:
### Holm-de Lichtenberg-Thorup (HDnT)
-Fully dynamic connectivity in O(log n):
+Fully dynamic connectivity with O(log² n) amortized updates and O(log n / log log n) queries:
```python
class HDnTConnectivity:
@@ -300,6 +303,239 @@ Combine data structures efficiently:
3. Persistent arrays with O(1) space per version?
4. 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.9, 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`, size `12 / 2 = 6`.
+- A at 1: `find_close = 6`, size `6 / 2 = 3` (A, C, D).
+- B at 7: `find_close = 10`, size `4 / 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.9 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.8 logs every write as `(time, field, old, new)`, in increasing time order. Write `read(node, field, t)` that returns the value `node.` 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.
+
+```python
+def read(node, field, t):
+ """Value of node. 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)
+
+```python
+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.
+
+
+
---
## Where this connects
diff --git a/src/volume-4/ch25-complete-selection-guide-and-complexity-reference.md b/src/volume-4/ch25-complete-selection-guide-and-complexity-reference.md
index c65b73a..362d1fb 100644
--- a/src/volume-4/ch25-complete-selection-guide-and-complexity-reference.md
+++ b/src/volume-4/ch25-complete-selection-guide-and-complexity-reference.md
@@ -32,7 +32,7 @@
| 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) | O(log C) | O(log C) | 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.
@@ -65,6 +65,166 @@ Each paradigm is defined by a bookkeeping question it must answer repeatedly, an
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.
+## 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.** The matrix lists "DSU (offline)" for dynamic connectivity. 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
+
+```python
+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.
+
+
+
---
## Where this connects
diff --git a/src/volume-4/index.md b/src/volume-4/index.md
index 8617325..03afcdd 100644
--- a/src/volume-4/index.md
+++ b/src/volume-4/index.md
@@ -8,4 +8,4 @@
Competitive-programming resources and the research papers behind these structures are collected in the [Bibliography](../appendices/bibliography.md).
-*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.*
+*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.*
diff --git a/src/volume-5/ch27-distributed-data-structures.md b/src/volume-5/ch27-distributed-data-structures.md
index ee47be7..d7ceb6b 100644
--- a/src/volume-5/ch27-distributed-data-structures.md
+++ b/src/volume-5/ch27-distributed-data-structures.md
@@ -37,7 +37,7 @@ Kademlia uses a XOR metric for distance, enabling more efficient lookups. The ke
**XOR Distance**: d(a,b) = a ⊕ b. This distance is symmetric and satisfies the triangle inequality, enabling simpler routing.
-**Node buckets**: Each node maintains k buckets for each prefix length. Buckets are prioritized by least-recently-seen nodes, ensuring long-lived nodes stay in routing tables.
+**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.
@@ -83,11 +83,11 @@ key_assigned_to = first_server where server_token > key_token
### Consistent Hashing with Bounded Load
-Amazon Dynamo improves on basic consistent hashing with load bounds:
+Consistent hashing with bounded loads (Mirrokni, Thorup and Zadimoghaddam, 2018; HAProxy exposes it as `hash-balance-factor`) caps how much any node can receive:
-1. Each node gets a "capacity" number representing load responsibility
-2. When a node receives too many keys, it splits its range with a neighbor
-3. System guarantees load within a factor of (2k/k+1) of ideal
+1. Pick ε > 0. With m keys (or active requests) on n nodes, each node gets a capacity of ⌈(1+ε)·m/n⌉
+2. 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
+3. 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
@@ -97,14 +97,13 @@ Replicating state across machines requires capturing consistent global states de
Designed for distributed snapshot collection without process coordination:
-1. **Initiator** sends marker on all outgoing channels
-2. When a process receives marker on channel C:
- - Record local state (marker is first from C)
- - Forward marker on all other outgoing channels
- - Start recording messages on channel C
-3. When all channels have received markers, snapshot is complete
+1. **Initiator** records its own state, then sends a marker on every outgoing channel
+2. 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
+3. When every process has recorded its state and received a marker on every incoming channel, the snapshot is complete
-**Causality guarantee**: The algorithm captures a consistent cut where each process's recorded state occurred at the same logical time across the system.
+**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
@@ -129,9 +128,9 @@ Raft Log Entry:
Conflict-free Replicated Data Types (CRDTs) enable eventual consistency without coordination. They guarantee convergence regardless of operation order.
-### Operation-based CRDTs
+### State-based Counters and Registers
-Each operation carries metadata enabling correct merge:
+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)**:
```python
@@ -140,7 +139,7 @@ class GCounter:
self.state = {} # node_id -> count
def increment(self, node_id):
- self.state[node_id] += 1
+ self.state[node_id] = self.state.get(node_id, 0) + 1
def merge(self, other):
for node_id, count in other.state.items():
@@ -168,12 +167,14 @@ class LWWRegister:
self.timestamp = other.timestamp
```
-### State-based CRDTs (Convergent CRDTs)
+### State-based Sets (Convergent CRDTs)
Operations are applied locally and entire state is merged using join operations:
**OR-Set (Observed-Remove Set)**:
```python
+from uuid import uuid4
+
class ORSet:
def __init__(self):
self.elements = {} # tag -> value
@@ -186,9 +187,11 @@ class ORSet:
def remove(self, tag):
self.tombstones.add(tag)
+ self.elements.pop(tag, None)
def merge(self, other):
- # Union of elements, removing tombstones
+ # 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()
@@ -223,7 +226,7 @@ Raft's three roles: **Leader**, **Follower**, **Candidate**. Term numbers provid
Optimized Paxos for replicated state machines:
- One leader per term (reduces prepare messages)
- PreparePromise with all accepted entries instead of single value
-- Accept phase can be skipped if no competing proposals
+- Prepare phase (phase 1) can be skipped while the leader is stable: each new command needs only the Accept phase
## 27.7 Quorum Systems
@@ -232,7 +235,7 @@ 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/2 failures)
+- **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
@@ -254,15 +257,246 @@ class VersionVector:
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) <= v
- for k, v in other.versions.items()
+ self.versions.get(k, 0) <= other.versions.get(k, 0)
+ for k in keys
) and any(
- self.versions.get(k, 0) < v
- for k, v in other.versions.items()
+ self.versions.get(k, 0) < other.versions.get(k, 0)
+ for k in keys
)
```
+## 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:
+
+1. 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.
+2. 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.
+3. 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`:
+
+```python
+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:
+
+```python
+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:
+
+```python
+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.
+
+
+
---
## Where this connects
diff --git a/src/volume-5/ch28-network-topology-and-routing-data-structures.md b/src/volume-5/ch28-network-topology-and-routing-data-structures.md
index dae7748..7639993 100644
--- a/src/volume-5/ch28-network-topology-and-routing-data-structures.md
+++ b/src/volume-5/ch28-network-topology-and-routing-data-structures.md
@@ -69,24 +69,24 @@ 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]
- / \
- [0.0/16] [1.0/24]
+ [192.168] ← stores the /16 route
+ |
+ [.1] ← stores the /24 route (the /16 contains it)
```
-**Linux routing cache** uses this structure internally. Memory per prefix: O(L) where L is number of bits until first branching.
+**BSD-derived kernels** use this structure (Sklower's radix tree) for their routing tables. Memory per prefix: O(L) where L is number of bits until first branching.
### LC-Trie (Level Compressed Trie)
-**Idea**: Group levels with low fan-out into arrays, apply trie compression to high-fan-out levels.
+**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^7 prefix range)
+Level 0-7: Compressed into single node (2^8 children)
Level 8-15: Second level compression
...
```
-Used in **Cisco IOS** and many hardware routers. Enables hardware-accelerated lookup with minimal memory.
+Used in the **Linux kernel's IPv4 forwarding table** (`fib_trie`). Few levels means few memory accesses per lookup, with modest memory.
### Multi-bit Trie
@@ -126,10 +126,11 @@ Prefix: 10.0.0.0/8
AS_PATH is a sequence, not a set. Multiple paths to same destination create branching structures:
```
-Dijkstra's algorithm adaptation for BGP:
-- Priority queue ordered by path attributes
-- Early exit when best path is known
-- Incremental updates when AS_PATH changes
+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.4 Software-Defined Networking (SDN) Tables
@@ -143,7 +144,7 @@ Hardware structure for wildcard matching:
- 1 = match bit exactly
- * = don't care (wildcard)
-**Priority**: Longest match wins (evaluate in order).
+**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:
@@ -200,22 +201,28 @@ class CountMinSketch:
Identify flows exceeding threshold T:
```python
+import heapq
+
class SpaceSaving:
def __init__(self, k):
self.k = k
self.counters = {} # flow_id -> count
- self.min_heap = [] # (count, flow_id) min-heap
+ 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 minimum
- min_count, evict_item = heapq.heappop(self.min_heap)
- self.counters[evict_item] = 0
+ # 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))
@@ -260,6 +267,217 @@ 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) Implement `insert(prefix, next_hop)` and `lookup(addr)` on a one-bit-per-level trie. (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)
+
+```python
+import ipaddress
+
+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
+
+
+t = RoutingTrie()
+t.insert("0.0.0.0/0", "D")
+t.insert("10.0.0.0/8", "A")
+t.insert("10.1.0.0/16", "B")
+t.insert("10.1.2.0/24", "C")
+assert t.lookup("10.1.2.3") == "C"
+assert t.lookup("10.1.3.4") == "B"
+assert t.lookup("10.2.0.1") == "A"
+assert t.lookup("11.0.0.1") == "D"
+```
+
+(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.3, 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.5.
+
+
+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.5 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.
+
+1. The counters sum to N. Each `add` raises 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.
+2. m never decreases. Counters only increase, and an eviction replaces the minimum with something larger.
+3. 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.
+
+
+
---
## Where this connects
diff --git a/src/volume-5/ch29-system-design-as-data-structure-composition.md b/src/volume-5/ch29-system-design-as-data-structure-composition.md
index 87456ad..99c7baf 100644
--- a/src/volume-5/ch29-system-design-as-data-structure-composition.md
+++ b/src/volume-5/ch29-system-design-as-data-structure-composition.md
@@ -46,7 +46,7 @@ Redis implements rich data types on top of key-value:
- **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/range
+- **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.
@@ -132,7 +132,7 @@ Compaction:
**Trade-offs vs B-trees**:
- Writes: 3-10x faster (sequential writes)
- Reads: Slower (check multiple structures)
-- Space: Higher (overwrite on read)
+- Space: Higher (stale versions persist until compaction removes them)
## 29.5 Load Balancing Algorithms
@@ -156,8 +156,8 @@ Request 4 → A (wrap)
Track active connections per server:
```python
class LeastConnections:
- def __init__(self):
- self.connections = {} # server -> count
+ 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)
@@ -169,7 +169,7 @@ class LeastConnections:
self.connections[server] -= 1
```
-**Problem**: Doesn't account for varying request durations.
+**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
@@ -184,6 +184,128 @@ def score_server(server):
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:
+
+```python
+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:
+
+```python
+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.
+
+```python
+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()` 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:
@@ -203,7 +325,7 @@ CDNs create multi-level caching hierarchies for content distribution.
**TTL-based expiration**:
```python
def is_valid(cached_item, max_age):
- return time.now() - cached_item.timestamp < max_age
+ return time.time() - cached_item.timestamp < max_age
```
**Active invalidation**: Purge signals propagate through cache hierarchy.
@@ -211,35 +333,226 @@ def is_valid(cached_item, max_age):
**Probabilistic early expiration**: Reduce cache stampedes:
```python
def should_revalidate(item, beta=1.0):
- # Beta = fuzziness parameter
- grace_time = item.ttl * beta
- if time.now() - item.expires > grace_time:
- return random.random() < 0.5 # Probabilistic revalidate
- return False
+ # 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
```
-### LFU-D with Dynamic Aging
+### 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](../volume-2/ch12-hash-tables.md), 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.
-Frequency-based with aging to prioritize recency:
```python
-class LFUD:
- def __init__(self):
- self.freq = {} # key -> frequency count
- self.min_freq = 0
+from collections import OrderedDict, defaultdict
+
- def access(self, key):
- self.freq[key] = self.freq.get(key, 0) + 1
- self.min_freq = min(self.freq.values())
+class LFUCache:
+ """O(1) LFU: keys grouped by frequency; ties go to the least recently used."""
- def evict(self):
- # Evict lowest frequency, age all frequencies
- for key in list(self.freq.keys()):
- self.freq[key] -= self.min_freq
- if self.freq[key] <= 0:
- del self.freq[key]
+ 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.
+
+```python
+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](../volume-3/ch14-probabilistic-data-structures.md) 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.
+
+```python
+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.
@@ -252,10 +565,10 @@ class TokenBucket:
self.rate = rate
self.capacity = capacity
self.tokens = capacity
- self.last_update = time.now()
+ self.last_update = time.time()
def allow(self, tokens=1):
- now = time.now()
+ now = time.time()
elapsed = now - self.last_update
self.tokens = min(
self.capacity,
@@ -276,8 +589,9 @@ class TokenBucket:
More accurate rate limiting:
```python
class SlidingWindowLog:
- def __init__(self, window_size):
+ 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):
@@ -296,9 +610,341 @@ class SlidingWindowLog:
**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.
+
+```python
+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.
+
+```python
+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
+
+```python
+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](../volume-1/ch10-multiway-search-trees-and-b-trees.md). The B-trees inside every storage engine described here
+- [Chapter 12: Hash Tables](../volume-2/ch12-hash-tables.md). The hash map plus linked list that every LRU cache in §29.6 is built from
- [Chapter 14: Probabilistic Data Structures](../volume-3/ch14-probabilistic-data-structures.md). The probabilistic structures these systems rely on
diff --git a/src/volume-5/ch30-advanced-system-patterns-and-case-studies.md b/src/volume-5/ch30-advanced-system-patterns-and-case-studies.md
index c1a2894..0c44efd 100644
--- a/src/volume-5/ch30-advanced-system-patterns-and-case-studies.md
+++ b/src/volume-5/ch30-advanced-system-patterns-and-case-studies.md
@@ -98,17 +98,19 @@ 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 distribution)
- level = int(-log(random()) % max_layers)
+ # Random layer selection (geometric): P(level >= l) = m ** -l
+ level = min(int(-log(random()) * self.mL), max_layers - 1)
- # Search from top layer to find insert position
+ # (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=1, layer=l)
- # Connect to m nearest unconnected nodes
+ candidates = self._search_layer(vector, ef=self.ef, layer=l)
+ # Connect to the m nearest candidates
self._connect(vector, candidates, l)
```
@@ -206,11 +208,11 @@ Physical Node B → VNode_3, VNode_8, VNode_15, VNode_19
Physical Node C → VNode_2, VNode_11, VNode_17, VNode_24
Shard calculation:
-shard = hash(key) % (num_physical × num_vnodes)
-owner = virtual_node_ring[shard]
+vnode = hash(key) % NUM_VNODES (fixed for the life of the cluster)
+owner = vnode_owner[vnode]
```
-**Rebalancing**: When adding nodes, only O(1/k) keys move where k is virtual node count.
+**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
@@ -279,13 +281,13 @@ class Span:
self.trace_id = trace_id
self.span_id = span_id
self.parent_id = parent_id
- self.start_time = time.now()
+ self.start_time = time.time()
self.end_time = None
self.tags = {}
self.annotations = []
def finish(self):
- self.end_time = time.now()
+ self.end_time = time.time()
def duration_ms(self):
return (self.end_time - self.start_time) * 1000
@@ -309,6 +311,217 @@ 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:
+
+```python
+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
+
+```python
+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.
+
+
+
---
## Where this connects
diff --git a/src/volume-5/ch31-real-world-case-studies.md b/src/volume-5/ch31-real-world-case-studies.md
index 2606dad..b6058e4 100644
--- a/src/volume-5/ch31-real-world-case-studies.md
+++ b/src/volume-5/ch31-real-world-case-studies.md
@@ -41,7 +41,7 @@ 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. With ε ≈ 7ms of uncertainty, every commit sleeps roughly 7ms before releasing locks. 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 ε.
+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](../volume-3/ch17-persistent-data-structures.md)'s partial persistence, deployed globally.
@@ -62,7 +62,7 @@ Consistent hashing ring (N=3, R=2, W=2):
- N: Number of replicas
- R: Minimum read replicas
- W: Minimum write replicas
-- Quorum: max(R,W) > N/2
+- 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.
@@ -211,6 +211,129 @@ Three observations worth carrying:
**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](../volume-3/ch16-external-memory-and-cache-oblivious-structures.md), 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
diff --git a/src/volume-5/ch32-synthesis-and-future-directions.md b/src/volume-5/ch32-synthesis-and-future-directions.md
index 58b976d..007b135 100644
--- a/src/volume-5/ch32-synthesis-and-future-directions.md
+++ b/src/volume-5/ch32-synthesis-and-future-directions.md
@@ -135,6 +135,197 @@ New structures will keep arriving, and most will not last. The survivors are the
That last constraint is the one this book opened with, in [Chapter 1](../volume-1/ch01-the-philosophy-and-mathematics-of-data-structures.md): 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
+
+```python
+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
diff --git a/theme/custom.css b/theme/custom.css
index 76fec10..64fca89 100644
--- a/theme/custom.css
+++ b/theme/custom.css
@@ -43,9 +43,11 @@ figure svg {
}
}
+/* Font sizes use em, not rem: mdBook sets the root font size to 62.5%, so
+ 1rem is only 10px. */
figcaption {
margin-top: 0.6rem;
- font-size: 0.875rem;
+ font-size: 0.875em;
line-height: 1.5;
opacity: 0.72;
font-style: italic;
@@ -54,12 +56,12 @@ figcaption {
/* "Where this connects" footers */
h2#where-this-connects {
- font-size: 1.1rem;
+ font-size: 1.1em;
opacity: 0.85;
}
h2#where-this-connects + ul {
- font-size: 0.925rem;
+ font-size: 0.925em;
}
/* Wide reference tables should scroll rather than overflow the page */
@@ -75,3 +77,30 @@ h2#where-this-connects + ul {
.content pre > code {
overflow-x: auto;
}
+
+/* Exercise hints and solutions: folded by default, clearly clickable */
+.content details {
+ margin: 0.4rem 0 1.4rem;
+ padding: 0.5rem 0.9rem;
+ border-left: 3px solid var(--links);
+ background: var(--quote-bg);
+ border-radius: 0 4px 4px 0;
+}
+
+.content details > summary {
+ cursor: pointer;
+ font-weight: 600;
+ font-size: 0.925em;
+ opacity: 0.85;
+}
+
+.content details[open] > summary {
+ margin-bottom: 0.6rem;
+}
+
+.content details + details {
+ margin-top: -0.8rem;
+}
+
+/* Printing: theme/print-details.js opens every before printing,
+ so hints and solutions appear in the PDF. */
diff --git a/theme/print-details.js b/theme/print-details.js
new file mode 100644
index 0000000..9f14afe
--- /dev/null
+++ b/theme/print-details.js
@@ -0,0 +1,15 @@
+// Expand every hint and solution when the book is printed or saved as PDF,
+// then restore the reader's open/closed state afterwards.
+(function () {
+ var opened = [];
+ window.addEventListener("beforeprint", function () {
+ document.querySelectorAll("details:not([open])").forEach(function (d) {
+ d.open = true;
+ opened.push(d);
+ });
+ });
+ window.addEventListener("afterprint", function () {
+ opened.forEach(function (d) { d.open = false; });
+ opened = [];
+ });
+})();