diff --git a/README.md b/README.md index 9a7a062..415a788 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,11 @@ 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 · ~155,000 words · 225 exercises with worked solutions · Python, C, C++, Java and Go examples. +Five volumes · 31 chapters · 4 appendices · ~185,000 words · 241 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. -Also by the author: **[Frontier LLM Engineering](https://github.com/dnakhoa/frontier-llm-engineering)** — a free field guide to how frontier language models are actually built, with exercises and runnable labs. +Also by the author: **[Frontier LLM Engineering](https://github.com/dnakhoa/frontier-llm-engineering)**: a free field guide to how frontier language models are actually built, with exercises and runnable labs. --- diff --git a/src/appendices/appendix-a-complexity-cheat-sheet.md b/src/appendices/appendix-a-complexity-cheat-sheet.md index a3e2194..40fe9a6 100644 --- a/src/appendices/appendix-a-complexity-cheat-sheet.md +++ b/src/appendices/appendix-a-complexity-cheat-sheet.md @@ -17,6 +17,13 @@ Two conventions for reading these tables: | Stack | n/a | O(n) | O(1)★ | O(1)★ | O(n) | | Queue | n/a | O(n) | O(1)★ | O(1)★ | O(n) | | Deque | O(1) | O(n) | O(1)★ at either end | O(1)★ at either end | O(n) | +| Circular buffer (fixed capacity) | O(1) | O(n) | O(1) at the rear | O(1) at the front | O(capacity) | +| Bit array | O(1) | O(n/w) | O(1) set a bit | O(1) clear a bit | n bits | +| Gap buffer (text) | O(1) | O(n) | O(1) at the cursor, O(distance) to move it | O(1) at the cursor | O(n) | +| Rope (text) | O(log n) | O(n) | O(log n) anywhere | O(log n) anywhere | O(n) | +| Piece table (text, list of k pieces) | O(k) | O(n) | O(k), text itself never moves | O(k) | O(n + k) | + +Where **w** = machine word size in bits. The linked-list rows come with the caveat that makes them much less useful than they look: insertion and deletion are O(1) **only once you already hold the relevant node**. Getting there is O(n), so an insert-at-position is O(n) overall. @@ -31,11 +38,16 @@ The linked-list rows come with the caveat that makes them much less useful than | Treap | O(log n) expected | O(n) | O(log n) expected | O(log n) expected | O(n) | | Skip list | O(log n) expected | O(n) | O(log n) expected | O(log n) expected | **O(n) expected** | | B-tree / B+ tree | O(log_B n) I/Os | O(log_B n) I/Os | O(log_B n) | O(log_B n) | O(n) | +| Order-statistic tree (size-augmented balanced BST) | O(log n) select / rank | O(log n) | O(log n) | O(log n) | O(n) | +| van Emde Boas tree (integer keys < u) | O(log log u) | O(log log u) | O(log log u) | O(log log u) | O(u), or O(n log log u) hashed | +| y-fast trie (integer keys < u) | O(log log u) | O(log log u) | O(log log u)★ | O(log log u)★ | O(n) | | Trie | O(L) | O(L) | O(L) | O(L) | O(N·A) | | Radix / Patricia trie | O(L) | O(L) | O(L) | O(L) | O(N) | Where **L** = key length, **N** = total characters stored across all keys, **A** = alphabet size. +On a BST of height h, successor, predecessor, floor and ceiling are O(h), and reporting every key in a range is O(h + k) for k results. A B-tree with minimum degree t has height at most log_t((n+1)/2); with t = 500, a billion keys fit in 4 levels. ([Chapter 7](../volume-1/ch07-binary-search-trees.md), [Chapter 10](../volume-1/ch10-multiway-search-trees-and-b-trees.md)) + Two rows worth reading carefully. **Skip list space is O(n) expected**, not O(n log n): with promotion probability p = ½, the expected total number of nodes across all levels is 2n. The O(log n) is the expected *height*, which is a different quantity. And **splay trees** have no per-operation guarantee at all: a single access can cost O(n), and only a sequence of m operations is bounded, at O(m log n). That makes them unsuitable for latency-sensitive work regardless of their excellent amortized behavior. ## A.3 Hash-Based Structures @@ -44,11 +56,15 @@ Two rows worth reading carefully. **Skip list space is O(n) expected**, not O(n |-----------|-------------|----------------|--------|--------|-------| | Hash table (chaining) | O(1) | O(n) | O(1)★ | O(1) | O(n + m) | | Hash table (open addressing) | O(1) | O(n) | O(1)★ | O(1) | O(m) | +| Robin Hood hashing | O(1) | O(n) | O(1)★ | O(1), backward shift | O(m) | +| Swiss table | O(1) | O(n) | O(1)★ | O(1) | O(m) plus 1 control byte per slot | | Cuckoo hashing | O(1) | **O(1) worst case** | O(1)★ expected | O(1) | O(n) | | Perfect hashing (static) | O(1) | O(1) | n/a | n/a | O(n) | Where **m** = number of buckets. Cuckoo hashing is the notable row: it is one of the few hash schemes with a genuine O(1) *worst-case* lookup, because a key can only live in one of two positions. Insertion pays for it, and can fail and require a full rehash. +Robin Hood hashing has the same *average* probe length as plain linear probing; what it improves is the variance, so the longest probe sequence and the cost of an unsuccessful lookup (which can stop early) drop sharply at high load. ([Chapter 12](../volume-2/ch12-hash-tables.md)) + Java's `HashMap` converts a bucket to a red-black tree past 8 entries, giving O(log n) rather than O(n) in the worst case: a defense against deliberate collision flooding. ## A.4 Heaps and Priority Queues @@ -56,35 +72,44 @@ Java's `HashMap` converts a bucket to a red-black tree past 8 entries, giving O( | Structure | Find min | Insert | Delete min | Decrease key | Merge | Space | |-----------|----------|--------|-----------|--------------|-------|-------| | Binary heap | O(1) | O(log n) | O(log n) | O(log n) | O(n) | O(n) | +| Indexed binary heap (position map) | O(1) | O(log n) | O(log n) | O(log n), and O(1) to locate the item | O(n) | O(n) | | d-ary heap | O(1) | O(log_d n) | O(d·log_d n) | O(log_d n) | O(n) | O(n) | | Binomial heap | O(log n) | O(1)★ | O(log n) | O(log n) | O(log n) | O(n) | | Fibonacci heap | O(1) | O(1) | O(log n)★ | O(1)★ | O(1) | O(n) | -| Pairing heap | O(1) | O(1) | O(log n)★ | O(log log n)★ | O(1) | O(n) | +| Pairing heap | O(1) | O(1) | O(log n)★ | o(log n)★, exact bound open | O(1) | O(n) | Building a heap from n existing elements is **O(n)**, not O(n log n): Floyd's bottom-up heapify. This surprises people and is worth remembering. +The pairing heap's decrease-key is known to be Ω(log log n)★ (Fredman, 1999) and o(log n)★ (Pettie's 2005 bound is O(2^(2√(log log n)))★), but its exact cost is still an open problem. + Fibonacci heaps have the best bounds on this table and lose to binary heaps on most real workloads; see [Chapter 19](../volume-3/ch19-emerging-and-specialized-structures.md). ## A.5 Graphs For a graph with V vertices and E edges: -| Operation | Adjacency list | Adjacency matrix | -|-----------|---------------|------------------| -| Space | O(V + E) | O(V²) | -| Add edge | O(1) | O(1) | -| Check edge (u,v) | O(deg(u)) | O(1) | -| Iterate neighbors of u | O(deg(u)) | O(V) | -| BFS / DFS | O(V + E) | O(V²) | +| Operation | Adjacency list | Adjacency matrix | CSR (static) | +|-----------|---------------|------------------|--------------| +| Space | O(V + E) | O(V²) | O(V + E), no pointers | +| Add edge | O(1) | O(1) | O(V + E) rebuild | +| Check edge (u,v) | O(deg(u)) | O(1) | O(log deg(u)) if sorted | +| Iterate neighbors of u | O(deg(u)) | O(V) | O(deg(u)), sequential | +| BFS / DFS | O(V + E) | O(V²) | O(V + E) | | Algorithm | Complexity | Requires | |-----------|-----------|----------| | BFS / DFS | O(V + E) | n/a | -| Topological sort | O(V + E) | DAG | +| Cycle detection (directed, three-colour DFS) | O(V + E) | n/a | +| Bipartiteness check (BFS 2-colouring) | O(V + E) | n/a | +| Topological sort (Kahn or DFS) | O(V + E) | DAG; Kahn also detects cycles | +| Strongly connected components (Kosaraju, Tarjan) | O(V + E) | Directed graph | +| 0-1 BFS | O(V + E) | Edge weights 0 or 1 | +| DAG shortest paths | O(V + E) | DAG, any weights | | Dijkstra (binary heap) | O((V + E) log V) | Non-negative weights | | Dijkstra (Fibonacci heap) | O(E + V log V) | Non-negative weights | | Bellman-Ford | O(V·E) | Detects negative cycles | -| Floyd-Warshall | O(V³) | All pairs | +| Floyd-Warshall | O(V³) | All pairs; negative edges but no negative cycles | +| Johnson's algorithm | O(V·E log V) | All pairs, sparse graphs, negative edges | | Kruskal MST | O(E log E) | Union-find | | Prim MST (binary heap) | O(E log V) | n/a | | Union-Find (path compression + union by rank) | O(α(n)) ★ | n/a | @@ -101,10 +126,13 @@ That last row is a common trap. Rollback requires undoing parent changes, which | Bloom filter | O(k) | O(k) | ~1.44·log₂(1/ε)·n bits | False positives only | | Counting Bloom filter | O(k) | O(k) | 4× a Bloom filter | False positives only | | Cuckoo filter | O(1) | O(1)★ | ~(log₂(1/ε) + 3)·n bits | False positives; supports delete | -| HyperLogLog | O(1) | O(1) | O(log log n), ~12KB for billions | ~2% cardinality error | +| HyperLogLog | O(1) | O(1) | O(log log n) bits per register; 12 KB in the standard configuration | ~0.81% standard error with 16,384 registers (1.04/√m) | +| Roaring bitmap | O(log c) to find the container, then O(1) or O(log 4096) | O(log c), plus up to 4,096 shifted values in an array container | ≤ 16 bits per value within a container | None, exact | | Count-Min Sketch | O(k) | O(k) | O((1/ε)·log(1/δ)) | Overestimates only | | Skip list | O(log n) expected | O(log n) expected | O(n) expected | None, exact | +Where **c** = number of non-empty Roaring containers (at most 65,536 for 32-bit values). + A Bloom filter with 1% false-positive rate needs about 9.6 bits per element regardless of how large the elements are, which is the property that makes it useful. ## A.7 Competitive Programming Structures @@ -125,13 +153,63 @@ A Bloom filter with 1% false-positive rate needs about 9.6 bits per element rega | Suffix automaton | O(n) | O(m) | Incremental | O(n), ≤ 2n−1 states | | Suffix tree | O(n) | O(m) | Static | O(n) | | Palindromic tree (eertree) | O(n) | O(1)★ | Incremental | O(n) | -| Li Chao tree | O(n) | O(log C) | O(log C) | O(n) | +| Li Chao tree | O(n log C) by n inserts | O(log C) | O(log C) | O(n) | Where **σ** = alphabet size, **m** = pattern length, **C** = coordinate range. Mo's algorithm is offline and processes q queries in O((n + q)√n) *total*; the O(√n) figure is the amortized per-query share, not a bound on any single query. -## A.8 Complexity Growth Reference +## A.8 Array and Sequence Techniques + +| Technique | Time | Extra space | Requires | +|-----------|------|-------------|----------| +| Binary search (lower / upper bound) | O(log n) | O(1) | Sorted array | +| Binary search on the answer | O(log R) predicate calls | O(1) | Monotone predicate over a range of size R | +| Two pointers | O(n) | O(1) | Sorted array (for pair-sum style problems) | +| Sliding window (fixed or variable) | O(n) | O(1) | Non-negative values for the variable "sum ≥ target" form | +| Prefix sums (1-D) | O(n) build, O(1) range sum | O(n) | Static array | +| Prefix sums (2-D) | O(rc) build, O(1) rectangle sum | O(rc) | Static r × c matrix | +| Difference array | O(1) per range add, O(n) to rebuild | O(n) | All updates before reads | +| Monotonic stack (next greater element) | O(n) total, amortized | O(n) | n/a | +| Monotonic deque (sliding-window maximum) | O(n) total, amortized | O(k) | n/a | +| In-place linked-list reversal | O(n) | O(1) | n/a | +| Floyd's cycle detection | O(μ + λ) | O(1) | n/a | +| Merge sort on a linked list | O(n log n) | O(log n) stack, O(1) bottom-up | n/a | + +Where **μ** = distance to the cycle and **λ** = cycle length. + +| String matching | Preprocess | Search a text of length n | Notes | +|-----------------|-----------|---------------------------|-------| +| KMP (prefix function) | O(m) | O(n) worst case | Never backs up in the text | +| Z-algorithm | O(n + m) total | O(n + m) worst case | Search P + separator + T | +| Rabin-Karp (rolling hash) | O(m) | O(n + m) expected | Random base and a large prime; verify matches to make it exact | +| Aho-Corasick (many patterns) | O(total pattern length) | O(n + number of matches) | One pass for every pattern | +| Suffix array (search) | O(n) to O(n log n) build | O(m log n) per query | Index the text once, query many patterns | + +| Posting-list intersection (lists of length m ≤ n) | Time | +|---------------------------------------------------|------| +| Linear merge | O(m + n) | +| Galloping (exponential) search | O(m log(n/m)) | +| Skip pointers | Between the two, depending on skip spacing | + +## A.9 Caches and Load Balancing + +| Structure | Per access | Metadata per entry | Scan-resistant | +|-----------|-----------|--------------------|----------------| +| LRU (hash map + doubly linked list) | O(1) | Two pointers | No | +| LFU (frequency buckets) | O(1) | Pointers plus a count | Yes, but slow to forget | +| CLOCK (second chance) | O(1) amortized | One reference bit | No | +| ARC | O(1) | Pointers, plus ghost lists | Yes | +| W-TinyLFU | O(1) | Pointers, plus a shared Count-Min sketch | Yes | + +| Load balancing rule | Maximum load, n requests into n servers | +|---------------------|-----------------------------------------| +| Uniformly random | Θ(log n / log log n) with high probability | +| Power of d choices (d ≥ 2) | ln ln n / ln d + Θ(1) with high probability | + +See [Chapter 29](../volume-5/ch29-system-design-as-data-structure-composition.md) for the simulations behind both tables. + +## A.10 Complexity Growth Reference How the classes actually behave, for intuition about when each becomes infeasible: diff --git a/src/appendices/appendix-b-when-to-use-what.md b/src/appendices/appendix-b-when-to-use-what.md index 4206e2c..20ae3a4 100644 --- a/src/appendices/appendix-b-when-to-use-what.md +++ b/src/appendices/appendix-b-when-to-use-what.md @@ -73,7 +73,7 @@ The structure that makes each operation cheapest, with the cost of choosing it. | Insert in the middle given a position | Linked list, O(1) | Finding the position is O(n) | | Merge two collections | Leftist / pairing heap, O(log n) | Slower than a binary heap otherwise | | Membership, huge set | Bloom filter, O(k) | False positives; no enumeration | -| Count distinct | HyperLogLog, O(1) | ~2% error | +| Count distinct | HyperLogLog, O(1) | ~0.81% standard error in 12 KB | | Connectivity under merging | Union-find, O(α(n)) | Cannot split | ## B.4 By Scale diff --git a/src/appendices/appendix-c-glossary.md b/src/appendices/appendix-c-glossary.md index f85760c..68ce10a 100644 --- a/src/appendices/appendix-c-glossary.md +++ b/src/appendices/appendix-c-glossary.md @@ -16,54 +16,98 @@ **Time / Space Complexity**: How running time or memory grows with input size. +**Word RAM**: A cost model in which memory holds w-bit words and arithmetic and bitwise operations on a word cost O(1). It is the model in which integer structures such as van Emde Boas trees beat the O(log n) comparison bound. + **Worst case**: The maximum over all inputs, including adversarial ones. The bound that matters when input is untrusted. ## Structural Terms +**Augmented Tree**: A tree whose nodes store extra summary data about their subtrees (sizes, sums, maximums) that is kept correct through inserts, deletes and rotations. Order-statistic trees and interval trees are examples. + **Balanced Tree**: A tree whose subtree heights differ by at most a constant factor, guaranteeing O(log n) height. +**Bulk Loading**: Building a B-tree or B+ tree bottom-up from sorted data instead of by repeated insertion. Much faster, and it lets you choose how full each node is. + **Cursor**: A position indicator within a data structure. +**Decrease-Key**: The priority-queue operation that lowers an existing element's priority. A binary heap needs a position map (an indexed heap) to find the element first. + **Degenerate Tree**: A tree that has degraded to essentially a linked list, the worst case for an unbalanced BST. **Fan-out**: The number of children a node can have. High fan-out is what makes B-trees shallow. +**Fill Factor**: How full a B-tree's nodes are allowed or chosen to be. Sorted inserts leave nodes about half full; bulk loading can pack them completely. + **Heap Property**: Every parent compares greater (max-heap) or less (min-heap) than its children. Note this is a *weaker* invariant than sorted order. **Invariant**: A property that must hold before and after every operation. Writing invariants as runnable assertions is the most effective way to catch structural bugs near their cause. **Leaf**: A node with no children. -**Sentinel**: A dummy node that removes special cases (an empty-list check, a null-pointer test)by guaranteeing a node always exists. +**Minimum Degree (t)**: The B-tree parameter that bounds node size: every node except the root holds between t − 1 and 2t − 1 keys. + +**Order Statistic**: The k-th smallest element of a set. A BST augmented with subtree sizes answers select (k-th smallest) and rank (position of a key) in O(height). + +**Predecessor / Successor**: The largest key smaller than x, and the smallest key larger than x. The core query of ordered sets, and the problem van Emde Boas trees solve for integer keys. + +**Rope**: A balanced tree whose leaves hold chunks of text, giving O(log n) insert, delete and indexing anywhere in a large string. Used by several text editors. + +**Sentinel**: A dummy node that removes special cases (an empty-list check, a null-pointer test) by guaranteeing a node always exists. + +**Serialization**: Writing a structure to a flat sequence (bytes, text) from which it can be rebuilt. A binary tree needs either null markers or two traversals to be rebuilt exactly. **Tombstone**: A marker left in place of a deleted entry so that probe sequences in an open-addressed hash table are not broken. +**van Emde Boas Tree**: A recursive structure for integer keys below u that splits each key into high and low halves, answering predecessor and successor queries in O(log log u). + ## Hashing **Collision**: When two distinct keys hash to the same index. Unavoidable whenever the key space exceeds the table size. +**Control Byte**: In a Swiss table, one byte of metadata per slot recording empty, deleted, or full plus 7 bits of the key's hash. A lookup compares a whole group of control bytes at once before touching any keys. + +**Hash Flooding**: A denial-of-service attack that sends many keys known to collide, turning a hash table's O(1) operations into O(n). Defended against with seeded, keyed hash functions such as SipHash. + **Load Factor (α)**: Ratio of stored elements to capacity. Open addressing degrades sharply above ~0.7; chaining tolerates α > 1. **Open Addressing**: Resolving collisions by probing for another slot within the table itself, rather than chaining externally. **Perfect Hashing**: A collision-free hash for a known, fixed key set. *Minimal* perfect hashing maps n keys onto exactly n slots. +**Probe Sequence Length (PSL)**: How far an entry in an open-addressed table sits from its home slot. Robin Hood hashing keeps PSLs even by letting an inserted key take the slot of any entry closer to home. + +**Robin Hood Hashing**: Linear probing where an inserted key displaces any entry with a shorter probe sequence length. Average cost is unchanged, but the variance and the cost of misses drop sharply. + +**SipHash**: A fast keyed hash function designed to resist hash flooding. The default string hash in Python, Ruby and Rust. + +**Swiss Table**: An open-addressing hash table that stores a control byte per slot and probes 16-slot groups with SIMD instructions. Abseil's flat_hash_map, Rust's HashMap and Go's maps since 1.24 use the design. + **Universal Hashing**: Choosing a hash function at random from a family, so that no fixed input is reliably bad. The defense against collision-flooding attacks. ## Memory and Storage +**Bit-Packing**: Storing a block of small integers in exactly as many bits each as the largest needs. With delta encoding, the basis of posting-list compression in search engines. + **Cache Line**: The unit of transfer between memory and cache, typically 64 bytes. Reading one byte costs the same as reading its whole line. **Cache-Oblivious**: Achieving optimal I/O performance without knowing the block size. By being well-organized at every scale simultaneously. **External Memory Model**: A cost model counting block transfers rather than operations. Predicts real disk performance where the RAM model does not. +**Gap Buffer**: A text buffer that keeps one contiguous gap at the cursor, so typing is O(1) but moving the cursor far away costs a large copy. Used by Emacs. + **Locality**: The tendency of an access pattern to touch nearby addresses. Sequential access has good locality; pointer chasing has none. **LSM Tree (Log-Structured Merge)**: A write-optimized structure that buffers writes in memory and flushes them as sorted immutable runs, converting random writes to sequential ones. **Page**: The unit of transfer between memory and disk, typically 4KB. +**Piece Table**: A text representation made of an append-only original buffer, an append-only add buffer, and a list of pieces pointing into them. Edits never move text, and undo is cheap. + +**Segment (search index)**: An immutable chunk of an inverted index. New documents create new segments, deletions are marked in a bitset, and background merges combine segments, much like LSM-tree compaction. + +**Varint (Variable-Byte Encoding)**: Encoding an integer in 7-bit groups, one per byte, with the high bit marking that more bytes follow. Small numbers take one byte. + **Write Amplification**: The ratio of bytes actually written to storage versus bytes logically written by the application. ## Persistence and Concurrency @@ -80,14 +124,16 @@ **MVCC (Multi-Version Concurrency Control)**: Keeping multiple versions of each row so readers see a consistent snapshot without blocking writers. Partial persistence, applied to databases. -**Persistent**: Preserving previous versions after modification. *Partial* persistence allows querying old versions; *full* allows updating them; *confluent* allows merging them. Unrelated to durable storage. - **Path Copying**: Achieving persistence by duplicating only the nodes on the path from root to the modification point, O(log n) per update in a balanced tree. +**Persistent**: Preserving previous versions after modification. *Partial* persistence allows querying old versions; *full* allows updating them; *confluent* allows merging them. Unrelated to durable storage. + **Structural Sharing**: Reusing unchanged subtrees between versions of an immutable structure. What makes persistence affordable. ## Distributed Systems +**Admission Policy**: A cache's rule for whether a new item should enter at all, rather than which item to evict. W-TinyLFU admits a newcomer only if it is estimated to be more popular than the victim. + **CAP Theorem**: During a network partition, a distributed system must sacrifice either consistency or availability. See [Appendix D](appendix-d-network-and-system-design-quick-reference.md) for why "CA" is not a third option. **Consistent Hashing**: Mapping keys and nodes onto a ring so that adding or removing a node remaps only ~1/n of keys, rather than nearly all of them. @@ -98,10 +144,14 @@ **Eventual Consistency**: A guarantee that replicas converge given no further updates, with no bound on when. -**Merkle Tree**: A tree of hashes where each node hashes its children, allowing two large datasets to be compared (and their differences located)in logarithmic work. +**Merkle Tree**: A tree of hashes where each node hashes its children, allowing two large datasets to be compared (and their differences located) in logarithmic work. + +**Power of Two Choices**: Sending each request to the less loaded of two randomly chosen servers. Cuts the maximum load from Θ(log n / log log n) to Θ(log log n) and avoids the herding that "least loaded" suffers with stale data. **Quorum**: A subset of replicas that must acknowledge an operation. Overlapping read and write quorums (R + W > N) give strong consistency. +**Scan Resistance**: A cache policy's ability to survive a one-off sequential scan without evicting its genuinely popular items. LRU has none; LFU, ARC and W-TinyLFU do. + **Vector Clock**: A per-replica counter vector that distinguishes causally-ordered updates from genuinely concurrent ones. ## Probabilistic and Compressed @@ -110,20 +160,74 @@ **Count-Min Sketch**: A fixed-size frequency estimator over a stream, which overestimates but never underestimates. -**HyperLogLog**: A cardinality estimator using the maximum leading-zero count of hashes, giving ~2% error in about 12KB regardless of set size. +**HyperLogLog**: A cardinality estimator using the maximum leading-zero count of hashes, giving about 0.81% standard error in 12 KB (16,384 registers) regardless of set size. **Rank / Select**: The two primitives underlying succinct structures. `rank(i)` counts 1-bits before position i; `select(k)` finds the position of the k-th 1-bit. +**Roaring Bitmap**: A compressed bitmap that splits 32-bit values into 65,536 chunks and stores each chunk as a sorted array, a plain bitmap or a list of runs, whichever is smallest. Used by Lucene, Druid, ClickHouse and many others. + **Succinct**: Using space within a lower-order term of the information-theoretic minimum, while still supporting queries *without decompressing*. ## Spatial and String +**Border**: A string that is both a proper prefix and a suffix of another. The prefix function (KMP's failure function) records the longest border of each prefix of a pattern. + +**Inverted Index**: A map from each term to its posting list, the sorted list of documents containing it. The core structure of full-text search. + **LCP Array**: Longest Common Prefix between each pair of adjacent suffixes in a suffix array. Together they encode a suffix tree implicitly. **MBR (Minimum Bounding Rectangle)**: The smallest axis-aligned rectangle enclosing a set of objects. The key type in an R-tree, and overlap between sibling MBRs is what degrades R-tree queries. +**Posting List**: The sorted list of document IDs (plus frequencies or positions) for one term in an inverted index. Stored as compressed gaps between consecutive IDs. + +**Rolling Hash**: A hash of a sliding window that can be updated in O(1) as the window moves one character. The basis of Rabin-Karp matching and of content-defined chunking in rsync and backup tools. + **Space-Filling Curve**: A mapping from multi-dimensional coordinates to one dimension that mostly preserves locality, Z-order and Hilbert being the common ones. The basis of geohashing. **Suffix Array**: The sorted list of a string's suffix starting positions. Suffix-tree power at about 4 bytes per character rather than 20. **Trie**: A tree keyed by character position, where lookup costs O(key length) independent of how many keys are stored. + +**Z-Array**: For each position i of a string, the length of the longest substring starting at i that matches a prefix of the string. Computed in O(n) and used for pattern matching. + +## Graphs + +**Adjacency List / Matrix**: The two standard graph representations. A list stores each vertex's neighbours (O(V + E) space); a matrix stores a V × V table of edges (O(V²) space, O(1) edge test). + +**Back Edge**: In a DFS, an edge to an ancestor still on the recursion stack. A directed graph has a cycle exactly when DFS finds one. + +**Bipartite**: A graph whose vertices split into two sides with every edge crossing between them. Equivalent to having no odd-length cycle. + +**CSR (Compressed Sparse Row)**: A static graph layout of two arrays, the concatenated neighbour lists and an offset per vertex. Compact and cache-friendly; adding an edge means rebuilding. + +**Cut Property**: For any split of a graph's vertices into two groups, the lightest edge crossing the split belongs to some minimum spanning tree. The reason Kruskal's and Prim's greedy choices are safe. + +**DAG (Directed Acyclic Graph)**: A directed graph with no cycles. Exactly the graphs that have a topological order. + +**Negative Cycle**: A cycle whose edge weights sum to less than zero. Shortest paths through it are undefined; Bellman-Ford detects one. + +**Relaxation**: Updating a vertex's tentative distance with dist[v] = min(dist[v], dist[u] + w(u, v)). Every shortest-path algorithm is a strategy for which edges to relax in which order. + +**Strongly Connected Component (SCC)**: A maximal set of vertices in a directed graph that can all reach one another. Collapsing each SCC to one vertex always leaves a DAG. + +**Topological Order**: An ordering of a DAG's vertices in which every edge points forward. Used for build systems, scheduling and dependency resolution. + +## Techniques + +**Binary Search on the Answer**: Binary searching over candidate answers rather than over an array, using a yes/no test that is monotone in the answer (for example, "can everything ship in d days with capacity c?"). + +**Fast and Slow Pointers**: Walking two pointers through a sequence at different speeds. Finds the middle of a linked list in one pass, and detects cycles (Floyd's algorithm). + +**Half-Open Interval**: A range written [lo, hi) that includes lo and excludes hi. Using it consistently is the easiest way to write a correct binary search. + +**Lazy Deletion**: Leaving stale entries in a structure and skipping them when they surface, instead of removing them immediately. The usual way to get decrease-key behaviour from Python's heapq. + +**Lower Bound / Upper Bound**: In a sorted array, the first position whose value is ≥ x and the first whose value is > x. Python's bisect_left and bisect_right. + +**Monotonic Stack**: A stack kept in increasing or decreasing order by popping everything that would break the order before each push. Finds the next greater or smaller element for every position in O(n) total. + +**Prefix Sum**: An array whose i-th entry is the sum of the first i input values, making any range sum a single subtraction. The inverse of a difference array. + +**Sliding Window**: Maintaining an answer over a contiguous window as one end advances, so each element enters and leaves once and the whole scan is O(n). + +**Two Pointers**: Moving two indices through a sorted array (often from both ends) so that each step rules out a candidate, giving O(n) instead of O(n²). diff --git a/src/appendices/appendix-d-network-and-system-design-quick-reference.md b/src/appendices/appendix-d-network-and-system-design-quick-reference.md index 26dd472..7d8cebf 100644 --- a/src/appendices/appendix-d-network-and-system-design-quick-reference.md +++ b/src/appendices/appendix-d-network-and-system-design-quick-reference.md @@ -12,7 +12,7 @@ ## D.2 CAP and PACELC -CAP says that **when a network partition occurs**, a distributed system must sacrifice either consistency or availability. Partitions are not optional (they are a fact of networks)so the real choice is only ever between CP and AP: +CAP says that **when a network partition occurs**, a distributed system must sacrifice either consistency or availability. Partitions are not optional (they are a fact of networks) so the real choice is only ever between CP and AP: | Choice | During a partition | Example | |--------|-------------------|---------| diff --git a/src/images/piece-table.svg b/src/images/piece-table.svg new file mode 100644 index 0000000..adb363b --- /dev/null +++ b/src/images/piece-table.svg @@ -0,0 +1,95 @@ + + + Original buffer (read-only: the file as loaded) + t0 + h1 + e2 + ␣3 + f4 + o5 + x6 + ␣7 + j8 + u9 + m10 + p11 + e12 + d13 + + + + "ed" was deleted, but the + bytes stay: no piece points here + Pieces, in text order: + (buffer, start, length) + (orig, 0, 4) + (add, 0, 12) + (orig, 4, 8) + (add, 12, 1) + Add buffer (append-only: everything ever typed) + q0 + u1 + i2 + c3 + k4 + ␣5 + b6 + r7 + o8 + w9 + n10 + ␣11 + s12 + + + + + + + + + + + Text: + + t + h + e + ␣ + + q + u + i + c + k + ␣ + b + r + o + w + n + ␣ + + f + o + x + ␣ + j + u + m + p + + s + diff --git a/src/images/posting-list-compression.svg b/src/images/posting-list-compression.svg new file mode 100644 index 0000000..808e13e --- /dev/null +++ b/src/images/posting-list-compression.svg @@ -0,0 +1,74 @@ + + + One posting list, from doc IDs to bytes + + term + "data" + the term dictionary points to the term's posting list + + + doc IDs + 70000 + 70003 + 70010 + 70130 + 90000 + as int32: + 20 bytes + + + subtract the previous ID + + d-gaps + 70000 + 3 + 7 + 120 + 19870 + mostly + small + + + 7 data bits per byte, low-order group first + + varint bytes + F0 + A2 + 04 + 03 + 07 + 78 + 9E + 9B + 01 + 9 bytes + high bit 1: more bytes follow + high bit 0: last byte of this number + + Zoom: the gap 70000 is 100 0100010 1110000 in binary + 7-bit groups + 0000100 + 0100010 + 1110000 + + + + bytes out + 11110000 F0 + 10100010 A2 + 00000100 04 + The lowest group + goes out first. + Each byte gets a + continuation flag. + diff --git a/src/images/veb-tree.svg b/src/images/veb-tree.svg new file mode 100644 index 0000000..d18055f --- /dev/null +++ b/src/images/veb-tree.svg @@ -0,0 +1,95 @@ + + + + + V (u = 16) + min = 2, max = 15 + 2 is stored only here, + not in cluster 0 + + + + + + + + summary + + + + + 0123 + nonempty clusters + + + cluster 0 + min 3, max 3 + holds low 3 + + cluster 1 + empty: no entry + in the hash table + + cluster 2 + min 1, max 1 + holds low 1 + + cluster 3 + min 1, max 3 + holds lows 1, 2, 3 + + 1 + 2 + 3 + + + + + + + keys 0 to 15, + grouped by high(x) + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + low 0123 + high 0high 1high 2high 3 + + x = 9 = 10 01 in binary: high(9) = 2 picks the cluster, low(9) = 1 is the position inside it. + successor(9): + 1 + cluster 2 has max 1 = low(9): nothing larger in this cluster. + 2 + summary.successor(2) = 3: the next nonempty cluster (one recursive call, on u = 4). + 3 + cluster 3's min is 1, read in O(1): the answer is 3 · 4 + 1 = 13. + diff --git a/src/index.md b/src/index.md index 5e48a34..b3c16e4 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 · ~155,000 words · 225 exercises with worked solutions · Python, C, C++, Java, and Go +Five volumes · 31 chapters · 4 appendices · ~185,000 words · 241 exercises with worked solutions · Python, C, C++, Java, and Go By **Ngoc Anh Khoa Doan**, with the editorial help of Claude. 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 2ddecc2..aebdb67 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 @@ -102,12 +102,12 @@ The signature of O(1) is "doesn't depend on n." Whether you have 10 elements or **Logarithmic Time: O(log n)** - Binary search in sorted array - Balanced tree operations (BST, AVL, Red-Black, B-Tree) -- Skip list operations -- Binary search in balanced tree -- van Emde Boas tree operations +- Skip list operations (expected, not worst case) Logarithmic growth is remarkably slow. Even at n = 1 billion, log₂(n) ≈ 30. This means an O(log n) operation takes at most about 30 steps for a billion elements. +O(log n) is the floor for comparison-based search, but not for every kind of search. When keys are integers below some bound u, a van Emde Boas tree answers predecessor queries in O(log log u), about 5 steps for 32-bit keys, by exploiting the bits of the key rather than comparing whole keys ([Chapter 24](../volume-4/ch24-research-grade-data-structures.md)). + **Linear Time: O(n)** - Sequential scan of array - Linked list traversal 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 3194505..13c4acb 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 @@ -175,6 +175,136 @@ if (bits[i / 8] & (1 << (i % 8))) { ... } **Networking**: IP packet filters, routing tables **Database**: Bitmap indexes +### Compressed Bitmaps + +A bitmap pays one bit for every value that *could* be in the set, whether or not it is. For n values from a universe of size U, that is U bits, against 32n bits for a sorted array of 32-bit integers, so the plain bitmap is smaller only when n > U/32: more than about 3% of the universe present. Bitmap indexes hit this constantly. A column of 10 million rows with 10,000 distinct values needs one 10-million-bit (1.25 MB) bitmap per value, 12.5 GB in all, to record what sorted arrays of row IDs store in 40 MB (10 million IDs, 4 bytes each). Yet bitmaps are worth keeping, because intersecting or uniting two of them is a loop of word-wide ANDs and ORs, 64 elements per instruction, and counting the result is a popcount per word. Compressed bitmaps try to keep that speed while paying space only where values actually are. + +**Run-length encoding.** A sparse bitmap is mostly long runs of zero words (and clustered data also produces runs of one words). Word-aligned schemes replace each run with a single counter word and keep every other word as a literal copy, so logical operations still work a machine word at a time. WAH (Word-Aligned Hybrid) cuts the bitmap into 31-bit groups and stores each 32-bit word as either a *literal*, a flag bit plus 31 bitmap bits, or a *fill*, a flag bit, the fill value (0 or 1), and how many consecutive all-0 or all-1 groups it stands for. EWAH (Enhanced WAH) works on 64-bit words and uses a marker word meaning "k clean words of 0s (or of 1s), then m literal words". To AND two such bitmaps, walk both in step and skip a whole run at once, so the cost is proportional to the compressed sizes rather than to U. The weakness is random access: there is no way to find bit i without decoding from the start, so a single membership test is O(compressed size). Git stores its reachability bitmaps (which objects each commit can reach, in pack order) in EWAH. + +**Roaring bitmaps** keep fast random access by partitioning instead of run-length encoding. For a 32-bit value x, the high 16 bits (`x >> 16`) pick a *chunk* of 65,536 consecutive values, and the low 16 bits (`x & 0xFFFF`) are stored in that chunk's *container*. The top level is a sorted array of the chunk numbers present, each paired with its container; empty chunks cost nothing. Each container chooses its own representation: + +| Container | Contents | Size | Used when | +|-----------|----------|------|-----------| +| Array | sorted 16-bit low halves | 2 bytes per value | at most 4096 values | +| Bitmap | 65,536 bits | 8 KB, fixed | more than 4096 values | +| Run | sorted (start, length − 1) pairs | 4 bytes per run | the values form few runs and this is smallest | + +The threshold of 4096 is where the two basic containers cost the same: 4096 values × 2 bytes = 8192 bytes = 8 KB, which is exactly a 65,536-bit bitmap. Below it the array is smaller, above it the bitmap is, so the rule simply picks the smaller one, and a container is converted when an insertion or deletion crosses the line. As a result no container uses more than 16 bits per value: an array container uses exactly 16, and a bitmap container spreads 65,536 bits over more than 4096 values. Run containers were added later for data with long runs, such as sorted columns; libraries switch a container to runs when that is smallest, typically when asked to optimize (`runOptimize()` in the Java library). + +Operations follow the two levels: + +- **Membership:** binary search the top level for the high half (at most 65,536 keys, so about 16 probes), then binary search an array container, test one bit in a bitmap container, or binary search the run starts. Both levels are bounded, so this is effectively O(1), and unlike EWAH no decoding from the start is needed. +- **Insertion** into an array container shifts up to 4095 entries, and the 4097th value converts it to a bitmap. That bounded shift is the price of the sorted array. +- **Intersection:** merge the two sorted top-level arrays; only chunks present in both can contribute. Then intersect container pairs. Two bitmaps: 1024 64-bit ANDs, with popcount giving the result's size, and the result becomes an array if it holds 4096 values or fewer. Array and bitmap: test each array value against the bitmap, O(size of the array), and the result is an array. Two arrays: merge them, or use galloping (exponential) search when one is much smaller. Real libraries have routines for run containers too, and use SIMD instructions for the bitmap and array cases. + +The cost of an intersection therefore depends on the sizes of the containers involved, never on U, and the dense parts are processed a word at a time. Here is a model in Python, with a Python `int` standing in for the 65,536-bit bitmap: + +```python +from bisect import bisect_left + +ARRAY_MAX = 4096 # 4096 values x 2 bytes = 8 KB = one 65,536-bit bitmap + + +def runs_of(lows): + """Sorted distinct 16-bit values -> list of (start, length - 1) runs.""" + runs = [] + for v in lows: + if runs and runs[-1][0] + runs[-1][1] + 1 == v: + runs[-1] = (runs[-1][0], runs[-1][1] + 1) + else: + runs.append((v, 0)) + return runs + + +def make_container(lows): + """Pick the smallest representation for one chunk's sorted low halves.""" + runs = runs_of(lows) + sizes = {"array": 2 * len(lows), "bitmap": 8192, "run": 4 * len(runs)} + if len(lows) > ARRAY_MAX: + del sizes["array"] # an array container never passes 8 KB + kind = min(sizes, key=sizes.get) # ties go to the first: array, then bitmap + if kind == "array": + return kind, list(lows) + if kind == "run": + return kind, runs + bits = 0 + for v in lows: + bits |= 1 << v + return kind, bits + + +def values(container): + kind, data = container + if kind == "array": + return data + if kind == "run": + return [v for s, l in data for v in range(s, s + l + 1)] + return [v for v in range(65536) if data >> v & 1] + + +def contains(container, low): + kind, data = container + if kind == "array": + i = bisect_left(data, low) + return i < len(data) and data[i] == low + if kind == "bitmap": + return data >> low & 1 == 1 + i = bisect_left(data, (low + 1, 0)) - 1 # last run starting at or before low + return i >= 0 and low <= data[i][0] + data[i][1] + + +class Roaring: + def __init__(self, xs=()): + chunks = {} + for x in sorted(set(xs)): + chunks.setdefault(x >> 16, []).append(x & 0xFFFF) + self.chunks = {hi: make_container(lows) for hi, lows in chunks.items()} + + def __contains__(self, x): + c = self.chunks.get(x >> 16) + return c is not None and contains(c, x & 0xFFFF) + + def __iter__(self): + for hi in sorted(self.chunks): + for low in values(self.chunks[hi]): + yield hi << 16 | low + + def __and__(self, other): + out = Roaring() + for hi in self.chunks.keys() & other.chunks.keys(): + (ka, a), (kb, b) = self.chunks[hi], other.chunks[hi] + if ka == kb == "bitmap": + lows = values(("bitmap", a & b)) # 1024 word ANDs in C + elif ka == "array": + lows = [v for v in a if contains((kb, b), v)] + elif kb == "array": + lows = [v for v in b if contains((ka, a), v)] + else: # runs: decode one side + lows = [v for v in values((ka, a)) if contains((kb, b), v)] + if lows: + out.chunks[hi] = make_container(lows) + return out +``` + +A set with three very different chunks: + +```python +s = Roaring([1, 2, 3, 1000, 50000] # chunk 0: 5 scattered values + + list(range(65536 + 100, 65536 + 8100)) # chunk 1: 8000 in a row + + list(range(2 * 65536, 3 * 65536, 3))) # chunk 2: every third value +assert {hi: c[0] for hi, c in s.chunks.items()} == {0: "array", 1: "run", 2: "bitmap"} + +evens = Roaring(range(0, 3 * 65536, 2)) # three half-full bitmaps +both = s & evens +assert {hi: c[0] for hi, c in both.chunks.items()} == {0: "array", 1: "array", 2: "bitmap"} +assert set(both) == set(s) & set(range(0, 3 * 65536, 2)) +assert 65636 in both and 65637 not in both +``` + +`s` holds 29,851 values. Chunk 0 becomes an array container of 10 bytes, chunk 1 a single run of 4 bytes (an array would be 16,000 bytes, a bitmap 8 KB), and chunk 2, with 21,846 values, a bitmap of 8 KB: about 8.2 KB in total. A sorted array of 32-bit integers would take 119,404 bytes, and a plain bitmap over all 32-bit values 512 MB. In the intersection with `evens` (all bitmaps), chunk 0 is array ∧ bitmap and keeps 3 values; chunk 1 is run ∧ bitmap and keeps 4000 values, few enough to fall back to an array container; chunk 2 is bitmap ∧ bitmap and keeps the 10,923 multiples of 6, so it stays a bitmap. + +In its authors' benchmarks Roaring is usually faster than WAH and EWAH, and often smaller, and it has become the default compressed bitmap. Apache Lucene's `RoaringDocIdSet` (and so Elasticsearch and OpenSearch), the bitmap indexes of Apache Druid and Apache Pinot, ClickHouse's bitmap functions, and Spark's tracking of empty shuffle blocks all use it. Delta Lake and Apache Iceberg store deletion vectors, the positions of deleted rows in a data file, as 64-bit Roaring bitmaps, which apply the same high/low split one level up: the high 32 bits select an ordinary 32-bit Roaring bitmap. + ## 3.6 Array Variants for Specific Purposes ### Circular Buffers @@ -504,6 +634,8 @@ The dynamic array (vector) concept emerged with languages supporting heap alloca Binary search was first described by John Mauchly in the 1946 Moore School Lectures, but according to Knuth (*The Art of Computer Programming*, Vol. 3) the published versions worked only for some array lengths until D. H. Lehmer's in 1960. Getting it right stayed hard: Joshua Bloch's 2006 report of the `(low + high) / 2` overflow covered both the JDK and *Programming Pearls*. Two-dimensional prefix sums entered graphics as Franklin Crow's summed-area tables (1984) and computer vision as the integral images of Paul Viola and Michael Jones's face detector (2001). +Compressed bitmaps grew out of bitmap indexes. Gennady Antoshenkov's Byte-aligned Bitmap Code (1995) was used in Oracle; Kesheng Wu, Ekow Otoo and Arie Shoshani's WAH (journal version 2006) aligned the runs to machine words; Daniel Lemire, Owen Kaser and Kamel Aouiche's EWAH (2010) moved to 64-bit words. Roaring was introduced by Samy Chambi, Daniel Lemire, Owen Kaser and Robert Godin in 2016, and run containers were added in a follow-up paper by Lemire, Gregory Ssi-Yan-Kai and Kaser the same year. + ## Exercises Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch. @@ -874,6 +1006,55 @@ In C, two lines overflow. `mid * mid` exceeds 2⁶³ − 1 once mid > about 3.04 +**3.10 ★ Choosing containers.** Using the Roaring rules of Section 3.5, give the chunks, the container type of each, and the total container size for each set below. Compare with a sorted array of 32-bit integers. + +(a) The 5000 even numbers 0, 2, 4, ..., 9998. + +(b) The 100,000 consecutive values 0, 1, ..., 99,999. + +(c) The 1000 values 0, 65,536, 2 × 65,536, ..., 999 × 65,536. + +
+Solution + +**(a)** All values are below 65,536, so there is one chunk (high half 0) with 5000 values. That is more than 4096, so an array container is ruled out (it would need 10,000 bytes, more than a bitmap). No two values are consecutive, so a run container needs 5000 runs, 20,000 bytes. The bitmap container wins at **8192 bytes**, about 13 bits per value, against 20,000 bytes for the sorted array. + +**(b)** Two chunks. Chunk 0 is full (0 to 65,535): one run, 4 bytes, against 8192 for a bitmap. Chunk 1 holds 65,536 to 99,999, low halves 0 to 34,463: again one run, 4 bytes. Total **8 bytes** of containers, against 400,000 bytes for the array. A plain bitmap or an array container could not get close; this is what run containers are for. + +**(c)** 1000 chunks, each holding a single value with low half 0, so 1000 array containers of 2 bytes each. The containers total only 2000 bytes, but every chunk also needs its 2-byte key in the top level, plus a pointer (in memory) or an offset and a cardinality (on disk). That is already 4 bytes per value (2 for the key, 2 for the container) before counting any pointer, offset or cardinality, as much as the 4000-byte sorted array, so here Roaring **loses**. Its 16-bits-per-value guarantee holds inside containers; when every chunk holds one value, the top level dominates. + +```python +r = Roaring(range(0, 10000, 2)) +assert [c[0] for c in r.chunks.values()] == ["bitmap"] +r = Roaring(range(100000)) +assert {hi: c for hi, c in r.chunks.items()} == {0: ("run", [(0, 65535)]), + 1: ("run", [(0, 34463)])} +r = Roaring(x * 65536 for x in range(1000)) +assert len(r.chunks) == 1000 and all(c == ("array", [0]) for c in r.chunks.values()) +``` + +
+ +**3.11 ★★ Roaring on random data.** n distinct 32-bit integers are drawn uniformly at random. Estimate the size of a Roaring bitmap for n = 10⁶ and for n = 10⁹, and compare each with a sorted array of 32-bit integers and with a plain bitmap of 2³² bits. Count 8 bytes of overhead per container, as Roaring's standard serialized format does (a 2-byte key, a 2-byte cardinality and a 4-byte offset). At what n do the containers switch from arrays to bitmaps? + +
+Hint + +There are 65,536 chunks, and with uniform data each gets about n / 65,536 values. + +
+ +
+Solution + +**n = 10⁶.** Each chunk gets about 10⁶ / 65,536 ≈ 15 values, so practically every chunk is non-empty (the chance that one is empty is about e⁻¹⁵) and every container is an array. Containers: 10⁶ × 2 bytes = 2 MB. Overhead: 65,536 × 8 bytes = 512 KB. Total about **2.5 MB**, against 4 MB for the sorted array and 512 MB for the plain bitmap. Random data has no runs and no dense regions, so the saving over the sorted array comes only from not repeating the high half, which every value in a chunk shares. + +**n = 10⁹.** Each chunk gets about 15,259 values, more than 4096, so every container is an 8 KB bitmap: 65,536 × 8 KB = **512 MB** plus 512 KB of overhead, the same as the plain bitmap (which is the right representation at this density), against 4 GB for the sorted array. + +**The switch** happens when a chunk's expected count crosses 4096, a density of 4096 / 65,536 = 1/16, so at about n = 2³² / 16 ≈ 2.7 × 10⁸. Below that Roaring costs about 16 bits per value plus overhead; above it, a fixed 512 MB. Either way it is never far from the better of the sorted array and the plain bitmap, which is the point of choosing the container per chunk. + +
+ --- ## Where this connects 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 32d8efc..0d9dd92 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 @@ -365,6 +365,7 @@ int pop_back(Deque *d); **Applications:** - Implementing both stacks and queues +- Sliding window maximum and minimum (Section 5.9) - Palindrome checking - A-Steal algorithm (parallel task scheduling) - Text editor undo/redo (two deques) @@ -453,7 +454,176 @@ threading.Thread(target=producer, args=(queue,)).start() threading.Thread(target=consumer, args=(queue,)).start() ``` -## 5.9 Historical Context +## 5.9 Monotonic Stacks and Queues + +A monotonic stack is an ordinary stack with one extra rule: before pushing x, pop every element on top that would break sorted order. The contents stay sorted, but that is a side effect. What matters is the pops: when x pops an element, x is the answer to a question about that element, such as "what is the first larger value to my right?" Any problem that asks, for every position, about the nearest larger or smaller element falls to this pattern in O(n). + +### Next Greater Element + +For each index i, find the first j > i with a[j] > a[i], or −1 if there is none. Scanning forward from every i is O(n²) in the worst case (a decreasing array, where every scan runs to the end). + +Instead, scan left to right and keep on a stack the indices that have not found their answer yet. + +**Invariant:** the values at the stacked indices are non-increasing from bottom to top. A smaller value cannot sit below a larger one that came after it, because the larger one would have answered it and popped it on arrival. + +When x = a[j] arrives, the waiting elements it answers are exactly those with values smaller than x, and the invariant puts all of them at the top. Pop them, record j for each, then push j. Everything left below j is ≥ x, so the invariant still holds. + +```python +def next_greater(a): + """ans[i] = index of the first j > i with a[j] > a[i], or -1 if none.""" + ans = [-1] * len(a) + stack = [] # indices still waiting for an answer + for j, x in enumerate(a): + while stack and a[stack[-1]] < x: + ans[stack.pop()] = j # x is the first larger value after it + stack.append(j) + return ans + + +assert next_greater([2, 7, 3, 5, 4, 6, 8]) == [1, 6, 3, 5, 5, 6, -1] +``` + +Trace on `a = [2, 7, 3, 5, 4, 6, 8]`, with the stack shown as values: + +| j | a[j] | Popped (index: value), answered by j | Stack after | +|---|------|--------------------------------------|-------------| +| 0 | 2 | | [2] | +| 1 | 7 | 0: 2 | [7] | +| 2 | 3 | | [7, 3] | +| 3 | 5 | 2: 3 | [7, 5] | +| 4 | 4 | | [7, 5, 4] | +| 5 | 6 | 4: 4, then 3: 5 | [7, 6] | +| 6 | 8 | 5: 6, then 1: 7 | [8] | + +The next greater values are 7, 8, 5, 6, 6, 8 and none. Whatever is still on the stack when the scan ends (here the 8) has no greater element to its right. + +The same loop answers related questions. Flipping the comparison gives the next *smaller* element. After the pops at step j, the new top of the stack is the nearest earlier element that is ≥ x, so one pass also yields every element's *previous* greater-or-equal element; stock span below uses exactly that. With duplicate values, decide deliberately whether equal elements pop (`<=`) or stay (`<`). It changes the answers, and Exercise 5.8 is a problem where getting it wrong double-counts. + +### Why It Is O(n): Amortized Analysis Again + +A single step can pop many elements. Step 6 above pops two, and on `[5, 4, 3, 2, 1, 9]` the last step pops five, so one step is O(n) in the worst case. But each index is pushed exactly once and popped at most once, so the `while` loop runs at most n times over the whole scan. The total is O(n) in the worst case, which is amortized O(1) per element: the aggregate method of Section 1.5 ([Chapter 1](ch01-the-philosophy-and-mathematics-of-data-structures.md)). + +The potential method makes the bookkeeping explicit. Let Φ be the number of elements on the stack: it starts at 0 and is never negative. A step that pops k elements and pushes one does k + 1 units of real work and changes Φ by 1 − k, so its amortized cost is (k + 1) + (1 − k) = 2, whatever k is. Each push prepays its own future pop. The dynamic array ([Chapter 3](ch03-arrays-the-foundation-of-contiguous-storage.md), Section 3.4) and the queue built from two stacks (Exercise 5.5) are paid for the same way: every element is moved a constant number of times over its lifetime, however those moves bunch together. + +### Stock Span + +The span of a stock's price on day i is the number of consecutive days, ending with day i, on which the price was at most the price on day i. It equals i minus the index of the most recent earlier day with a strictly higher price. That is the "previous greater" variant, and it works online: each span is known as soon as that day's price arrives. + +```python +def stock_spans(prices): + """span[i] = number of consecutive days ending at day i with price <= prices[i].""" + spans = [] + stack = [] # indices; prices strictly decreasing + for i, p in enumerate(prices): + while stack and prices[stack[-1]] <= p: + stack.pop() # can never stop a later span that p doesn't + spans.append(i - stack[-1] if stack else i + 1) + stack.append(i) + return spans + + +assert stock_spans([100, 80, 60, 70, 60, 75, 85]) == [1, 1, 1, 2, 1, 4, 6] +``` + +On day 5 (price 75) the stack holds the prices 100, 80, 70, 60. The 60 and the 70 are popped, 80 at index 1 is left on top, and the span is 5 − 1 = 4 (days 2 to 5: 60, 70, 60, 75). Day 2's 60 is not on the stack at all: day 3's 70 popped it, and rightly so, because any later price that 60 would stop, 70 stops too, and 70 is nearer. + +### Largest Rectangle in a Histogram + +Bars of width 1 and heights h[0], ..., h[n − 1] stand side by side. Find the area of the largest axis-aligned rectangle that fits under them. Trying every start and extending to the right while tracking the minimum height is O(n²). + +The largest rectangle is as tall as its shortest bar, say bar i, and at that height it extends as far as it can: left until the nearest bar lower than h[i], right until the nearest bar lower than h[i]. So the answer is the maximum over i of h[i] × (right − left − 1), where left and right are the indices of those two lower bars (−1 and n when there is none). A single monotonic stack pass finds both for every bar. Keep indices whose heights are strictly increasing from bottom to top. When bar j pops bar i, j is the first bar to the right of i that is not taller than h[i], and the index just below i on the stack is the nearest bar to the left that is strictly lower (everything that stood between them was popped by i or by something that i later popped, so it was at least as tall as h[i]). + +```python +def largest_rectangle(h): + """Area of the largest rectangle under a histogram of bar heights h.""" + best = 0 + stack = [] # indices; heights strictly increasing + for j, x in enumerate(h + [0]): # a height-0 bar at the end flushes the stack + while stack and h[stack[-1]] >= x: + i = stack.pop() # bar j is the first one right of i not taller than h[i] + left = stack[-1] if stack else -1 # nearest bar left of i lower than h[i] + best = max(best, h[i] * (j - left - 1)) + stack.append(j) + return best + + +assert largest_rectangle([2, 1, 5, 6, 2, 3]) == 10 +``` + +Equal heights need one remark. With `>=`, a bar is popped by the next bar of the same height, so its rectangle is cut short at that bar. Nothing is lost: the later bar has the same height, inherits the same left boundary (the index below), and computes the full rectangle when it is popped in turn. + +Trace on `h = [2, 1, 5, 6, 2, 3]`: + +| j | h[j] | Popped bar i (height): left, width, area | Stack after (heights) | Best | +|---|------|------------------------------------------|-----------------------|------| +| 0 | 2 | | [2] | 0 | +| 1 | 1 | 0 (2): left −1, width 1, area 2 | [1] | 2 | +| 2 | 5 | | [1, 5] | 2 | +| 3 | 6 | | [1, 5, 6] | 2 | +| 4 | 2 | 3 (6): left 2, width 1, area 6; 2 (5): left 1, width 2, area 10 | [1, 2] | 10 | +| 5 | 3 | | [1, 2, 3] | 10 | +| 6 | 0 (sentinel) | 5 (3): left 4, width 1, area 3; 4 (2): left 1, width 4, area 8; 1 (1): left −1, width 6, area 6 | [0] | 10 | + +The answer is the 5 × 2 rectangle over bars 2 and 3. Each bar is pushed once and popped once, so the pass is O(n) in the worst case with O(n) extra space. The same pass applied row by row finds the largest all-1 rectangle in a 0/1 matrix (Exercise 5.9), and the same stack builds a Cartesian tree in O(n) ([Chapter 23](../volume-4/ch23-advanced-competitive-programming-data-structures.md)). + +### Monotonic Deque: Sliding Window Maximum + +Given an array `a` and a window size k, output the maximum of every window `a[i : i + k]`. Recomputing each window is O(nk). A heap (Chapter 9) with lazy deletion of expired entries gets O(n log n). A monotonic deque gets O(n). + +A stack is not enough here, because elements also leave the window at the old end. A deque (Section 5.6) provides both ends: the back behaves exactly like a monotonic stack, and the front lets expired indices out. + +**Invariant:** the deque holds indices in increasing order, oldest at the front, and their values are strictly decreasing from front to back. These are exactly the elements that could still be the maximum of the current window or a later one. An element is useless as soon as a newer element at least as large arrives, because the newer one stays in every future window the older one is in. The front is therefore the maximum of the current window. + +For each new index i: + +1. Pop from the back every index whose value is ≤ `a[i]`. +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 on `a = [1, 3, -1, -3, 5, 3, 6, 7]` with k = 3 (deque shown as values): + +| i | a[i] | Deque after step | Output | +|---|------|------------------|--------| +| 0 | 1 | [1] | | +| 1 | 3 | [3] | | +| 2 | −1 | [3, −1] | 3 | +| 3 | −3 | [3, −1, −3] | 3 | +| 4 | 5 | [5] | 5 | +| 5 | 3 | [5, 3] | 5 | +| 6 | 6 | [6] | 6 | +| 7 | 7 | [7] | 7 | + +At i = 4 the front, 3 at index 1, has just expired, but the 5 had already cleared the whole deque from the back. Expiry from the front only matters when the maximum is old and nothing larger has arrived since: on `[5, 4, 3, 2, 1]` with k = 2, every step from i = 2 on pops the front. + +**Why O(n):** each index is pushed onto the deque once and popped at most once, from one end or the other, so all the `while` loops together do at most n pops, and every deque operation is O(1). At most one front pop is needed per step, because the window advances one index at a time. The bound is O(n) worst case for the whole array and amortized O(1) per element, by the same potential argument as for the stack. Reversing the comparison gives the sliding window minimum. The pattern turns up wherever a rolling maximum or minimum is needed over a stream, and in the dynamic-programming optimization that [Chapter 21](../volume-3/ch21-algorithm-design-using-data-structures.md) calls the monotonic deque. Exercise 5.7 runs a maximum deque and a minimum deque together inside the variable-size sliding window of Chapter 3. + +The test for whether a problem fits: the brute force, for each position, scans outward until it meets something larger (or smaller), and once an element is beaten by a nearer one it can never be the answer for anything further away. Then a monotonic stack does the whole job in one pass, or a monotonic deque if old elements must also expire. + +## 5.10 Historical Context The stack and queue concepts emerged in the 1950s as programmers recognized common access patterns. Alan Turing's 1949 work on subroutine linkage predated formal stack concepts, the call stack was an informal but essential mechanism. @@ -461,6 +631,8 @@ 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. +Robert Hood and Robert Melville (1981) showed how to make the two-stack queue of Exercise 5.5 run in O(1) worst-case time per operation in pure Lisp, by spreading the reversal over many operations instead of doing it all at once. The problem a monotonic stack solves, finding for every element the nearest smaller value on each side, was named "all nearest smaller values" by Omer Berkman, Baruch Schieber and Uzi Vishkin (1993), who used it as a building block for fast parallel algorithms; the sequential stack algorithm was already standard by then. + ## Exercises Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch. @@ -698,66 +870,152 @@ The redo stack needs no cap: it can never hold more than the undo history did, a -**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. +**5.7 ★★★ Longest run with bounded spread.** Given an array `a` and a number `limit` ≥ 0, find the length of the longest contiguous run `a[lo : hi + 1]` whose maximum minus minimum is at most `limit`, in O(n). For example, `a = [10, 1, 2, 4, 7, 2]` with limit 5 gives 4, for the run `[2, 4, 7, 2]`. + +
+Hint + +Combine the variable-size sliding window of [Chapter 3](ch03-arrays-the-foundation-of-contiguous-storage.md) (Section 3.7) with the monotonic deque of Section 5.9. The window needs both its maximum and its minimum. + +
+ +
+Solution + +**Why a sliding window works.** Shrinking a run cannot increase its spread and growing it cannot decrease it. So for each right end `hi` the valid left ends form a range ending at `hi`, and the smallest valid left end never moves left as `hi` grows. That is the same monotonicity `shortest_at_least` relies on in Chapter 3: grow on the right, and shrink from the left only while the window is invalid. + +**Maintaining max and min.** Keep two monotonic deques of indices: `maxq` with values strictly decreasing (its front is the window maximum, exactly as in `window_max`) and `minq` with values strictly increasing (its front is the minimum). When `lo` advances past a deque's front index, pop that front. + +```python +from collections import deque + + +def longest_bounded(a, limit): + """Length of the longest run a[lo:hi+1] with max - min <= limit.""" + maxq, minq = deque(), deque() # indices; values decreasing / increasing + best = lo = 0 + for hi, x in enumerate(a): + while maxq and a[maxq[-1]] <= x: + maxq.pop() + maxq.append(hi) + while minq and a[minq[-1]] >= x: + minq.pop() + minq.append(hi) + while a[maxq[0]] - a[minq[0]] > limit: # shrink from the left + lo += 1 + if maxq[0] < lo: + maxq.popleft() + if minq[0] < lo: + minq.popleft() + best = max(best, hi - lo + 1) + return best + + +assert longest_bounded([10, 1, 2, 4, 7, 2], 5) == 4 +assert longest_bounded([8, 2, 4, 7], 4) == 2 +assert longest_bounded([], 3) == 0 +``` + +The shrink loop never empties a deque: both always contain `hi`, and once `lo` reaches `hi` the spread is 0. -For example, `a = [1, 3, -1, -3, 5, 3, 6, 7]` and k = 3 gives `[3, 3, 5, 5, 6, 7]`. +Trace for the example (deques shown as values): + +| hi | a[hi] | maxq | minq | lo | best | +|----|-------|------|------|----|------| +| 0 | 10 | [10] | [10] | 0 | 1 | +| 1 | 1 | [1] | [1] | 1 | 1 | +| 2 | 2 | [2] | [1, 2] | 1 | 2 | +| 3 | 4 | [4] | [1, 2, 4] | 1 | 3 | +| 4 | 7 | [7] | [2, 4, 7] | 2 | 3 | +| 5 | 2 | [7, 2] | [2] | 2 | 4 | + +At hi = 1 the spread 10 − 1 = 9 is too large, so `lo` moves to 1 and the 10 leaves `maxq`. At hi = 4 the spread 7 − 1 = 6 is too large, so `lo` moves to 2 and the 1 leaves `minq`. + +**Cost.** Each index enters and leaves each deque at most once, and `lo` advances at most n times in total, so the whole run is O(n) in the worst case, amortized O(1) per element. A brute force over all O(n²) runs, each scanned for its spread, is O(n³). + +
+ +**5.8 ★★ Sum of subarray minimums.** The array `[3, 1, 2, 4]` has 10 contiguous subarrays, and the sum of their minimums is 17. Compute this sum for any array in O(n). Be careful with duplicate values: check your method on `[2, 2]`, whose answer is 6.
Hint -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. +Turn it around: for each i, count the subarrays whose minimum is `a[i]`. They can stretch left and right until they meet a smaller value.
Solution -Keep a deque of indices whose values are strictly decreasing from front to back. The front is always the maximum of the current window. +Let `left[i]` be the nearest index before i with a smaller value (or −1) and `right[i]` the nearest index after i with a smaller value (or n). Then `a[i]` is the minimum of every subarray `a[l : r + 1]` with `left[i] < l ≤ i ≤ r < right[i]`, and there are `(i − left[i]) × (right[i] − i)` of them. The answer is the sum of `a[i]` times that count. -For each new index i: +**Duplicates.** If both boundaries stop only at strictly smaller values, a subarray whose minimum appears twice is counted once for each copy. On `[2, 2]` that gives 2 × 1 × 2 + 2 × 2 × 1 = 8, because `[2, 2]` is counted twice. The fix is to make one side non-strict: `left[i]` stops at a value < `a[i]`, but `right[i]` stops at a value ≤ `a[i]`. Each subarray is then credited to the rightmost position of its minimum only, and `[2, 2]` gives 2 × 1 × 1 + 2 × 2 × 1 = 6. -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]`. +One monotonic stack pass computes both arrays: when j pops i (because `a[i] ≥ a[j]`), j is i's next index with a value ≤ `a[i]`; after the pops, the top of the stack is j's previous index with a strictly smaller value. ```python -from collections import deque +def sum_subarray_mins(a): + n = len(a) + left, right = [-1] * n, [n] * n + stack = [] # indices; values strictly increasing + for j, x in enumerate(a): + while stack and a[stack[-1]] >= x: # j is the next index with a value <= a[i] + right[stack.pop()] = j + left[j] = stack[-1] if stack else -1 # last index with a value < a[j] + stack.append(j) + return sum(a[i] * (i - left[i]) * (right[i] - i) for i in range(n)) + + +assert sum_subarray_mins([3, 1, 2, 4]) == 17 +assert sum_subarray_mins([2, 2]) == 6 +``` +For `[3, 1, 2, 4]`: `left = [-1, -1, 1, 2]` and `right = [1, 4, 4, 4]`, so the contributions are 3 × 1 × 1 = 3, 1 × 2 × 3 = 6, 2 × 1 × 2 = 4 and 4 × 1 × 1 = 4, which sum to 17. The pass is O(n) worst case by the argument of Section 5.9; summing the minimums of all O(n²) subarrays directly, extending each start to the right while tracking the minimum, is O(n²). -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 +
+**5.9 ★★ Largest rectangle of 1s.** Given a 0/1 matrix with R rows and C columns, find the area of the largest rectangle that contains only 1s, in O(RC) time. Apply it to: -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] +``` +1 0 1 0 0 +1 0 1 1 1 +1 1 1 1 1 +1 0 0 1 0 ``` -Trace of the example (deque shown as values): +
+Hint -| 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 | +Fix the row that the rectangle's bottom edge sits on. What does the matrix above that row look like, column by column? + +
+ +
+Solution + +For row r, let `heights[c]` be the number of consecutive 1s in column c ending at row r (0 if the cell is 0). An all-1 rectangle whose bottom edge is on row r is exactly a rectangle under the histogram `heights`, so the answer is the largest result of `largest_rectangle` (Section 5.9) over all rows. Each row updates `heights` in O(C) (add 1, or reset to 0) and runs one O(C) histogram pass, for O(RC) in total, with O(C) extra space. + +```python +def maximal_rectangle(grid): + """Area of the largest all-1 rectangle in a 0/1 matrix.""" + if not grid: + return 0 + heights = [0] * len(grid[0]) + best = 0 + for row in grid: + heights = [h + 1 if cell else 0 for h, cell in zip(heights, row)] + best = max(best, largest_rectangle(heights)) + return best +``` + +| Row | heights | Largest rectangle under it | +|-----|---------|----------------------------| +| 0 | [1, 0, 1, 0, 0] | 1 | +| 1 | [2, 0, 2, 1, 1] | 3 | +| 2 | [3, 1, 3, 2, 2] | 6 | +| 3 | [4, 0, 0, 3, 0] | 4 | -**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. +The answer is 6: rows 1 and 2, columns 2 to 4. At row 2 the best histogram rectangle has height 2 and spans the last three bars (heights 3, 2, 2). Checking every rectangle directly would take O(R²C²) candidates, each needing a check of its cells (or O(1) each with the 2-D prefix sums of Chapter 3).
@@ -767,3 +1025,4 @@ Trace of the example (deque shown as values): - [Chapter 9: Heaps and Priority Queues](ch09-heaps-and-priority-queues.md). The priority queue, when FIFO and LIFO are both the wrong order - [Chapter 21: Algorithm Design Using Data Structures](../volume-3/ch21-algorithm-design-using-data-structures.md). The stack as the implicit structure behind all recursion +- [Chapter 23: Advanced Competitive Programming Data Structures](../volume-4/ch23-advanced-competitive-programming-data-structures.md). Cartesian trees, built in O(n) with the monotonic stack of Section 5.9 diff --git a/src/volume-1/index.md b/src/volume-1/index.md index 4b964fb..2f86ea6 100644 --- a/src/volume-1/index.md +++ b/src/volume-1/index.md @@ -17,9 +17,9 @@ The volume moves from the language of cost (Chapter 1) and how memory really wor | 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 | +| [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, and explain how Roaring bitmaps compress sets | | [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 | +| [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, use circular buffers and deques, and solve next-greater and sliding-window problems with monotonic stacks and queues | ## Part 3: Hierarchical Structures and Trees diff --git a/src/volume-2/ch12-hash-tables.md b/src/volume-2/ch12-hash-tables.md index 4d53163..17ad457 100644 --- a/src/volume-2/ch12-hash-tables.md +++ b/src/volume-2/ch12-hash-tables.md @@ -13,11 +13,11 @@ Direct addressing would need 26 slots for letters. Hash table needs fewer slots with good hash function. ``` -The idea is best understood as a compromise between two extremes. **Direct addressing** (one array slot per possible key)gives genuine O(1) access but needs an array the size of the key space, which for 64-bit integers or arbitrary strings is impossible. **A sorted array** needs only n slots but costs O(log n) per lookup. +The idea is best understood as a compromise between two extremes. **Direct addressing** (one array slot per possible key) gives genuine O(1) access but needs an array the size of the key space, which for 64-bit integers or arbitrary strings is impossible. **A sorted array** needs only n slots but costs O(log n) per lookup. A hash table takes the array indexing of the first and the space of the second, and pays for it with **collisions**: squeezing a large key space into m slots guarantees that different keys sometimes land on the same one. Everything difficult about hash tables follows from that single consequence. -Worth being precise about the guarantee, since "O(1) lookup" is repeated so often it stops being examined. It is O(1) *average case*, under the assumption that keys distribute uniformly. The worst case is O(n) (every key colliding)and that worst case is reachable by an adversary who knows your hash function. This is not hypothetical: collision-flooding denial of service against PHP, Java, Python, and Ruby web frameworks was demonstrated in 2011 and forced all of them to change their hashing. +Worth being precise about the guarantee, since "O(1) lookup" is repeated so often it stops being examined. It is O(1) *average case*, under the assumption that keys distribute uniformly. The worst case is O(n) (every key colliding), and that worst case is reachable by an adversary who knows your hash function. This is not hypothetical: collision-flooding denial of service against PHP, Java, Python, and Ruby web frameworks was demonstrated in 2011 and forced all of them to change their hashing or limit their input (Section 12.2). ## 12.2 Hash Functions @@ -89,6 +89,39 @@ The original version of this function used `int` and applied `% m` inside the lo Choose by threat model: keyed hashes for anything reachable by user input, fast unkeyed hashes for internal maps with trusted keys. Rust makes this explicit. The default `HashMap` uses SipHash, and swapping in `FxHashMap` for internal use is often a 2× speedup. +### Hash Flooding + +A web framework parses every POST request into a hash table of form fields before application code runs. If the attacker can choose field names that all have the same hash, n fields cost Θ(n²) comparisons to insert, and the server burns CPU on a request that took milliseconds to send. Crosby and Wallach described these *algorithmic complexity attacks* in 2003. At the 28th Chaos Communication Congress (28C3) in December 2011, Alexander Klink and Julian Wälde showed that the default hash tables in PHP, ASP.NET, Java, Python, Ruby and JavaScript platforms were all exploitable this way. + +Building the colliding keys is easy when the hash is a fixed polynomial. Java's `String.hashCode` computes s₀·31ⁿ⁻¹ + ... + sₙ₋₁, and the two-character strings `"Aa"` and `"BB"` have the same hash (65 · 31 + 97 = 66 · 31 + 66 = 2112). Because the hash of a concatenation depends only on the hashes and lengths of its parts, any string made of k such blocks collides with all 2ᵏ of them: + +```python +from itertools import product + +def java_string_hash(s): + """Java's String.hashCode, reduced to 32 bits.""" + h = 0 + for ch in s: + h = (31 * h + ord(ch)) & 0xFFFFFFFF + return h + +assert java_string_hash("Aa") == java_string_hash("BB") == 2112 +keys = ["".join(blocks) for blocks in product(["Aa", "BB"], repeat=16)] +assert len(keys) == 65536 +assert len({java_string_hash(k) for k in keys}) == 1 # one hash value +``` + +The *full* hash values are equal, so these keys collide for every table size, and resizing does not help. Inserting all 65,536 into a chained table makes about 65,536² / 2 ≈ 2 × 10⁹ key comparisons. + +The responses came in layers: + +- **Limit the input.** PHP added `max_input_vars` (default 1,000 fields) in December 2011. This caps the damage for one entry point and fixes nothing else. +- **Randomize the seed.** Python made a per-process random hash seed the default in 3.3. A random seed alone is not enough if the function has collisions that do not depend on the seed: at 29C3 (2012), Aumasson, Bernstein and Boßlet built seed-independent multicollisions for MurmurHash2, MurmurHash3 and CityHash64, the functions Ruby and others had just adopted as their randomized fix. +- **Use a keyed pseudorandom function.** SipHash (Aumasson and Bernstein, 2012) takes a secret 128-bit key chosen at startup. It is a pseudorandom function: without the key its outputs are unpredictable, so an attacker cannot compute colliding inputs offline, and it is still fast on the short keys hash tables see. Ruby switched to it in 2012, Python in 3.4 (PEP 456), and Rust and Perl use it too. +- **Bound the worst case structurally.** Java 8's tree bins (Section 12.3) turn a flooded chain into a red-black tree, so even a successful attack costs O(log n) per operation instead of O(n). + +The defences compose: Rust uses SipHash with randomly generated keys, and Java uses a predictable hash but caps the damage with trees. + ## 12.3 Collision Resolution
@@ -237,7 +270,291 @@ Four details in that code are the ones people get wrong: That last point has a consequence for latency-sensitive systems: a hash table's *average* insert is O(1), but one insert in every n takes O(n). If tail latency matters, either pre-size the table or use an incremental-resize scheme that migrates a few entries per operation, as Redis does. -## 12.5 Perfect Hashing +## 12.5 Modern Open Addressing + +The table in Section 12.4 is linear probing much as it was implemented in 1954, and it has three weaknesses that show up in production. Probe lengths have a long tail: the average is small but a few unlucky keys sit dozens of slots from home. Unsuccessful searches scan all the way to an empty slot. And every probe compares a full key, which for strings means a memory access and a comparison loop per slot. The two designs that dominate modern libraries attack these directly. Robin Hood hashing fixes the tail and the deletion problem; Swiss tables make each probe so cheap that the tail barely matters. + +### Robin Hood Hashing + +For an entry stored at slot i whose home slot is h = hash(k) mod m, its **probe-sequence length** (PSL) is (i − h) mod m: how many slots past home it sits. A lookup that finds the entry costs PSL + 1 probes. Plain linear probing gives each slot to whichever key arrives first, so a key's PSL depends on luck. + +Robin Hood hashing (Celis, 1985) changes one rule. Insertion walks forward from home, tracking the PSL d the new entry would have at the current slot. If the occupant's PSL is *smaller* than d, the occupant is "richer" (closer to home), so the new entry takes the slot and the evicted occupant continues the walk with its own PSL. The rich give to the poor. + +This maintains an invariant: **moving from one occupied slot to the next, PSL rises by at most one.** Equivalently, within a run of occupied slots, entries are sorted by home slot. Two consequences follow. + +- **Unsuccessful lookups stop early.** Suppose a search for k reaches slot i at distance d and the occupant's PSL is less than d. If k were stored further on, at slot j, its PSL there would be d + (j − i), so PSL would have to rise by more than j − i over j − i steps, which the invariant forbids. So the search can stop without reaching an empty slot. (An empty slot can be treated as PSL −1, which makes it the same test.) +- **Deletion needs no tombstones.** Remove the entry, then shift each following entry back one slot, reducing its PSL by one, until reaching an empty slot or an entry with PSL 0 (already at home, so it cannot move closer). This is **backward-shift deletion**. The run stays sorted and the table never accumulates tombstones. + +The code keeps the conventions of `HashTable` above, with a third array holding each slot's PSL: + +```python +class RobinHoodTable: + """Linear probing where the entry farther from home keeps the slot.""" + + def __init__(self, capacity=16): + self._keys = [None] * capacity + self._values = [None] * capacity + self._dist = [-1] * capacity # probe-sequence length; -1 marks empty + self._count = 0 + + def __len__(self): + return self._count + + def _home(self, key): + return hash(key) % len(self._keys) + + def _find(self, key): + """Slot holding key, or None. Stops early at an empty or richer slot.""" + m = len(self._keys) + i, d = self._home(key), 0 + while self._dist[i] >= d: # empty (-1) is < d too, so it also stops + if self._dist[i] == d and self._keys[i] == key: + return i + i, d = (i + 1) % m, d + 1 + return None + + def __getitem__(self, key): + i = self._find(key) + if i is None: + raise KeyError(key) + return self._values[i] + + def __setitem__(self, key, value): + i = self._find(key) + if i is not None: + self._values[i] = value # overwrite in place + return + if self._count + 1 > len(self._keys) * 0.9: + self._resize(len(self._keys) * 2) + m = len(self._keys) + i, d = self._home(key), 0 + while self._dist[i] != -1: + if self._dist[i] < d: # occupant is closer to home: rob it + key, self._keys[i] = self._keys[i], key + value, self._values[i] = self._values[i], value + d, self._dist[i] = self._dist[i], d + i, d = (i + 1) % m, d + 1 + self._keys[i], self._values[i], self._dist[i] = key, value, d + self._count += 1 + + def __delitem__(self, key): + i = self._find(key) + if i is None: + raise KeyError(key) + m = len(self._keys) + j = (i + 1) % m + while self._dist[j] > 0: # backward shift: pull the run left + self._keys[i], self._values[i] = self._keys[j], self._values[j] + self._dist[i] = self._dist[j] - 1 + i, j = j, (j + 1) % m + self._keys[i], self._values[i], self._dist[i] = None, None, -1 + self._count -= 1 + + def _resize(self, new_capacity): + old = [(k, v) for k, v, d in zip(self._keys, self._values, self._dist) + if d != -1] + self.__init__(new_capacity) + for k, v in old: + self[k] = v +``` + +Two details. `_find` compares the stored PSL before the key: an entry with a different PSL at this slot has a different home, so it cannot be k, and the expensive key comparison is skipped. Production tables store part of the hash per slot for the same reason. And `__setitem__` searches for an existing key first, so the displacement walk never needs to compare keys: every entry it carries is known to be unique. + +**A trace.** Take m = 8 and h(k) = k mod 8 (small integers hash to themselves in CPython), and insert 2, 3, 8, 16, 24. The first four go to slots 2, 3, 0, 1 with no conflict. Key 24 has home 0: + +| Slot | Occupant (PSL) | 24's distance | Action | +|------|----------------|---------------|--------| +| 0 | 8 (0) | 0 | 0 is not < 0, move on | +| 1 | 16 (1) | 1 | 1 is not < 1, move on | +| 2 | 2 (0) | 2 | 0 < 2: 24 takes slot 2, carry 2 at distance 0 | +| 3 | 3 (0) | 1 | 0 < 1: 2 takes slot 3, carry 3 at distance 0 | +| 4 | empty | 1 | 3 settles here with PSL 1 | + +Compare the two layouts: + +``` +slot: 0 1 2 3 4 5 6 7 +linear probing: 8 16 2 3 24 . . . PSLs 0 1 0 0 4 +Robin Hood: 8 16 24 2 3 . . . PSLs 0 1 2 1 1 +``` + +Both PSL lists sum to 5, so the average successful lookup costs the same, but the worst entry dropped from 4 to 2. An unsuccessful search for 32 (home 0) scans slots 0 to 5 under linear probing, 6 probes. Under Robin Hood it stops at slot 3, where it is at distance 3 but the occupant has PSL 1: 4 probes. Deleting 16 from the Robin Hood table shifts 24, 2 and 3 back one slot each, giving `8 24 2 3 . . . .` with PSLs 0 1 0 0, which is exactly the table you would get if 16 had never been inserted. + +**Why it works: the mean is fixed, the variance is not.** The equal sums in the trace are not a coincidence. Under linear probing, Robin Hood never changes the total PSL of a set of keys, only who pays it (Exercise 12.9). What it changes is the spread. Measured on one table of m = 65,536 slots filled with random hash values: + +| α | Mean PSL (both) | PSL variance, LP / RH | Max PSL, LP / RH | Probes per miss, LP / RH | +|---|---|---|---|---| +| 0.50 | 0.50 | 1.6 / 0.7 | 29 / 7 | 2.5 / 1.7 | +| 0.75 | 1.5 | 18.6 / 3.9 | 115 / 24 | 8.2 / 2.9 | +| 0.90 | 4.3 | 234 / 19 | 467 / 36 | 44.5 / 5.7 | + +At α = 0.9 the longest probe drops by a factor of 13 and misses get 8 times cheaper, which is what lets Robin Hood tables run at a load factor of 0.9 where plain linear probing has collapsed. All operations remain O(1) *expected* time for a fixed α < 1, O(n) worst case, with insertion O(1) amortized across resizes. The costs are an extra field per slot (a byte is enough for the PSL in practice), more writes per insertion because of the swaps, and deletions that may shift a whole run. + +Robin Hood hashing was the design of Rust's standard `HashMap` until Rust 1.36 (2019), and it is used by C++ libraries such as `tsl::robin_map`, which combines it with backward-shift deletion. + +### Swiss Tables + +Robin Hood still compares keys slot by slot. A Swiss table, the design behind Google's Abseil `flat_hash_map`, moves the search out of the key array altogether. + +**Layout.** Alongside the array of slots (each holding a key and value) sits a separate array of **control bytes**, one per slot. A control byte says what the slot holds: + +| Control byte | Meaning | +|--------------|---------| +| `0b1000_0000` (0x80) | empty | +| `0b1111_1110` (0xFE) | deleted (tombstone) | +| `0b0xxx_xxxx` | full; the low 7 bits are H2 of the key's hash | + +These are Abseil's values (Abseil also has a sentinel, 0xFF, marking the end of the array for iteration). The essential rule is that special states have the top bit set and full slots have it clear, so "is this slot free?" is a single bit test. + +**Splitting the hash.** A 64-bit hash is split into two parts. **H1**, 57 bits, chooses where in the table the probe starts. **H2**, the other 7 bits, is stored in the control byte. (The original design took H2 from the low 7 bits; current Abseil and Rust's hashbrown take the top 7. Either works if the hash is well mixed.) + +**Probing a group at once.** Slots are examined in **groups** of 16. To look up k, start at the group H1 selects, load its 16 control bytes into one 128-bit SSE2 register, and compare all 16 against H2 in a single instruction (`_mm_cmpeq_epi8`, after broadcasting H2 to all 16 lanes). A second instruction (`_mm_movemask_epi8`) packs the result into a 16-bit mask with one bit per matching slot. Only those slots' keys are compared. If the group also contains an empty byte, the key is absent; otherwise move to the next group. For example, with H2 = 0x15: + +``` +slot j: 0 1 2 3 4 5 6 7 ... 15 +control: 0x15 0x80 0x3A 0x15 0xFE 0x61 0x80 0x0C ... +== H2? 1 0 0 1 0 0 0 0 +match mask: 0b...1001 -> compare keys in slots 0 and 3 only +empty mask: 0b...0100_0010 (nonzero) -> if neither matches, k is absent +``` + +A full slot holding a different key matches a random 7-bit H2 with probability 1/128, so wasted key comparisons are rare. In the model below, filled to the maximum load of 7/8, a successful lookup inspected 1.1 groups and made 0.07 failed key comparisons on average, and an unsuccessful one inspected 2.1 groups and made 0.23. + +**Why it wins on cache behaviour.** A probe step reads 16 *bytes* of contiguous metadata, a quarter of a 64-byte cache line, instead of 16 keys and values spread over several lines. A typical lookup touches one line of control bytes and then the one slot that matches: about two cache misses whatever the key type, and the key comparison, which for strings is the expensive part, almost always succeeds the first time it runs. Because one step covers 16 slots, clusters cost little, and the table runs comfortably at 7/8 load with only one byte of overhead per slot. No PSLs are stored, and nothing moves on insert. + +Groups are visited in triangular order (offsets of 0, 1, 3, 6, 10, ... groups), which visits every group exactly once when the number of groups is a power of two. Deletion writes a tombstone, with one refinement: if the deleted slot's group still contains an empty byte, then that group has never been full, so no insertion ever probed past it, and the slot can be marked empty instead. Tombstones consume the growth budget like full slots, so a delete-heavy table eventually rehashes, often in place at the same size. + +The following Python models that logic. It has no SIMD: `_match` loops over 16 bytes where the real code runs about three instructions. It also simplifies one thing: here groups are aligned blocks of 16, while Abseil and hashbrown load 16 bytes starting at any slot, copying the first group's control bytes to the end of the array so a load can wrap around. With unaligned groups, the never-full test for deletion has to look at the control bytes on both sides of the slot. + +```python +GROUP = 16 # slots per group: one 16-byte SSE2 register +EMPTY, DELETED = 0x80, 0xFE # Abseil's values; a full slot holds 0x00-0x7F +MASK64 = (1 << 64) - 1 + +def _mix(h): + """Scramble Python's hash: small ints hash to themselves, and both + H1 and H2 need well-mixed bits.""" + h = (h * 0x9E3779B97F4A7C15) & MASK64 + return h ^ (h >> 29) + +class SwissTable: + def __init__(self, groups=1): # groups must be a power of 2 + n = groups * GROUP + self._ctrl = bytearray([EMPTY]) * n + self._keys = [None] * n + self._values = [None] * n + self._count = 0 + self._growth_left = n * 7 // 8 # max load factor 7/8 + + def __len__(self): + return self._count + + @staticmethod + def _split(key): + h = _mix(hash(key)) + return h >> 7, h & 0x7F # H1: where to start, H2: 7-bit tag + + def _match(self, g, pred): + """Bitmask of slots j in group g with pred(ctrl byte). Models one SIMD + compare plus movemask: 16 bytes tested at once in hardware.""" + base, mask = g * GROUP, 0 + for j in range(GROUP): + if pred(self._ctrl[base + j]): + mask |= 1 << j + return mask + + def _probe(self, h1): + """Groups in triangular order g, g+1, g+3, g+6, ...: with a power-of-2 + number of groups this visits every group exactly once.""" + ngroups = len(self._ctrl) // GROUP + g = h1 & (ngroups - 1) + for i in range(ngroups): + yield g + g = (g + i + 1) & (ngroups - 1) + + def _find(self, key): + h1, h2 = self._split(key) + for g in self._probe(h1): + m = self._match(g, lambda c: c == h2) + while m: # usually 0 or 1 candidates + i = g * GROUP + (m & -m).bit_length() - 1 + if self._keys[i] == key: + return i + m &= m - 1 # clear lowest set bit + if self._match(g, lambda c: c == EMPTY): + return None # nothing ever probed past here + return None + + def __getitem__(self, key): + i = self._find(key) + if i is None: + raise KeyError(key) + return self._values[i] + + def __setitem__(self, key, value): + i = self._find(key) + if i is not None: + self._values[i] = value + return + if self._growth_left == 0: # full of entries or tombstones + ngroups = len(self._ctrl) // GROUP + grow = self._count >= len(self._ctrl) * 7 // 16 + self._rehash(2 * ngroups if grow else ngroups) + h1, h2 = self._split(key) + for g in self._probe(h1): + m = self._match(g, lambda c: c & 0x80) # EMPTY or DELETED: top bit set + if m: + i = g * GROUP + (m & -m).bit_length() - 1 + if self._ctrl[i] == EMPTY: + self._growth_left -= 1 # reusing a tombstone costs nothing + self._ctrl[i] = h2 + self._keys[i], self._values[i] = key, value + self._count += 1 + return + + def __delitem__(self, key): + i = self._find(key) + if i is None: + raise KeyError(key) + if self._match(i // GROUP, lambda c: c == EMPTY): + self._ctrl[i] = EMPTY # group was never full: no probe went past it + self._growth_left += 1 + else: + self._ctrl[i] = DELETED # some key may have probed past: tombstone + self._keys[i] = self._values[i] = None + self._count -= 1 + + def _rehash(self, groups): + old = [(k, v) for c, k, v in zip(self._ctrl, self._keys, self._values) + if not c & 0x80] + self.__init__(groups) + for k, v in old: + self[k] = v +``` + +The `_mix` step is not decoration. With Python's identity hash for integers, the top bits of every small key would be zero and every key would share the same H2, turning each probe into a full scan of the group. Swiss tables need a hash whose every bit is well mixed, which is why Abseil and hashbrown ship their own hash functions rather than trusting the key type's. Complexity is the same as for any open-addressing table: O(1) expected per operation at bounded load, O(n) worst case, insertion O(1) amortized. + +**Who uses what.** It is worth being precise, because "hash table" names a different structure in every language: + +- **C++:** Abseil's `flat_hash_map` and `flat_hash_set` are Swiss tables. `std::unordered_map` uses chaining, because the standard requires that references to elements survive a rehash and exposes a bucket interface, which together rule out open addressing. +- **Rust:** `std::collections::HashMap` has been a Swiss table since Rust 1.36 (2019), when the standard library adopted the `hashbrown` crate. It uses 16-slot groups with SSE2 on x86 and 8-slot groups on other 64-bit targets. Its byte values differ from Abseil's (empty is 0xFF, deleted is 0x80), but the top-bit rule is the same. +- **Go:** the built-in `map` switched to a Swiss table in Go 1.24 (February 2025). It uses groups of 8 slots with a 64-bit control word, SIMD instructions on amd64 and portable bit arithmetic elsewhere (Exercise 12.10), and the same 7/8 load factor. Each map is a set of tables of at most 1,024 slots, with upper hash bits choosing the table, so growing the map splits one small table at a time and no single insertion pays for rehashing the whole map. +- **Python:** `dict` is neither linear probing nor a Swiss table. It probes with the recurrence i ← (5i + 1 + perturb) mod 2ᵏ, shifting `perturb` (initially the full hash) right by 5 bits each step, so the high bits of the hash influence the probe sequence; this matters because small integers hash to themselves. Since CPython 3.6 the table is also **compact**: the hashed array holds only small integer indices (1 byte each for small tables), pointing into a dense array of (hash, key, value) entries kept in insertion order. An empty slot then costs 1 byte instead of a 24-byte entry, and the dense array is why dicts iterate in insertion order, a guarantee of the language since 3.7. The index array is kept at most 2/3 full. +- **Java:** `HashMap` uses chaining with tree bins (Section 12.3). + +### Choosing a Scheme + +| | Chaining | Linear probing (12.4) | Robin Hood | Swiss table | +|---|---|---|---|---| +| **Memory per entry** | Node per entry (next pointer plus allocator overhead) and a bucket pointer per slot | Key and value only, but 1 − α of the slots are empty and full-sized | As linear probing, plus a PSL or stored hash per slot | Key and value plus 1 control byte per slot | +| **Probe behaviour** | One dependent pointer load per chain node, each a likely cache miss | Sequential and cache-friendly; primary clustering gives long tails; misses scan to an empty slot | Sequential with low variance; misses stop at the first richer occupant | 16 (or 8) control bytes tested per step; keys compared only on a 7-bit tag match | +| **Deletion** | Unlink the node; no tombstones | Tombstones, cleared only by rehashing | Backward shift; no tombstones | Tombstone, or empty if the group was never full | +| **Max useful α** | Above 1 still works; Java uses 0.75, C++ `unordered_map` 1.0 | About 0.7 | About 0.9 | 7/8 | +| **Used by** | Java `HashMap`, C++ `std::unordered_map` | Java `IdentityHashMap`, many hand-written tables | Rust before 1.36, `tsl::robin_map` | Abseil, Rust `HashMap`, Go 1.24+ | + +All four are O(1) expected and O(n) worst case per operation; the differences are constant factors, memory, and tail behaviour. For open addressing, memory per *stored* entry is the slot size divided by α: at 7/8 load a Swiss table spends 8/7 of a slot per entry, at 0.7 linear probing spends 10/7. Chaining remains the right choice when elements must never move (other code holds pointers to them) or are large, since open addressing copies entries on every resize. When keys and values are small and lookups are hot, which is the common case, the Swiss table is the current default for good reason. + +## 12.6 Perfect Hashing If all keys are known in advance, we can construct a hash table with no collisions. @@ -249,7 +566,7 @@ The FKS scheme (Fredman, Komlós, Szemerédi, 1984) makes this concrete and give **Minimal perfect hashing** goes further, mapping n keys to exactly n slots with no gaps. Modern constructions (CHD, BBHash, PTHash) achieve about 2–3 bits of overhead per key. These are used where a key set is fixed and lookups are hot: compiler keyword recognition, `gperf`-generated parsers, static routing tables, and the term dictionaries in search indexes. -## 12.6 Applications +## 12.7 Applications **Dictionaries/Maps**: - Python dict, Java HashMap, C++ unordered_map @@ -269,11 +586,11 @@ The FKS scheme (Fredman, Komlós, Szemerédi, 1984) makes this concrete and give **Counting/frequency**: - Word frequency in text -The LRU cache is worth expanding, because it is the canonical example of composing two structures to get properties neither has alone. A hash table gives O(1) lookup but no notion of recency; a doubly linked list gives O(1) reordering but no lookup. Combine them (hash key → list node, list ordered by recency)and every operation is O(1): find the node by hash, unlink it, move it to the head. Python's `functools.lru_cache` and every production cache are built this way. +The LRU cache is worth expanding, because it is the canonical example of composing two structures to get properties neither has alone. A hash table gives O(1) lookup but no notion of recency; a doubly linked list gives O(1) reordering but no lookup. Combine them (hash key → list node, list ordered by recency), and every operation is O(1): find the node by hash, unlink it, move it to the head. Python's `functools.lru_cache` and every production cache are built this way. **Where hash tables are the wrong choice**, which is easy to forget given how good the average case is: any workload needing ordered iteration, range queries, nearest-key lookups, or prefix matching. Those need a tree or a trie. The failure mode is insidious because a hash table works fine until the day someone asks for "all records between these two dates". -## 12.7 Historical Context +## 12.8 Historical Context Hash tables were invented independently by multiple researchers in the 1950s-1960s. The term "hash" comes from the idea of "hashing" (mixing up) the keys. @@ -281,6 +598,8 @@ 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. +Robin Hood hashing comes from Pedro Celis's work with Per-Åke Larson and Ian Munro at Waterloo, published at FOCS in 1985 and in Celis's 1986 PhD thesis. Crosby and Wallach described algorithmic complexity attacks on hash tables in 2003; Klink and Wälde's 28C3 talk in December 2011 showed how widely web platforms were exposed, and Aumasson and Bernstein's SipHash (2012) became the standard response. Swiss tables were designed at Google by Sam Benzaquen, Alkis Evlogimenos, Matt Kulukundis and Roman Perepelitsa, presented by Kulukundis at CppCon 2017, and open-sourced in Abseil in 2018. Rust adopted the design through `hashbrown` in 2019 and Go in 2025. + ## Exercises Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch. @@ -445,7 +764,7 @@ The probabilities sum to 1. The slot just past the run of length 4 catches half -**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`. +**12.6 ★★ Build the LRU cache.** Section 12.7 describes an LRU cache as a hash table pointing into a doubly linked list. Implement `LRUCache(capacity)` with `get(key)` (return the value or `None`, and mark the key most recently used) and `put(key, value)` (insert or update, evicting the least recently used key when full). Both must be O(1). Do not use `OrderedDict`.
Hint @@ -547,6 +866,108 @@ By Markov again, Pr[Σ bᵢ² ≥ 4n] < ½. So the construction picks a first-le
+**12.8 ★★ Robin Hood by hand.** Use the `RobinHoodTable` from Section 12.5 with capacity 8, so h(k) = k mod 8. (a) Insert 5, 6, 13, 14, 21 in that order and show the keys and PSLs after each insertion. (b) How many probes does an unsuccessful search for 29 take, and how many would it take in the plain linear-probing table holding the same keys? (c) Delete 13 and show the result. + +
+Hint + +21's walk wraps from slot 7 to slot 0, and the entry it evicts keeps walking. + +
+ +
+Solution + +(a) Writing each slot as key(PSL): + +| Insert | Home | Result (slots 0 to 7) | What happened | +|--------|------|------------------------|---------------| +| 5 | 5 | `. . . . . 5(0) . .` | empty home slot | +| 6 | 6 | `. . . . . 5(0) 6(0) .` | empty home slot | +| 13 | 5 | `. . . . . 5(0) 13(1) 6(1)` | at slot 6, 13 has distance 1 and 6 has PSL 0, so 13 takes it; 6 moves to slot 7 | +| 14 | 6 | `14(2) . . . . 5(0) 13(1) 6(1)` | slots 6 and 7 hold PSL 1 against 14's 0 and 1; wraps to slot 0 | +| 21 | 5 | `14(2) 6(3) . . . 5(0) 13(1) 21(2)` | at slot 7, 21 has distance 2 and 6 has PSL 1: swap. 6 continues at distance 2, cannot take slot 0 (14 has PSL 2), lands in slot 1 | + +(b) 29 has home 5. It sees 5(0) at distance 0, 13(1) at distance 1, 21(2) at distance 2, then 14(2) at slot 0 at distance 3. Since 2 < 3, the search stops: **4 probes**. Plain linear probing puts the same keys at `14 21 . . . 5 6 13`, and the search scans slots 5, 6, 7, 0, 1 and stops at the empty slot 2: **6 probes**. + +(c) 13 is in slot 6. Backward shift moves 21 to slot 6 (PSL 1), 14 to slot 7 (PSL 1) and 6 to slot 0 (PSL 2), then stops at the empty slot 2 and clears slot 1: + +``` +slot: 0 1 2 3 4 5 6 7 + 6(2) . . . . 5(0) 21(1) 14(1) +``` + +No tombstone was written, and every entry that moved is now one slot closer to home. + +
+ +**12.9 ★★★ Robin Hood cannot change the average.** Insert the same keys in the same order into a plain linear-probing table and a Robin Hood table of the same size, with no deletions or resizes. Prove that the sum of all PSLs is the same in both, so the average successful lookup costs the same. What does Robin Hood change, then? + +
+Hint + +First show both tables have the same set of occupied slots. Then, during a Robin Hood insertion, track the quantity T = (sum of PSLs of the entries in the table) + (current distance of the entry being carried). + +
+ +
+Solution + +**Same occupied slots.** By induction on insertions. Suppose both tables have the same occupied set and a key with home h arrives. Linear probing puts it in e, the first empty slot at or after h. Robin Hood's walk also starts at h and moves forward one slot at a time; swaps exchange which entry occupies a slot but never empty or fill one, so the walk ends by filling the same slot e. The occupied sets stay equal. + +**Same total.** Linear probing adds one entry with PSL (e − h) mod m, so the total grows by (e − h) mod m. For Robin Hood, track T as in the hint. At the start of the walk T is the old total plus 0. A step to the next slot adds 1 to the carried entry's distance, so T grows by 1. A swap puts the carried entry, with distance d, into the slot and picks up the occupant with its PSL d′: the table's sum changes by d − d′ and the carried distance by d′ − d, so T is unchanged. The walk takes (e − h) mod m steps, and when it ends the carried entry is placed at e, so the new total is the old total plus (e − h) mod m, exactly as for linear probing. + +(Without wraparound there is a one-line version: the total PSL is Σ(position − home) = Σ positions − Σ homes. The first sum depends only on the occupied set and the second only on the keys.) + +So the mean PSL, and the average successful-search cost of 1 + mean PSL, is identical. Robin Hood only redistributes the total: it takes slots from entries near home and gives them to entries far from home, which shrinks the variance and the maximum, as the table in Section 12.5 shows. Separately, its invariant lets *unsuccessful* searches stop early, so those do get cheaper on average. + +
+ +**12.10 ★★★ Matching without SIMD.** Go's map on architectures other than amd64, and hashbrown on targets without SSE2, use groups of 8 control bytes packed into one 64-bit integer and find matches with ordinary arithmetic. With `LSB = 0x0101010101010101` and `MSB = 0x8080808080808080`, the match is: + +``` +x = word XOR (h2 × LSB) +match = (x − LSB) AND (NOT x) AND MSB +``` + +(a) Implement it in Python (byte j of the group is bits 8j to 8j + 7) and run it on the group `0x15 0x80 0x3A 0x15 0xFE 0x61 0x80 0x0C` with H2 = 0x15. (b) Show that a byte equal to h2 is always flagged, and that an empty or deleted byte (top bit set) never is. (c) The test can flag a byte that does not equal h2. Find an example, say exactly when it happens, and explain why it is harmless. + +
+Hint + +XOR turns matching bytes into 0x00. Think about what subtracting 0x01 does to a 0x00 byte, and what the resulting borrow does to the byte above it. + +
+ +
+Solution + +(a) + +```python +LSB = 0x0101010101010101 # 0x01 in every byte +MSB = 0x8080808080808080 # 0x80 in every byte +MASK64 = (1 << 64) - 1 + +def match_h2(word, h2): + """0x80 in every byte of word that (probably) equals h2.""" + x = word ^ (h2 * LSB) # bytes equal to h2 become 0x00 + return (x - LSB) & ~x & MSB & MASK64 + +group = bytes([0x15, 0x80, 0x3A, 0x15, 0xFE, 0x61, 0x80, 0x0C]) +word = int.from_bytes(group, "little") +assert match_h2(word, 0x15) == 0x80000080 # bytes 0 and 3 + +fp = int.from_bytes(bytes([0x15, 0x14] + [0x80] * 6), "little") +assert match_h2(fp, 0x15) == 0x8080 # byte 1 is a false positive +``` + +(b) Take one byte b of x, ignoring borrows for now. If b = 0x00 (the control byte equals h2), then b − 1 = 0xFF with the top bit set, and NOT b = 0xFF also has it set, so the byte is flagged. A borrow coming in from below only makes b − 1 smaller, and 0x00 minus 1 or 2 still has the top bit set, so a true match is never missed. If the control byte is empty or deleted, its top bit is 1 and h2's is 0, so b has its top bit set and NOT b has it clear: the AND with NOT x removes it whatever the subtraction produced. Special bytes are never reported. + +(c) The subtraction borrows across bytes. A matching byte (b = 0x00) borrows from the byte above it, which therefore has 2 subtracted instead of 1. If that byte is b = 0x01, then 0x01 − 2 = 0xFF (top bit set) and NOT 0x01 = 0xFE (top bit set), so it is flagged. That happens exactly when a full control byte equals h2 XOR 0x01 and sits directly above a true match (or above another such byte in a chain). In the example, byte 1 holds 0x14 = 0x15 XOR 0x01 just above the 0x15 in byte 0. It is harmless because every flagged slot has its key compared before anything is returned: a false positive costs one extra comparison and never a wrong answer, and by (b) it can never be an empty or deleted slot. Implementations accept it because the exact version needs more instructions on every probe. + +
+ --- ## Where this connects diff --git a/src/volume-2/ch13-string-data-structures.md b/src/volume-2/ch13-string-data-structures.md index b555d5f..7c4a29f 100644 --- a/src/volume-2/ch13-string-data-structures.md +++ b/src/volume-2/ch13-string-data-structures.md @@ -2,7 +2,7 @@ Strings break the assumptions the rest of this book runs on. A comparison is no longer O(1). Comparing two strings costs up to their length. And the queries people actually want are different in kind: not "is this key present" but "which keys start with this", "where does this pattern occur", "what is the longest repeated section". Hash tables answer none of those, because hashing destroys exactly the structure the questions are about. -The structures here exploit the one property strings have that opaque keys don't: **shared prefixes**. Every structure in this chapter is a way of storing a set of strings so that common prefixes are stored once. +The structures here exploit the one property strings have that opaque keys don't: **shared prefixes**. The first half of the chapter is about ways of storing a set of strings so that common prefixes are stored once. The rest covers the other side of string work: finding one pattern in a text that streams past (Section 13.5), many patterns at once (Section 13.6), and holding a string that is being edited (Section 13.7). ## 13.1 Tries (Prefix Trees) @@ -112,7 +112,7 @@ root The chain c→a became one edge "ca". ``` -The guarantee this buys: **every internal node either ends a word or has at least two children**, so a radix tree over n strings has at most n−1 branching nodes regardless of how long the strings are. Space becomes proportional to the number of strings, not the number of characters. For sparse key sets (long keys with little overlap, like URLs or file paths)the saving is enormous. +The guarantee this buys: **every internal node either ends a word or has at least two children**, so a radix tree over n strings has at most n−1 branching nodes regardless of how long the strings are. Space becomes proportional to the number of strings, not the number of characters. For sparse key sets (long keys with little overlap, like URLs or file paths) the saving is enormous. **PATRICIA tries** take it further by storing, at each node, only the *bit position* that distinguishes the subtrees, skipping the intervening bits entirely. A lookup descends on those bit tests alone and performs exactly one full key comparison at the end. This makes them ideal for fixed-width binary keys, which is why they index IP routing tables. An IP lookup is a longest-prefix match over 32 or 128 bits, and the Linux kernel's routing table (`fib_trie`) is a PATRICIA variant. @@ -196,19 +196,205 @@ LCP: 0 0 1 3 0 0 2 Kasai's algorithm computes the LCP array in O(n) once the suffix array is known. Together, the suffix array and LCP array carry all the information in a suffix tree: the LCP array encodes the tree's internal node structure implicitly, so any suffix-tree algorithm can be rewritten to use them. -**Construction** is a solved problem: **SA-IS** (Nong, Zhang, Chan, 2009) builds a suffix array in O(n) worst case, is straightforward compared to Ukkonen's algorithm, and is fast in practice. The simpler O(n log n) doubling approach (sort by first character, then by first 2, then 4, then 8)is what most people implement in contests and is usually fast enough. +**Construction** is a solved problem: **SA-IS** (Nong, Zhang, Chan, 2009) builds a suffix array in O(n) worst case, is straightforward compared to Ukkonen's algorithm, and is fast in practice. The simpler O(n log n) doubling approach (sort by first character, then by first 2, then 4, then 8) is what most people implement in contests and is usually fast enough. **Searching** with a plain suffix array is O(m log n): binary search, comparing up to m characters at each of log n steps. With the LCP array and a little extra bookkeeping this drops to O(m + log n). Suffix arrays are the practical default. The [FM-index](../volume-4/ch24-research-grade-data-structures.md) goes one step further, compressing the suffix array to the text's own entropy while keeping it searchable, which is how BWA and Bowtie fit a human genome index in a few gigabytes. -## 13.5 Aho–Corasick: Searching for Many Patterns at Once +## 13.5 Single-Pattern Matching: Prefix Function, Z-Array, Rolling Hash -Everything so far searches for one pattern. The common real problem is the opposite: given ten thousand patterns (a spam word list, a malware signature set, a set of banned URLs)find every occurrence of any of them in one pass over the text. +Sections 13.3 and 13.4 index the *text*. The opposite case is just as common: one pattern P of length m, one text T of length n that is read once (a log line, a network packet, a file being scanned), and no index worth building. The naive method tries every alignment and compares up to m characters at each, which is O(nm) in the worst case. P = `aaaab` against T = `aaaa…a` reads four `a`s at every one of the n alignments before failing. + +The three structures below are built from the pattern (or from P and T together) in linear time and remove that worst case. Each is an array of integers, or a single number, that summarizes how the string overlaps itself. + +### The prefix function (KMP's failure function) + +A **border** of a string is a proper prefix that is also a suffix: `abab` has the borders `ab` and the empty string. The **prefix function** stores, for every prefix of P, the length of its longest border: + +``` +π[i] = length of the longest proper prefix of P[0..i] that is also a suffix of P[0..i] + +P = a b a b a c a +i = 0 1 2 3 4 5 6 +π = 0 0 1 2 3 0 1 +``` + +π[4] = 3 because `ababa` begins and ends with `aba`. π[5] = 0 because no prefix of `ababac` ends in `c`. + +Why this is the right thing to store: suppose the last k characters of the text match P[0..k), and the next text character c is not P[k]. The alignment that just failed is dead, but a later alignment can only still succeed if the part of it already read is both a suffix of the matched text P[0..k) and a prefix of P. That is a border of P[0..k). The longest one has length π[k−1]; if c does not extend that either, the next candidate is the longest border of the border, π[π[k−1]−1], and so on. A border of a border is itself a border, and this chain visits every border of P[0..k) from longest to shortest, so no possible alignment is skipped. The text pointer never moves backwards. Computing π is the same procedure run on P against itself: + +```python +def prefix_function(p): + """pi[i] = length of the longest proper prefix of p[:i+1] that is also its suffix.""" + pi = [0] * len(p) + k = 0 # length of the current border + for i in range(1, len(p)): + while k > 0 and p[i] != p[k]: + k = pi[k - 1] # fall back to the next shorter border + if p[i] == p[k]: + k += 1 + pi[i] = k + return pi + +def kmp_search(text, pattern): + """Start positions of every occurrence of pattern in text. O(n + m) worst case.""" + pi = prefix_function(pattern) + m, k, hits = len(pattern), 0, [] + for i, ch in enumerate(text): + while k > 0 and ch != pattern[k]: + k = pi[k - 1] + if ch == pattern[k]: + k += 1 + if k == m: + hits.append(i - m + 1) + k = pi[k - 1] # keep going: occurrences may overlap + return hits + +assert prefix_function("ababaca") == [0, 0, 1, 2, 3, 0, 1] +assert kmp_search("abababacab", "ababaca") == [2] +assert kmp_search("aaaa", "aa") == [0, 1, 2] +``` + +A trace of that search, with `k` the number of pattern characters currently matched: + +| i | text[i] | k before | Fallbacks | k after | +|---|---------|----------|-----------|---------| +| 0–4 | a b a b a | 0 → 5 | | 5 | +| 5 | b | 5 | needs `c`; k = π[4] = 3, and P[3] = `b` matches | 4 | +| 6 | a | 4 | | 5 | +| 7 | c | 5 | | 6 | +| 8 | a | 6 | | 7 = m: **match at 2**, then k = π[6] = 1 | +| 9 | b | 1 | | 2 | + +At i = 5 the naive method would restart at alignment 1 and re-read four characters. KMP keeps the three it knows are right (`aba`, the longest border of `ababa`) and continues. + +**Complexity.** Building π is O(m) and searching is O(n), both worst case. The argument is amortized over the run: k grows by at most 1 per character, each fallback shrinks it by at least 1, and it never goes below 0, so the total number of fallbacks is at most the total number of increments, n. The bound is on the total, not per character: with P = `aaaab` and text `aaaac`, the single `c` triggers four fallbacks (k = 4, 3, 2, 1, 0). That matters only for hard real-time stream processing, and Knuth's refinement of the failure function, which skips borders followed by the same character that just failed, cuts the per-character delay to O(log m). Memory is m integers, and the text is consumed one character at a time, so KMP works on a stream that is never stored. + +A side result used constantly: the smallest period of P (the least p with P[i] = P[i + p] for every valid i) is m − π[m−1]. For `abababab`, π[7] = 6, so the period is 2. + +**The connection to Aho–Corasick.** Build the Aho–Corasick automaton of Section 13.6 from a single pattern. The trie is a path of m + 1 nodes, and the failure link of the node at depth q points to the node at depth π[q−1]. The construction is the same loop, too: Aho–Corasick computes failure links in breadth-first order by following the parent's failure link until it reaches a node with an outgoing edge labelled c, which is `while k > 0 and p[i] != p[k]: k = pi[k - 1]` with "has a child labelled c" in place of `p[k] == c`. Aho–Corasick is the prefix function computed over a trie instead of a string. + +### The Z-array + +The **Z-array** measures self-overlap from the other direction: Z[i] is the length of the longest common prefix of S and S[i:], with Z[0] = n by convention. + +``` +S = a a b x a a b +i = 0 1 2 3 4 5 6 +Z = 7 1 0 0 3 1 0 +``` + +Z[4] = 3 because S[4:] = `aab` matches the first three characters of S, and the string ends there. + +Computing every Z[i] by direct comparison is O(n²). The linear algorithm keeps the **Z-box** [l, r): among the matches found so far, the one reaching furthest right, so S[l:r] = S[0:r−l]. For i inside the box, S[i:r] is a copy of S[i−l : r−l], whose Z value is already known, so Z[i] ≥ min(r − i, Z[i − l]) without looking at a character. Only characters at or beyond r are compared, and each successful comparison moves r right. + +```python +def z_array(s): + """z[i] = length of the longest common prefix of s and s[i:]; z[0] = len(s).""" + n = len(s) + z = [0] * n + if n: + z[0] = n + l = r = 0 # s[l:r] matches s[0:r-l], r maximal so far + for i in range(1, n): + if i < r: + z[i] = min(r - i, z[i - l]) # reuse what the box already tells us + while i + z[i] < n and s[z[i]] == s[i + z[i]]: + z[i] += 1 # extend by direct comparison + if i + z[i] > r: + l, r = i, i + z[i] + return z + +def z_search(text, pattern, sep="\0"): + """sep must occur in neither string. O(n + m) worst case.""" + m = len(pattern) + z = z_array(pattern + sep + text) + return [i - m - 1 for i in range(m + 1, len(z)) if z[i] >= m] + +assert z_array("aabxaab") == [7, 1, 0, 0, 3, 1, 0] +assert z_search("abababacab", "ababaca") == [2] +``` + +r only increases and never exceeds n, so the comparisons that extend a match total at most n, and each i adds at most one failed comparison: **O(n) worst case**. To search, compute Z over P + separator + T; the separator caps every value at m, and the occurrences are exactly the positions in the T part where Z reaches m. + +The prefix function and the Z-array carry the same information (each can be converted to the other in O(n)), and both give O(n + m) matching. The practical differences: KMP is online with O(m) memory, while the Z approach as written holds all of P + T. Z values are often easier to reason with, though, because each one directly answers "how far does the text at i agree with the pattern". Matching with at most one mismatch, for example, is two Z computations: one forward over P + sep + T, one over the reversed strings, and an alignment qualifies when the forward and backward agreements together cover at least m − 1 characters. + +### Rolling hashes and Rabin–Karp + +The third approach turns each length-m window of the text into a number and compares numbers. The **polynomial hash** of a string s of length m, for a prime p and a base b in [0, p), is + +``` +H(s) = (s[0]·b^(m-1) + s[1]·b^(m-2) + ... + s[m-1]) mod p +``` + +What makes it useful is that the next window's hash follows from the current one in O(1): remove the leading character's term, shift everything by one power of b, add the new character. + +``` +H(T[i+1 .. i+m]) = ((H(T[i .. i+m-1]) - T[i]·b^(m-1))·b + T[i+m]) mod p +``` + +With small numbers (digits as their own values, b = 10, p = 13), searching for P = `14` in T = `3141592`: H(P) = 14 mod 13 = 1. The windows hash to 31 → 5, then (5 − 3·10)·10 + 4 = −246 ≡ 1, then 2, 2, 7, and for `92`, (7 − 5·10)·10 + 2 = −428 ≡ 1. Two windows hash to 1: `14` at position 1 is a real match, and `92` at position 5 is a **spurious hit**, two different strings with the same hash. Rabin–Karp therefore checks the characters whenever the hashes agree: + +```python +import random + +MOD = (1 << 61) - 1 # a Mersenne prime, about 2.3 * 10**18 + +def rabin_karp(text, pattern, base=None): + """Start positions of pattern in text. Expected O(n + m) when matches are few.""" + n, m = len(text), len(pattern) + if m == 0 or m > n: + return [] + if base is None: + base = random.randrange(256, MOD - 1) # drawn after the input is fixed + high = pow(base, m - 1, MOD) # weight of the character leaving the window + hp = ht = 0 + for i in range(m): + hp = (hp * base + ord(pattern[i])) % MOD + ht = (ht * base + ord(text[i])) % MOD + hits = [] + for i in range(n - m + 1): + if ht == hp and text[i:i + m] == pattern: # verify, so never a false match + hits.append(i) + if i + m < n: # roll: drop text[i], append text[i+m] + ht = ((ht - ord(text[i]) * high) * base + ord(text[i + m])) % MOD + return hits + +assert rabin_karp("abababacab", "ababaca") == [2] +assert rabin_karp("3141592", "14") == [1] +``` + +All three functions in this section were checked against a brute-force search on thousands of random texts over small alphabets, where overlaps and near-misses are most frequent. + +**How likely is a collision?** Fix two different strings x and y of length m *before* the base is chosen. H(x) − H(y) = Σ (x[i] − y[i])·b^(m−1−i) mod p is a nonzero polynomial in b of degree at most m − 1. Over the integers mod a prime, which form a field, such a polynomial has at most m − 1 roots. So for b drawn uniformly at random, **Pr[H(x) = H(y)] ≤ (m − 1)/p**. Summed over the n − m + 1 windows, the expected number of spurious hits is at most about nm/p. With p = 2⁶¹ − 1, n = 10⁹ and m = 1,000, that is about 4 × 10⁻⁷ for the entire scan. With a 30-bit prime such as 10⁹ + 7, the same scan expects about 1,000 spurious hits, each costing an m-character check. + +There are two ways to use the hash: + +- **Las Vegas** (the code above): verify every hash hit. Never wrong, expected O(n + m + m·occ) time. Its worst case is a text full of real matches, `a`ⁿ against `a`ᵐ, where verification costs O(nm). KMP reports the same matches in O(n). +- **Monte Carlo**: trust the hash and skip verification. O(n + m) worst case, wrong with probability at most about nm/p. + +**Why the base must be random.** The bound above is a probability over the choice of b, for inputs fixed before b is drawn. With b and p hard-coded, nothing is random: two given strings either collide or they don't, and anyone who can read the code can pick inputs that do. This is the hash-flooding problem from [Section 12.1](ch12-hash-tables.md) in another form. The most common way to get this wrong is to drop the modulus and let 64-bit arithmetic overflow, which computes the hash mod 2⁶⁴. 2⁶⁴ is not prime, the root-counting argument no longer applies, and there are strings of length 1,024 that collide for *every* odd base (Exercise 13.9). An even base is worse: b⁶⁴ ≡ 0 mod 2⁶⁴, so only the last 64 characters affect the hash at all. + +**Double hashing** runs two hashes with independently drawn bases (and usually two different primes p₁, p₂) and treats a hit as real only when both agree. For a fixed pair of strings the collision probability becomes at most (m/p₁)·(m/p₂), so two primes near 10⁹ behave like one modulus near 10¹⁸. This is the standard technique in languages without cheap 128-bit multiplication. (It is unrelated to double hashing as an open-addressing probe sequence in [Section 12.3](ch12-hash-tables.md).) + +**Beyond one pattern.** A rolling hash turns any substring into a number in O(1): with prefix hashes h[i] = H(S[0..i)), the hash of S[l..r) is h[r] − h[l]·b^(r−l) mod p, so after O(n) preprocessing any two substrings can be compared for equality in O(1) with small error probability. That one primitive gives longest repeated substring by binary search on the length, matching many patterns of the same length through a hash set of their hashes, and two-dimensional matching. In shipped systems, rsync finds moved blocks with a rolling checksum (a sum-based cousin of the polynomial hash) backed by a strong hash; LBFS and backup tools such as restic cut files into content-defined chunks at positions chosen by a rolling Rabin fingerprint (polynomial hashing over GF(2) rather than mod a prime), so an insertion only changes nearby chunks; and MOSS detects plagiarism by "winnowing" the hashes of every k-gram. + +| | Prefix function (KMP) | Z-array | Rolling hash (Rabin–Karp) | +|-|-----------------------|---------|---------------------------| +| Extra space | m integers | n + m integers | O(1) plus the current window | +| Matching time | O(n + m) worst case | O(n + m) worst case | O(n + m) expected with few matches (Las Vegas); O(n + m) worst case if unverified (Monte Carlo) | +| Can report a false match | No | No | Only if unverified, probability ≤ about nm/p | +| Reads the text as a stream | Yes | Not as written | Yes | +| Generalizes to | Many patterns (Aho–Corasick) | Matching with one mismatch | O(1) substring equality, many equal-length patterns, 2D | + +## 13.6 Aho–Corasick: Searching for Many Patterns at Once + +Everything so far searches for one pattern. The common real problem is the opposite: given ten thousand patterns (a spam word list, a malware signature set, a set of banned URLs) find every occurrence of any of them in one pass over the text. Running a single-pattern search once per pattern is O(k·n) for k patterns. Aho–Corasick does it in **O(n + total pattern length + occurrences)**, independent of k. -The construction is a trie of all patterns, augmented with **failure links**. A failure link from a node points to the node representing the longest proper suffix of the current match that is also a prefix of some pattern: exactly the generalization of the KMP failure function to a set of patterns. +The construction is a trie of all patterns, augmented with **failure links**. A failure link from a node points to the node representing the longest proper suffix of the current match that is also a prefix of some pattern: exactly the generalization of the KMP failure function (the prefix function of Section 13.5) to a set of patterns. ``` Patterns: {"he", "she", "his", "hers"} @@ -230,7 +416,233 @@ of a pattern. So on matching "she" you also report "he" for free. When a character doesn't match, follow the failure link instead of restarting. The automaton never re-reads a character of the text, which is where the linear bound comes from. This is the algorithm behind `grep -F`, most intrusion detection systems, and content filters. -## 13.6 Choosing a String Structure +## 13.7 Text Editor Buffers: Gap Buffer, Rope, Piece Table + +Everything so far treats the string as fixed. A text editor holds one string that changes constantly: a stream of small insertions and deletions, interleaved with reads by position (drawing the screen), by line number ("go to line 50,000"), and undo. Files can be hundreds of megabytes (logs, generated JSON). The obvious representation, one contiguous array of characters, costs O(n − i) to insert at position i because everything after i shifts. Typing near the top of a 100 MB file would move 100 MB per keystroke. + +Three access patterns decide which structure fits: edits **at the cursor** (ordinary typing, with strong locality), edits **at scattered positions** (multiple cursors, search-and-replace, a formatter, a collaborator's edits arriving over the network), and **reads** by offset or by line. + +### The gap buffer + +Keep one array, but leave the free space in the middle, at the cursor, instead of at the end. The text is everything outside the gap: `buf[:gap_start] + buf[gap_end:]`, and the cursor is `gap_start`. Typing writes into the gap; moving the cursor moves the gap by copying the characters it passes over to the other side. + +``` +GapBuffer("hello world"): capacity 22, cursor at the end, _ marks the gap + + h e l l o ␣ w o r l d _ _ _ _ _ _ _ _ _ _ _ gap = [11, 22) + +move_to(5): the 6 characters " world" are copied to the far end of the array + h e l l o _ _ _ _ _ _ _ _ _ _ _ ␣ w o r l d gap = [5, 16) + +insert(","): one write into the gap, nothing shifts + h e l l o , _ _ _ _ _ _ _ _ _ _ ␣ w o r l d gap = [6, 16) +``` + +```python +class GapBuffer: + """Text = buf[:gap_start] + buf[gap_end:]. The cursor sits at gap_start.""" + + def __init__(self, text="", capacity=16): + cap = max(capacity, 2 * len(text)) + self.buf = list(text) + [None] * (cap - len(text)) + self.gap_start, self.gap_end = len(text), cap + + def __len__(self): + return len(self.buf) - (self.gap_end - self.gap_start) + + def __getitem__(self, i): # O(1) + if not 0 <= i < len(self): + raise IndexError(i) + if i < self.gap_start: + return self.buf[i] + return self.buf[i + self.gap_end - self.gap_start] + + def move_to(self, pos): # O(|pos - cursor|) + if not 0 <= pos <= len(self): + raise IndexError(pos) + while self.gap_start > pos: # carry characters left of the gap to its right + self.gap_start -= 1 + self.gap_end -= 1 + self.buf[self.gap_end] = self.buf[self.gap_start] + while self.gap_start < pos: # carry characters right of the gap to its left + self.buf[self.gap_start] = self.buf[self.gap_end] + self.gap_start += 1 + self.gap_end += 1 + + def insert(self, s): # O(len(s)) amortized, at the cursor + for ch in s: + if self.gap_start == self.gap_end: + self._grow() + self.buf[self.gap_start] = ch + self.gap_start += 1 + + def delete(self, k=1): # O(1): backspace k characters + self.gap_start = max(0, self.gap_start - k) + + def _grow(self): # double the array: O(n), rare + old_cap = len(self.buf) + tail = self.buf[self.gap_end:] + self.buf = self.buf[:self.gap_start] + [None] * old_cap + tail + self.gap_end = self.gap_start + old_cap + + def __str__(self): + return "".join(self.buf[:self.gap_start] + self.buf[self.gap_end:]) + +g = GapBuffer("hello world") +g.move_to(5) +g.insert(",") +assert str(g) == "hello, world" and (g.gap_start, g.gap_end) == (6, 16) +g.delete(1) +assert str(g) == "hello world" and g[6] == "w" +``` + +**Costs.** Insertion at the cursor is O(1) amortized (the gap is refilled by doubling, the same argument as the dynamic array in [Section 3.4](../volume-1/ch03-arrays-the-foundation-of-contiguous-storage.md)); backspace is O(1), just widening the gap; indexing is O(1), one comparison and one array read. An edit at an arbitrary position first moves the gap there, O(distance), so **O(n) worst case**. That is the whole tradeoff: typing produces long runs of edits in one place, so gap moves are rare and short, and the gap buffer has the best constant factors of anything here, because the text is one contiguous array. It degrades when edits alternate between distant positions, which is exactly what multiple cursors and some search-and-replace orders do (Exercise 13.10). Nothing in it helps find line k (you scan for newlines or keep a separate index), and it has no undo of its own: overwritten gap contents are gone, so editors keep a separate log of (position, text inserted or deleted) records. Emacs is the best-known gap-buffer editor; its buffer text is a gap buffer (`GPT` and `GAP_SIZE` in its C source), and its undo log is the Lisp-visible `buffer-undo-list`. + +### The rope + +A **rope** (Boehm, Atkinson and Plass, 1995) is a balanced binary tree whose leaves hold short strings. The text is the left-to-right concatenation of the leaves, and each internal node stores its **weight**, the length of its left subtree: + +``` + [9] weight = length of the left subtree + / \ + [4] [6] + / \ / \ + "the " "quick" " brown" " fox" text: "the quick brown fox" + +index(12): 12 >= 9, go right with 12 - 9 = 3; 3 < 6, go left; + " brown"[3] = 'o'. +``` + +The operations are built from two primitives. **Concat** makes a new root over two ropes: O(1), plus O(log n) to rebalance. **Split** at position i walks down to i, cuts the leaf there in two, and separates the tree along that root-to-leaf path: O(log n). Insert is split, then two concats; delete is two splits and one concat. On a balanced rope every one of these is **O(log n) worst case wherever the edit lands**: the cursor gives no advantage, and scattered edits cost no more. Indexing is O(log n) instead of O(1), and sequential reads use an iterator that walks leaves rather than descending from the root per character. + +Two extensions make ropes the structure of choice for modern editors: + +- **Augmented counts.** Each node can store, besides the character count, the number of newlines in its subtree. "Offset of line k" and "line containing offset i" then descend the tree in O(log n), the same subtree-summary trick as the weights. +- **Persistence.** If nodes are never modified in place, an edit creates only the O(log n) nodes on the split paths and shares everything else with the previous version, which is path copying from [Chapter 17](../volume-3/ch17-persistent-data-structures.md). An old root is a complete old version, so undo is "keep the root", and a background thread (syntax highlighting, saving, a language server) can read a consistent snapshot while the user keeps typing. + +Production ropes put chunks of tens to about a thousand bytes in each leaf and use a B-tree rather than a binary tree, so the tree is shallow and the per-character work is a copy within one small array. xi-editor's `xi-rope` is a B-tree rope, Helix uses the Ropey library, and Zed's rope is a B+ tree of chunks (its `SumTree`) whose nodes carry summaries including line counts and UTF-16 lengths; Zed takes a snapshot of a buffer for a background thread by copying the root and incrementing reference counts. The cost is constant factors: more memory per character than an array, and pointer chasing on every access. + +### The piece table + +A **piece table** never moves or overwrites text. It keeps two buffers: the **original** buffer, the file exactly as loaded and never modified, and the **add** buffer, to which every typed character is appended. The document is a sequence of **pieces**, each a (buffer, start, length) triple naming a span of one buffer; the text is the concatenation of the spans in piece order. + +Load `the fox jumped`, insert `quick brown ` at offset 4, delete the final `ed`, then type `s`: + +``` +start: [(orig, 0, 14)] "the fox jumped" +insert(4, "quick brown "): split the piece at 4, add a piece for the new text + [(orig, 0, 4), (add, 0, 12), (orig, 4, 10)] "the quick brown fox jumped" +delete(24, 2): split at 24, drop the piece covering "ed" + [(orig, 0, 4), (add, 0, 12), (orig, 4, 8)] "the quick brown fox jump" +insert(24, "s"): [(orig, 0, 4), (add, 0, 12), (orig, 4, 8), (add, 12, 1)] + "the quick brown fox jumps" +``` + +
+{{#include ../images/piece-table.svg}} +
Each piece points into one of the two buffers; the deleted "ed" is still in the original buffer, just no longer referenced, which is what makes undo free.
+
+ +```python +class PieceTable: + """Text = concatenation of pieces; each piece is (buffer, start, length).""" + ORIGINAL, ADD = 0, 1 + + def __init__(self, text=""): + self.buffers = (text, []) # original is read-only, add is append-only + self.pieces = [(self.ORIGINAL, 0, len(text))] if text else [] + self.history = [] # earlier piece lists, for undo + + def _split(self, pos): + """Make pos fall on a piece boundary; return the index of the piece starting there.""" + offset = 0 + for i, (buf, start, length) in enumerate(self.pieces): + if pos == offset: + return i + if pos < offset + length: # pos is inside this piece: cut it in two + k = pos - offset + self.pieces[i:i + 1] = [(buf, start, k), (buf, start + k, length - k)] + return i + 1 + offset += length + if pos == offset: + return len(self.pieces) + raise IndexError(pos) + + def insert(self, pos, s): # O(number of pieces) + if not s: + return + self.history.append(list(self.pieces)) + add = self.buffers[self.ADD] + i = self._split(pos) + prev = self.pieces[i - 1] if i > 0 else None + if prev and prev[0] == self.ADD and prev[1] + prev[2] == len(add): + self.pieces[i - 1] = (self.ADD, prev[1], prev[2] + len(s)) # typing: extend + else: + self.pieces.insert(i, (self.ADD, len(add), len(s))) + add.extend(s) # text is only ever appended + + def delete(self, pos, length): # O(number of pieces) + if length <= 0: + return + self.history.append(list(self.pieces)) + i = self._split(pos) + j = self._split(pos + length) + del self.pieces[i:j] # the characters stay in their buffers + + def undo(self): + if self.history: + self.pieces = self.history.pop() + + def __getitem__(self, i): # O(number of pieces) + for buf, start, length in self.pieces: + if i < length: + return self.buffers[buf][start + i] + i -= length + raise IndexError(i) + + def __len__(self): + return sum(length for _, _, length in self.pieces) + + def __str__(self): + return "".join("".join(self.buffers[b][s:s + n]) for b, s, n in self.pieces) + +pt = PieceTable("the fox jumped") +pt.insert(4, "quick brown ") +pt.delete(24, 2) +pt.insert(24, "s") +assert str(pt) == "the quick brown fox jumps" +assert pt.pieces == [(0, 0, 4), (1, 0, 12), (0, 4, 8), (1, 12, 1)] +pt.undo() +assert str(pt) == "the quick brown fox jump" +pt.undo() +assert str(pt) == "the quick brown fox jumped" +``` + +Both classes were tested against a plain Python string on thousands of random edit sequences, including undo for the piece table. + +**Costs.** With k pieces in a list, finding the piece that contains an offset is O(k), and so are insert, delete and indexing. k grows with the number of separate edits, not with the number of characters: each insert adds at most two pieces and each delete at most one net, so k ≤ 2e + 1 after e edits. Ordinary typing adds none, because the `prev` check extends the piece that ends at the end of the add buffer; editors also cache the cursor's piece, so typing is O(1) amortized. Loading is O(1) beyond reading the file: the original buffer is the file's bytes, never copied or split into lines, and can be memory-mapped. Memory is the original file plus every character ever typed (deleted text is never reclaimed while undo can reach it) plus the pieces. + +**Undo comes free.** The buffers only ever grow, so every past version of the document is still fully described by its piece list. Undo restores an earlier list, and the code above simply snapshots the list (O(k) per edit). Real implementations record the few piece-level changes each edit made and invert them, but the principle is the same: no text is ever copied to support undo. + +**The piece tree.** Replacing the list with a balanced search tree of pieces, each node caching the total length (and newline count) of its left subtree, makes locating an offset or a line O(log k). VS Code switched to exactly this in 2018 (release 1.21): a piece table whose pieces live in a red-black tree, with each node storing its left subtree's length and line-feed count. The old representation, an array of line objects, cost roughly 40 to 60 bytes per line; a 35 MB file of 13.7 million lines took about 600 MB, while the piece tree's memory after loading is close to the file size. + +### Comparing the three + +n is the document length and k the number of pieces. + +| | Gap buffer | Rope (balanced) | Piece table (list) | Piece tree | +|-|-----------|-----------------|--------------------|------------| +| Insert/delete at the cursor | O(1) amortized | O(log n) worst case | O(1) amortized with a cached cursor piece | O(log k) worst case | +| Insert/delete elsewhere | O(n) worst case (gap move) | O(log n) worst case | O(k) | O(log k) worst case | +| Character at offset i | O(1) | O(log n) | O(k) | O(log k) | +| Offset of line j | O(n) scan, unless indexed separately | O(log n) with newline counts | O(n) scan | O(log k) with line-feed counts | +| Undo | Separate edit log | Keep old roots (persistent) | Restore old piece lists; text never destroyed | Same as piece table | +| Memory beyond the text | The gap | Node per chunk | All deleted text, plus pieces | Same, plus tree nodes | +| Used by | Emacs | xi-editor, Zed, Helix (Ropey) | Bravo; Word's "fast save" format | VS Code | + +For one person typing into a file of a few megabytes, all three are instantaneous and the gap buffer is the simplest. The differences appear with large files (load time and memory favour the piece table), with edits scattered across the document (the gap buffer loses), and with concurrency (a persistent rope or piece tree lets other threads read snapshots without locking out the user). + +## 13.8 Choosing a String Structure | Need | Use | Why | |------|-----|-----| @@ -241,11 +653,13 @@ When a character doesn't match, follow the failure link instead of restarting. T | Same, with minimal memory | FM-index | Compressed to text entropy, still searchable | | Many patterns, one text | Aho–Corasick | O(n) regardless of pattern count | | One pattern, one pass, no preprocessing of text | KMP or Boyer–Moore | O(n + m), no index to build | +| Many substring-equality checks on one string | Rolling hash with prefix hashes | O(1) per comparison after O(n) setup, random base | +| A string being edited (an editor buffer) | Gap buffer, rope, or piece table | Section 13.7: by locality of edits, file size, and need for snapshots | | Exact set membership only, no prefix queries | Hash set | Simpler and faster when you don't need order | The decisive question is **which side you preprocess**. Index the text (suffix array, FM-index) when the text is fixed and queries are many: a genome, a codebase, a document corpus. Index the pattern (KMP, Aho–Corasick) when the text streams past once and the patterns are fixed: a log pipeline, a packet filter. -## 13.7 Applications +## 13.9 Applications **Autocomplete**: Trie prefix matching **Spell checking**: Dictionary lookup @@ -253,9 +667,9 @@ The decisive question is **which side you preprocess**. Index the text (suffix a **DNA sequencing**: Pattern matching **Search engines**: Inverted indexes -In shipped systems: Elasticsearch and Lucene store their term dictionaries as finite-state transducers, a compressed-trie variant that shares suffixes as well as prefixes; the Linux kernel routes packets through `fib_trie`, a PATRICIA variant; BWA and Bowtie align sequencing reads against an FM-index of the reference genome; `grep -F` and Snort use Aho–Corasick; Redis implements its stream IDs and cluster key routing over radix trees; and DuckDB and HyPer index with ART. +In shipped systems: Elasticsearch and Lucene store their term dictionaries as finite-state transducers, a compressed-trie variant that shares suffixes as well as prefixes; the Linux kernel routes packets through `fib_trie`, a PATRICIA variant; BWA and Bowtie align sequencing reads against an FM-index of the reference genome; `grep -F` and Snort use Aho–Corasick; Redis implements its stream IDs and cluster key routing over radix trees; and DuckDB and HyPer index with ART. Editors split three ways: Emacs keeps text in a gap buffer, VS Code in a piece tree, and Zed, xi-editor and Helix in ropes; rsync and content-defined chunking in backup tools rest on rolling hashes. -## 13.8 Historical Context +## 13.10 Historical Context Tries were described by Axel Thue in 1912 in a paper on repetition-free strings, long before computers existed to store them. René de la Briandais rediscovered them for file searching in 1959, and Edward Fredkin named them in 1960. From *retrieval*, which is why the original pronunciation is "tree" and why nobody agrees about it. @@ -267,6 +681,10 @@ 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`. +James Morris and Vaughan Pratt found the linear-time single-pattern algorithm in 1970, and Donald Knuth found it independently; the three published it together in 1977 as the Knuth–Morris–Pratt algorithm. Richard Karp and Michael Rabin published randomized fingerprint matching in 1987. The Z-algorithm reached most students through Dan Gusfield's 1997 textbook *Algorithms on Strings, Trees, and Sequences*, which builds linear-time matching on it. + +Editor buffers have their own lineage. Bravo (Butler Lampson and Charles Simonyi, Xerox PARC, 1974) used a piece table, and Simonyi went on to lead Microsoft Word. Hans Boehm, Russ Atkinson and Michael Plass described ropes in 1995, drawing on the Cedar environment at PARC, where ropes had been the standard string representation almost from the start. Charles Crowley's 1998 survey *Data Structures for Text Sequences* compared gap buffers, piece tables and their relatives and argued for the piece table, and VS Code's 2018 rewrite to a piece tree brought the idea back into the mainstream. + ## Exercises Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch. @@ -410,7 +828,7 @@ Each binary search takes O(log n) steps, each comparing up to m characters, so t -**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. +**13.5 ★★ Aho–Corasick failure links.** For the patterns `{"he", "she", "his", "hers"}` from Section 13.6, give the failure link of every trie node. Then run the automaton over the text `ushers` and list every match it reports, with the position where each match starts.
Hint @@ -572,6 +990,108 @@ assert longest_common_substring("abc", "xyz") == ""
+**13.8 ★★ Prefix function, Z-array and periods.** (a) Compute the prefix function π and the Z-array for `aabaaab`. (b) Use π to find the smallest period of `abcabcab`. (c) Explain why m − π[m−1] is always the smallest period of a string of length m. + +
+Solution + +(a) + +``` +S = a a b a a a b +i = 0 1 2 3 4 5 6 +π = 0 1 0 1 2 2 3 +Z = 7 1 0 2 3 1 0 +``` + +Two entries worth checking by hand. π[5] = 2: the prefix `aabaaa` ends in `aa`, which is also its start, but `aab` ≠ `aaa`, so 2 is the longest border. Computing it, the algorithm had k = 2 (border `aa` of `aabaa`), tried to extend with S[5] = `a` against S[2] = `b`, fell back to k = π[1] = 1, and extended `a` to `aa`. Z[3] = 2: S[3:] = `aaab` agrees with S = `aab…` for two characters, then `a` ≠ `b`. + +(b) π for `abcabcab` is `[0, 0, 0, 1, 2, 3, 4, 5]`, so the period is 8 − 5 = 3: the string is `abc` repeated and cut off. + +(c) P has period p exactly when P[i] = P[i + p] for every valid i, which says the prefix of length m − p equals the suffix of length m − p, that is, P has a border of length m − p. So periods and borders correspond one to one (p ↔ m − p), and the smallest period corresponds to the longest border, whose length is π[m−1]. + +```python +def smallest_period(p): + return len(p) - prefix_function(p)[-1] + +assert prefix_function("aabaaab") == [0, 1, 0, 1, 2, 2, 3] +assert z_array("aabaaab") == [7, 1, 0, 2, 3, 1, 0] +assert smallest_period("abcabcab") == 3 +assert smallest_period("abcd") == 4 +``` + +(This block uses `prefix_function` and `z_array` from Section 13.5.) + +
+ +**13.9 ★★★ Breaking a 64-bit rolling hash.** A library computes polynomial hashes with 64-bit unsigned integers and lets them overflow, so all arithmetic is mod 2⁶⁴. The base is random but always odd. Let t₀ = `0`, u₀ = `1`, and t_{k+1} = t_k u_k, u_{k+1} = u_k t_k (concatenation), so t₁₀ and u₁₀ are 1,024 characters long (t is the Thue–Morse sequence, u its complement). Show that H(t₁₀) = H(u₁₀) for every odd base. Why does the collision bound of Section 13.5 not protect against this? + +
+Hint + +Let D_k = H(t_k) − H(u_k), computed over the integers. Write H(t_{k+1}) and H(u_{k+1}) in terms of H(t_k), H(u_k) and b^(2^k), and find a recurrence for D_k. Then count factors of 2. + +
+ +
+Solution + +For strings x and y with |y| = L, H(xy) = H(x)·b^L + H(y). With L = 2^k: + +``` +H(t_{k+1}) = H(t_k)·b^L + H(u_k) +H(u_{k+1}) = H(u_k)·b^L + H(t_k) +D_{k+1} = D_k·b^L − D_k = D_k·(b^(2^k) − 1) +``` + +D₀ = 0 − 1 = −1, so D₁₀ = −(b − 1)(b² − 1)(b⁴ − 1)···(b^512 − 1). + +Now count factors of 2 for odd b. b − 1 is even: at least 1. b² − 1 = (b − 1)(b + 1) is a product of two consecutive even numbers, so it is divisible by 8: at least 3. Each further factor is b^(2^(i+1)) − 1 = (b^(2^i) − 1)(b^(2^i) + 1), and the second factor is even, so the count grows by at least 1 each time: b^(2^i) − 1 has at least i + 2 factors of 2 for i ≥ 1. The total for i = 0 to 9 is at least 1 + (3 + 4 + ··· + 11) = 1 + 63 = 64. So 2⁶⁴ divides D₁₀, and the two strings collide mod 2⁶⁴ whatever the odd base. (For k = 9 the count is only 1 + 52 = 53, so 512 characters are not enough; that agrees with experiment.) + +```python +import random + +def h64(s, b): + h = 0 + for c in s: + h = (h * b + c) & ((1 << 64) - 1) # what overflowing uint64 arithmetic computes + return h + +t, u = [0], [1] +for _ in range(10): + t, u = t + u, u + t +assert len(t) == 1024 and t != u +for _ in range(1000): + b = random.randrange(1, 1 << 64) | 1 # any odd base + assert h64(t, b) == h64(u, b) +``` + +The Section 13.5 bound relies on the modulus being prime: over a field, a nonzero polynomial of degree m − 1 has at most m − 1 roots, so few bases are bad. The integers mod 2⁶⁴ are not a field, and a polynomial there can vanish at every odd input. Here D₁₀, viewed as a polynomial in b, is zero for all 2⁶³ odd bases. Choosing the base at random does not help when the modulus admits a polynomial that kills every base. Use a prime modulus such as 2⁶¹ − 1 (and still draw the base at random). + +
+ +**13.10 ★★ Two cursors.** A 10 MB file is open in an editor. The user places two cursors, at offsets 1,000 and 9,000,000, and types 20 characters; each keystroke inserts one character at each cursor. Estimate the work for (a) a gap buffer, (b) a piece table using the Section 13.7 code (how many pieces are there at the end?), and (c) a balanced rope. + +
+Solution + +(a) Each keystroke inserts at the first cursor, then at the second, and the next keystroke returns to the first. Every visit moves the gap about 9 × 10⁶ characters, twice per keystroke: roughly 20 × 2 × 9 × 10⁶ ≈ 3.6 × 10⁸ character copies for 40 characters typed. With one cursor the same 20 keystrokes cost 20 writes. This is why multi-cursor editing is the gap buffer's weak spot. + +(b) The first insertion splits the original piece at offset 1,000 and adds a piece; the second splits at the far cursor and adds another: 5 pieces. After that, every insertion lands right after an add-buffer piece, but that piece no longer ends at the end of the add buffer, because the other cursor's character was appended in between. The "extend" shortcut fails, and each insertion adds one piece: 5 + 19 × 2 = **43 pieces**. Each operation scans that list, so the work is trivial (a few thousand piece visits), and nothing proportional to the 10 MB file is ever touched. The interleaving shows up in the piece count, not in copying. + +```python +pt = PieceTable("x" * 100) +c1, c2 = 10, 90 +for _ in range(20): + pt.insert(c1, "a"); c1 += 1; c2 += 1 + pt.insert(c2, "b"); c2 += 1 +assert len(pt.pieces) == 43 +``` + +(c) Each insertion is a split and two concatenations, O(log n): with leaves of about 1 KB, a 10 MB rope has about 10⁴ leaves and depth around 14 for a binary tree. 40 insertions cost a few hundred node visits plus copying within small leaves. Like the piece table, the rope does not care how far apart the cursors are. + +
+ --- ## Where this connects diff --git a/src/volume-2/index.md b/src/volume-2/index.md index dc25b06..2256fea 100644 --- a/src/volume-2/index.md +++ b/src/volume-2/index.md @@ -11,7 +11,7 @@ Volume I organised data by position (arrays, lists) and by order (search trees, | 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 | +| [12: Hash Tables](ch12-hash-tables.md) | Explain chaining versus open addressing, reason about load factor and resizing, choose a hash function, explain why Robin Hood hashing and Swiss tables are what modern hash maps use, defend against hash flooding, and build an LRU cache | +| [13: String Data Structures](ch13-string-data-structures.md) | Build tries and radix trees, explain suffix trees and suffix arrays, match patterns with KMP, the Z-array and rolling hashes, search for many patterns at once with Aho-Corasick, and choose between a gap buffer, rope and piece table for a text editor | The three chapters are independent, so read them in any order. If you are preparing for interviews, Chapters 11 and 12 are the most frequently tested material in the whole book. diff --git a/src/volume-3/ch14-probabilistic-data-structures.md b/src/volume-3/ch14-probabilistic-data-structures.md index 83b0c3e..f4126e1 100644 --- a/src/volume-3/ch14-probabilistic-data-structures.md +++ b/src/volume-3/ch14-probabilistic-data-structures.md @@ -4,7 +4,7 @@ Sometimes we don't need exact answers, we need fast, space-efficient approximate answers. Probabilistic data structures trade accuracy for speed and space. -That trade is worth stating precisely, because the amount of accuracy given up is small and the amount of space saved is not. Tracking the unique visitors to a website exactly means storing every visitor ID: 100 million IDs at 16 bytes each is 1.6GB. A HyperLogLog answers the same question to within about 2% using **12 kilobytes**: a factor of 130,000. For a dashboard, 2% error is invisible and 1.6GB is not. +That trade is worth stating precisely, because the amount of accuracy given up is small and the amount of space saved is not. Tracking the unique visitors to a website exactly means storing every visitor ID: 100 million IDs at 16 bytes each is 1.6GB. A HyperLogLog answers the same question with a standard error under 1% using **12 kilobytes**: a factor of 130,000. For a dashboard, an error of a percent or two is invisible and 1.6GB is not. The general shape of every structure in this chapter: @@ -135,7 +135,7 @@ Modern alternative to Bloom filters: - O(1) expected operations - Uses cuckoo hashing internally -A cuckoo filter stores a short **fingerprint** of each element (typically 8 to 12 bits)in a cuckoo hash table with two candidate buckets per item. A query checks both buckets for the fingerprint. +A cuckoo filter stores a short **fingerprint** of each element (typically 8 to 12 bits) in a cuckoo hash table with two candidate buckets per item. A query checks both buckets for the fingerprint. The trick that makes it work is **partial-key cuckoo hashing**. Standard cuckoo hashing needs the original key to relocate an item, and a filter has thrown the key away. Cuckoo filters compute the second bucket as: @@ -151,7 +151,7 @@ Use a cuckoo filter when you need deletion or the lowest false-positive rate per ## 14.5 HyperLogLog -Estimates the number of distinct elements with ~2% error using ~12KB: +Estimates the number of distinct elements with about 0.81% standard error using 12 KB (derived below): ``` Idea: Hash each element @@ -177,7 +177,7 @@ m = number of registers, M[i] = max leading zeros in register i α_m ≈ 0.7213 / (1 + 1.079/m) bias correction constant ``` -Standard error is 1.04/√m. With m = 16,384 registers at 6 bits each (12KB)that is 0.81% error, for a set of any cardinality up to about 2⁶⁴. +Standard error is 1.04/√m. With m = 16,384 registers at 6 bits each (12KB), that is 0.81% error, for a set of any cardinality up to about 2⁶⁴. **The mergeability is the underrated property.** The union of two HyperLogLogs is the element-wise maximum of their registers. That means cardinality across a hundred servers can be computed by each server keeping its own sketch and sending 12KB to a coordinator. No coordination, no shuffling of raw data, and the merge is exact. Merging sketches of A and B gives precisely the sketch you'd get from counting A ∪ B directly. This is why every distributed analytics system uses it. @@ -225,7 +225,7 @@ Count-Min sketches are linear: adding two sketches element-wise gives the sketch **MinHash** estimates the Jaccard similarity of two sets (|A∩B|/|A∪B|)without comparing them. Hash every element of a set and keep the minimum hash. The probability that two sets share the same minimum is exactly their Jaccard similarity, so keeping k independent minima estimates it to within about 1/√k. Combined with locality-sensitive hashing, this is how near-duplicate detection works at web scale: Google used it for deduplicating crawled pages, and it remains standard for plagiarism detection and clustering. -**t-digest** estimates quantiles (medians, p95, p99)over a stream in a few kilobytes, with the crucial property that accuracy is *highest at the extremes*. Ordinary sampling gives uniform accuracy, which is backwards for latency monitoring: nobody cares about a precise median, and everyone cares about p99. t-digest is what Prometheus-adjacent tooling, Elasticsearch percentile aggregations, and most latency dashboards use. +**t-digest** estimates quantiles (medians, p95, p99) over a stream in a few kilobytes, with the crucial property that accuracy is *highest at the extremes*. Ordinary sampling gives uniform accuracy, which is backwards for latency monitoring: nobody cares about a precise median, and everyone cares about p99. t-digest is what Prometheus-adjacent tooling, Elasticsearch percentile aggregations, and most latency dashboards use. ## 14.8 Applications 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 5e6d112..ebfbe06 100644 --- a/src/volume-3/ch15-spatial-and-geometric-data-structures.md +++ b/src/volume-3/ch15-spatial-and-geometric-data-structures.md @@ -152,7 +152,7 @@ R-Tree: └──────────────────┘ ``` -KD-trees and quadtrees index *points*. R-trees index *extended objects* (roads, building footprints, delivery zones)and they are the structure databases actually ship. +KD-trees and quadtrees index *points*. R-trees index *extended objects* (roads, building footprints, delivery zones) and they are the structure databases actually ship. An R-tree is a B-tree whose keys are **minimum bounding rectangles (MBRs)**. Each internal entry stores the MBR enclosing everything in its subtree. A query descends into every child whose MBR intersects the query region, which may be more than one, and that is the crucial difference from a B-tree. Where a B-tree descends exactly one path, an R-tree may descend several. 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 642411a..15d7bf8 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 @@ -35,7 +35,7 @@ The I/O model accounts for disk access: Goal: Minimize block transfers. -The external memory model (also called the I/O model or the Aggarwal–Vitter model, after its 1988 authors)replaces "count the operations" with "count the block transfers." Computation on data already in memory is free; only I/O counts. This sounds crude, and it predicts real performance remarkably well. +The external memory model (also called the I/O model or the Aggarwal–Vitter model, after its 1988 authors) replaces "count the operations" with "count the block transfers." Computation on data already in memory is free; only I/O counts. This sounds crude, and it predicts real performance remarkably well. The model changes the answers, not just the constants: @@ -94,7 +94,7 @@ Compare the layouts directly: | B-tree | O(log_B n) | Yes, node size = B | | van Emde Boas layout | O(log_B n) | No | -The level-order row is worth noting because it is the layout most people write by default. Storing a binary tree breadth-first feels cache-friendly (it is contiguous, after all)but a root-to-leaf path in it touches one new block per level near the bottom, where almost all the nodes are. +The level-order row is worth noting because it is the layout most people write by default. Storing a binary tree breadth-first feels cache-friendly (it is contiguous, after all) but a root-to-leaf path in it touches one new block per level near the bottom, where almost all the nodes are. **Other cache-oblivious results.** Funnelsort achieves the optimal sorting bound obliviously, using a recursively-defined merger structure. Cache-oblivious B-trees combine the vEB layout with a packed-memory array to support updates. These are theoretically beautiful and less common in production than the theory would suggest. The constant factors are worse than a well-tuned B-tree, and in practice you usually *do* know your page size. diff --git a/src/volume-3/ch17-persistent-data-structures.md b/src/volume-3/ch17-persistent-data-structures.md index 7b27148..ffc0d40 100644 --- a/src/volume-3/ch17-persistent-data-structures.md +++ b/src/volume-3/ch17-persistent-data-structures.md @@ -69,7 +69,7 @@ v2 = insert(v1, 35) # v1 still queryable, unchanged v3 = insert(v2, 60) # three coexisting versions ``` -There is no mutation anywhere in that function (it only ever constructs new nodes)which is what makes the old roots remain valid. +There is no mutation anywhere in that function (it only ever constructs new nodes) which is what makes the old roots remain valid. **This is path copying**, and its cost is the height of the tree: @@ -121,7 +121,7 @@ Functional languages favor immutable structures: Each of those bullets deserves unpacking, because they are the practical reasons persistence is worth its overhead. -**Thread-safe by default** is the big one. Every concurrency hazard in [Chapter 18](ch18-concurrent-data-structures.md) (torn reads, lost updates, iterator invalidation)comes from one thread mutating what another is reading. If nothing is ever mutated, there is nothing to synchronize. Readers need no locks at all, and a writer publishes a new version with a single atomic pointer swap. This is why Clojure's concurrency story is as simple as it is. +**Thread-safe by default** is the big one. Every concurrency hazard in [Chapter 18](ch18-concurrent-data-structures.md) (torn reads, lost updates, iterator invalidation) comes from one thread mutating what another is reading. If nothing is ever mutated, there is nothing to synchronize. Readers need no locks at all, and a writer publishes a new version with a single atomic pointer swap. This is why Clojure's concurrency story is as simple as it is. **Undo/redo becomes free.** Keeping a stack of old roots *is* the undo history; no command objects, no inverse operations, no replay. Editors and CAD tools built on persistent structures get unlimited undo as a side effect of the data model. diff --git a/src/volume-3/ch18-concurrent-data-structures.md b/src/volume-3/ch18-concurrent-data-structures.md index 49dfcda..4e4cf3f 100644 --- a/src/volume-3/ch18-concurrent-data-structures.md +++ b/src/volume-3/ch18-concurrent-data-structures.md @@ -40,7 +40,7 @@ The distinction that matters in production: with locks, a thread that is desched **Compare-and-Swap (CAS)** is the primitive everything else is built from. Its semantics are: *atomically*, compare the value at an address to an expected value, and if they match, replace it with a new value. Report whether the swap happened. -The critical word is *atomically*. This is a single indivisible hardware instruction (`LOCK CMPXCHG` on x86, `LDREX`/`STREX` or `CAS` on ARM)not something you can write in plain C. The following is what CAS is **specified to do**, and is emphatically *not* a valid implementation, since the read and the write can be interleaved by another thread exactly as in the lost-update example above: +The critical word is *atomically*. This is a single indivisible hardware instruction (`LOCK CMPXCHG` on x86, `LDREX`/`STREX` or `CAS` on ARM), not something you can write in plain C. The following is what CAS is **specified to do**, and is emphatically *not* a valid implementation, since the read and the write can be interleaved by another thread exactly as in the lost-update example above: ```c /* SPECIFICATION ONLY. This is what the hardware does atomically. @@ -78,7 +78,7 @@ void lock_free_push(_Atomic(Node*) *head, Node *n) { No thread ever waits for another. A failed CAS means someone else succeeded, which is why this is lock-free rather than wait-free: the system always progresses, but one unlucky thread could in principle retry forever. -**The ABA problem** is the classic trap. CAS checks whether a value is unchanged, but what you actually care about is whether the *state* is unchanged, and those differ. Thread A reads head = X. Thread B pops X, pops Y, then pushes X back. Thread A's CAS on X succeeds (the pointer matches)but the list beneath it is now completely different, and A may splice in a node pointing at freed memory. +**The ABA problem** is the classic trap. CAS checks whether a value is unchanged, but what you actually care about is whether the *state* is unchanged, and those differ. Thread A reads head = X. Thread B pops X, pops Y, then pushes X back. Thread A's CAS on X succeeds (the pointer matches) but the list beneath it is now completely different, and A may splice in a node pointing at freed memory. The standard defenses: @@ -125,7 +125,7 @@ void enqueue(Queue *q, Node *n) { } ``` -That final CAS is allowed to fail, because if it does, some other thread has already performed the fix-up. This **helping** pattern (threads completing each other's partial operations rather than waiting)is the general technique for building lock-free structures with multi-step updates. +That final CAS is allowed to fail, because if it does, some other thread has already performed the fix-up. This **helping** pattern (threads completing each other's partial operations rather than waiting) is the general technique for building lock-free structures with multi-step updates. **Concurrent hash maps** are where most real applications actually meet this material, and the design has evolved: @@ -134,7 +134,7 @@ That final CAS is allowed to fail, because if it does, some other thread has alr - **Per-bucket locking with lock-free reads**: Java 8 onward CASes into empty buckets and locks only the first node of a non-empty one, while reads are entirely lock-free over `volatile` fields. Reads scale perfectly; writes contend only on the exact bucket. - **Split-ordered lists** (Shalev and Shavit, 2006): a genuinely lock-free hash table that supports resizing without ever blocking. Resizing being the operation that makes concurrent hash tables hard, since it touches everything at once. -**Concurrent skip lists** are worth knowing because they are why `ConcurrentSkipListMap` exists while a concurrent balanced BST does not. Insertion is local (CAS a few forward pointers)whereas a red-black tree rebalance rotates nodes far from the insertion point, which is very hard to do lock-free. Randomized structure buys concurrency. This is the same trade that makes skip lists attractive in MemSQL, LevelDB's memtable, and Redis sorted sets. +**Concurrent skip lists** are worth knowing because they are why `ConcurrentSkipListMap` exists while a concurrent balanced BST does not. Insertion is local (CAS a few forward pointers) whereas a red-black tree rebalance rotates nodes far from the insertion point, which is very hard to do lock-free. Randomized structure buys concurrency. This is the same trade that makes skip lists attractive in MemSQL, LevelDB's memtable, and Redis sorted sets. **Read-Copy-Update (RCU)** deserves separate mention because it is the dominant technique inside the Linux kernel. Readers pay *nothing at all*: no atomics, no barriers on most architectures, literally just a dereference. Writers copy the structure, modify the copy, and atomically swap the pointer, then wait for a grace period before freeing the old version. It is the right answer for the extremely common read-mostly case, and the wrong one for write-heavy workloads. @@ -154,7 +154,7 @@ The honest summary: lock-free structures win on tail latency and on immunity to Leslie Lamport defined sequential consistency in 1979 and produced the first lock-free queue (for one reader and one writer) in 1977. Maurice Herlihy and Jeannette Wing introduced linearizability in 1990, giving the field its correctness criterion. -Herlihy's 1991 paper "Wait-Free Synchronization" is the theoretical foundation: it established the **consensus hierarchy**, proving that primitives have a consensus number (the maximum number of threads for which they can solve consensus)and that atomic read/write registers have consensus number 1, while compare-and-swap has consensus number ∞. That result is why CAS is *the* universal primitive and why hardware designers ship it: with CAS you can build a wait-free implementation of any object, and without something like it you provably cannot. +Herlihy's 1991 paper "Wait-Free Synchronization" is the theoretical foundation: it established the **consensus hierarchy**, proving that primitives have a consensus number (the maximum number of threads for which they can solve consensus) and that atomic read/write registers have consensus number 1, while compare-and-swap has consensus number ∞. That result is why CAS is *the* universal primitive and why hardware designers ship it: with CAS you can build a wait-free implementation of any object, and without something like it you provably cannot. Maged Michael and Michael Scott published their queue in 1996; it went into `java.util.concurrent` and has been the reference lock-free FIFO ever since. Michael followed with hazard pointers in 2004, addressing the reclamation problem. Paul McKenney's RCU work brought the read-mostly approach into the Linux kernel from 2002 onward, where it is now used in tens of thousands of places. diff --git a/src/volume-3/ch19-emerging-and-specialized-structures.md b/src/volume-3/ch19-emerging-and-specialized-structures.md index c8fde3d..d6da2aa 100644 --- a/src/volume-3/ch19-emerging-and-specialized-structures.md +++ b/src/volume-3/ch19-emerging-and-specialized-structures.md @@ -10,7 +10,7 @@ The Fibonacci heap from [Chapter 9](../volume-1/ch09-heaps-and-priority-queues.m The response has been a search for structures with the same bounds and less machinery: -- **Pairing heaps** (Fredman et al., 1986) are dramatically simpler (a single multiway tree with a `merge` operation)and fast in practice. Their exact amortized `decrease-key` complexity was an open problem for two decades; it is now known to be O(log log n), not O(1), yet they still beat Fibonacci heaps on essentially every real workload. +- **Pairing heaps** (Fredman et al., 1986) are dramatically simpler (a single multiway tree with a `merge` operation) and fast in practice. Their exact amortized `decrease-key` complexity was an open problem for two decades; it is now known to be O(log log n), not O(1), yet they still beat Fibonacci heaps on essentially every real workload. - **Rank-pairing heaps** (Haeupler, Sen, Tarjan, 2011) achieve the full Fibonacci bounds with substantially simpler restructuring. - **Strict Fibonacci heaps** (Brodal, Lagogiannis, Tarjan, 2012) attain the same bounds in the *worst case* rather than amortized: theoretically significant for real-time systems, still not competitive in practice. @@ -64,7 +64,7 @@ Machine learning for index structures: The idea, from Kraska et al.'s 2018 paper "The Case for Learned Index Structures," is a genuine reframing: **an index is a function from key to position, and a model can approximate a function.** If your keys are integers 1 to 100,000,000 stored in order, the "index" is `position = key − 1`, no tree needed. Real data is not that clean, but real data is rarely random either, and a model that captures the shape of the key distribution can beat a structure that assumes nothing about it. -A learned index predicts a position, then does a bounded local search to correct the prediction. The **Recursive Model Index** stages simple models (usually linear regressions, not neural networks, because inference must cost nanoseconds)with each stage narrowing the range. +A learned index predicts a position, then does a bounded local search to correct the prediction. The **Recursive Model Index** stages simple models (usually linear regressions, not neural networks, because inference must cost nanoseconds) with each stage narrowing the range. Reported results are strong: up to 3× faster lookups at a fraction of the memory of a B-tree. The caveats are equally real, and they are what keeps this out of most production systems: @@ -108,7 +108,7 @@ Collaborative text editing is the demanding case, since concurrent inserts at th One significant omission from the original survey, added because it went from research to ubiquitous in roughly three years. -Embedding models turn text, images, and audio into high-dimensional vectors (typically 384 to 1,536 dimensions)and searching them means approximate nearest neighbor over millions of points. [Chapter 15](ch15-spatial-and-geometric-data-structures.md) explained why KD-trees collapse at these dimensionalities. The structures that work instead: +Embedding models turn text, images, and audio into high-dimensional vectors (typically 384 to 1,536 dimensions) and searching them means approximate nearest neighbor over millions of points. [Chapter 15](ch15-spatial-and-geometric-data-structures.md) explained why KD-trees collapse at these dimensionalities. The structures that work instead: - **HNSW** (Hierarchical Navigable Small World, Malkov and Yashunin, 2016) builds a layered proximity graph and greedily descends it. A skip list where the "links" are nearest neighbors. It is the default in most vector databases: excellent recall, fast queries, high memory use, awkward deletion. - **IVF** (inverted file index) clusters vectors and searches only the nearest clusters. Lower memory, tunable recall. diff --git a/src/volume-3/ch20-data-structure-design-patterns.md b/src/volume-3/ch20-data-structure-design-patterns.md index 4d884e5..c599cbc 100644 --- a/src/volume-3/ch20-data-structure-design-patterns.md +++ b/src/volume-3/ch20-data-structure-design-patterns.md @@ -193,7 +193,7 @@ One further note on the example: `build()` sorts `self.values` in place and can Three more that earn their place in collection code. -**Adapter** converts one interface to another. A max-heap from a min-heap by negating keys is the smallest possible example, and Python's `heapq` (min-only)makes it a daily occurrence: +**Adapter** converts one interface to another. A max-heap from a min-heap by negating keys is the smallest possible example, and Python's `heapq` (min-only) makes it a daily occurrence: ```python class MaxHeap: 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 08a1140..7a1276f 100644 --- a/src/volume-3/ch21-algorithm-design-using-data-structures.md +++ b/src/volume-3/ch21-algorithm-design-using-data-structures.md @@ -2,7 +2,7 @@ Algorithm design is usually taught as a catalog of paradigms and data structures as a separate catalog of containers. They are not separate. **Each paradigm is defined by a specific bookkeeping problem, and the paradigm becomes practical exactly when a structure solves that bookkeeping in the right complexity.** -Dijkstra's algorithm is the cleanest demonstration. The algorithm (repeatedly settle the nearest unsettled vertex)is unchanged since 1956. Its complexity is entirely a property of the structure answering "which is nearest?": +Dijkstra's algorithm is the cleanest demonstration. The algorithm (repeatedly settle the nearest unsettled vertex) is unchanged since 1956. Its complexity is entirely a property of the structure answering "which is nearest?": | Priority queue | Complexity | Best for | |----------------|-----------|----------| @@ -28,7 +28,7 @@ The structural insight worth carrying: **the split and the combine trade off aga Where a structure changes the answer outright: - **Segment trees** ([Chapter 23](../volume-4/ch23-advanced-competitive-programming-data-structures.md)) are divide-and-conquer made persistent. Rather than re-splitting per query, the split is stored once as a tree and reused, turning O(n) range queries into O(log n). -- **Karatsuba multiplication** and **Strassen's algorithm** win by reducing the number of subproblems (3 instead of 4, 7 instead of 8)so the branching factor `a` drops and the exponent falls with it. +- **Karatsuba multiplication** and **Strassen's algorithm** win by reducing the number of subproblems (3 instead of 4, 7 instead of 8) so the branching factor `a` drops and the exponent falls with it. - **Deep recursion** on user-controlled input is a stack-overflow bug. An explicit stack is not just a style preference. ## 21.2 Dynamic Programming @@ -92,7 +92,7 @@ Look at the three examples through their structures: | Kruskal's MST | Add cheapest edge that doesn't cycle | Sort + **union-find** | O(E log E) | | Interval scheduling | Take earliest finish time | Sort by end time | O(n log n) | -Kruskal's is the interesting row, because its bookkeeping is not "what's cheapest" (sorting answers that once)but "would this edge create a cycle?" Union-find answers it in near-constant amortized time, α(n), and without union-find the cycle check would be a graph traversal per edge and the algorithm would be O(E·V). A different question needs a different structure. +Kruskal's is the interesting row, because its bookkeeping is not "what's cheapest" (sorting answers that once) but "would this edge create a cycle?" Union-find answers it in near-constant amortized time, α(n), and without union-find the cycle check would be a graph traversal per edge and the algorithm would be O(E·V). A different question needs a different structure. **Greedy is only correct when the problem has the right structure**, and that is a genuine mathematical condition, not a hopeful assumption. The **matroid** property guarantees it. Kruskal's is correct because forests of a graph form a matroid. Absent such a property, greedy produces plausible wrong answers: it fails on 0/1 knapsack, on set cover (though it gives a ln n approximation), and on shortest paths with negative edges, which is exactly why Dijkstra requires non-negative weights. A greedy algorithm that is *nearly* right is often worse than an obviously wrong one, because nobody notices. diff --git a/src/volume-3/ch22-practical-considerations.md b/src/volume-3/ch22-practical-considerations.md index 92b032d..4f28b96 100644 --- a/src/volume-3/ch22-practical-considerations.md +++ b/src/volume-3/ch22-practical-considerations.md @@ -67,7 +67,7 @@ Three practical notes that catch people repeatedly: - **Go randomizes map iteration order on purpose**, so that code cannot come to depend on it. If you need order, sort the keys. - **Rust's default hasher is SipHash**, chosen to resist collision attacks, and it is measurably slower than a non-cryptographic hash. For internal maps with trusted keys, `FxHashMap` is often 2× faster. -- **C++ `std::list` is nearly always a mistake.** The textbook case for a linked list (cheap insertion in the middle)loses to `std::vector` at surprisingly large n, because finding the insertion point requires a traversal and the traversal is cache-hostile. Measure before believing otherwise. +- **C++ `std::list` is nearly always a mistake.** The textbook case for a linked list (cheap insertion in the middle) loses to `std::vector` at surprisingly large n, because finding the insertion point requires a traversal and the traversal is cache-hostile. Measure before believing otherwise. ## 22.3 Performance Optimization @@ -174,7 +174,7 @@ def to_dot(node, out): to_dot(child, out) ``` -**For memory bugs** (use-after-free, double-free, buffer overruns in hand-written C structures)reach for the sanitizers rather than reasoning: `-fsanitize=address` and `-fsanitize=undefined` find in seconds what code review misses for weeks. For concurrent structures, `-fsanitize=thread`, Java's JCStress, or Rust's `loom` are effectively mandatory; a race that has not manifested in testing is not a race that does not exist. +**For memory bugs** (use-after-free, double-free, buffer overruns in hand-written C structures) reach for the sanitizers rather than reasoning: `-fsanitize=address` and `-fsanitize=undefined` find in seconds what code review misses for weeks. For concurrent structures, `-fsanitize=thread`, Java's JCStress, or Rust's `loom` are effectively mandatory; a race that has not manifested in testing is not a race that does not exist. **A checklist for the specific bug classes that recur:** diff --git a/src/volume-4/ch24-research-grade-data-structures.md b/src/volume-4/ch24-research-grade-data-structures.md index 1106065..7046391 100644 --- a/src/volume-4/ch24-research-grade-data-structures.md +++ b/src/volume-4/ch24-research-grade-data-structures.md @@ -139,7 +139,262 @@ VEB Layout of a complete binary tree with h levels: **Search Complexity:** O(log_B N) I/Os, optimal. -## 24.7 External Memory Data Structures +## 24.7 Integer Data Structures and the Predecessor Problem + +### The Predecessor Problem on a Word RAM + +Maintain a set S of n keys drawn from the universe U = {0, 1, ..., u − 1}, under insert and delete, and answer: + +- **predecessor(x):** the largest key in S that is smaller than x; +- **successor(x):** the smallest key in S that is larger than x. + +(Some texts use ≤ and ≥; the difference is one membership test.) This is what an ordered map does for `floor`, `ceiling` and iteration, what a priority queue does when it finds the next nonempty priority level, and what an IP router does when it finds which address range a destination falls into. + +A balanced BST or B-tree answers these in O(log n), and in the **comparison model** that is optimal: an algorithm that learns about keys only by comparing them is a binary decision tree, a query has n + 1 possible answers, so some query needs ⌈log₂(n + 1)⌉ comparisons. Integer keys are not opaque, though. On a **word RAM** with w-bit words (u = 2^w, and w ≥ log₂ n so that a word can hold a pointer), arithmetic, shifts, bitwise operations and reading memory at a computed address each cost O(1), and the decision-tree argument says nothing about algorithms that use them. Radix sort and hashing already escape comparison bounds this way. Hashing alone does not solve predecessor, because a hash table answers "is x in S?" in O(1) but knows nothing about order. The structures in this section answer predecessor queries in O(log log u) = O(log w) time: the recursion depth for 64-bit keys is 6, whatever n is. + +### van Emde Boas Trees + +Peter van Emde Boas (1975) introduced this structure as a priority queue. Split a k-bit key x (u = 2^k) into a high half and a low half: + +high(x) = x >> ⌊k/2⌋, low(x) = x mod 2^⌊k/2⌋, x = high(x) · 2^⌊k/2⌋ + low(x). + +This cuts the universe into about √u **clusters** of about √u keys each: high(x) names x's cluster and low(x) is its position inside. A vEB tree V over a universe of size u holds: + +- `clusters[h]`: a vEB tree over the √u-sized universe of low halves, holding low(x) for every key x in cluster h; +- `summary`: a vEB tree over the √u cluster numbers, holding h for every nonempty cluster; +- `min` and `max`. The minimum is stored **only** here, never in a cluster. The maximum is a cached copy: it is also stored in its cluster. + +When k is odd there are 2^⌈k/2⌉ clusters of 2^⌊k/2⌋ keys, so the summary gets the larger half of the bits. + +Keeping the minimum out of the clusters is what makes the time bound work. Inserting into an empty vEB tree is O(1): set `min = max = x` and stop, with no recursion. So when insert finds x's cluster empty, it makes one recursive call into the summary (to record that the cluster is now nonempty) and an O(1) insert into the empty cluster. When the cluster is already nonempty, the summary does not change and the one recursive call goes into the cluster. Successor has the same shape: if x's cluster holds something larger than low(x), which the cluster's cached `max` tells us in O(1), recurse into the cluster; otherwise recurse into the summary to find the next nonempty cluster and read its `min` in O(1). Either way the work is **one recursive call on a universe of size √u, plus O(1)**: + +T(u) = T(√u) + O(1). + +Substitute m = log₂ u, the number of key bits. Each call halves m, so S(m) = S(m/2) + O(1), which is O(log m). Hence T(u) = O(log log u), **worst case**, for insert, delete, member, successor and predecessor, and O(1) for min and max. For 64-bit keys the bit count goes 64, 32, 16, 8, 4, 2, 1: seven levels. Without the cached `min` and `max`, successor would sometimes need two recursive calls, and T(u) = 2T(√u) + O(1) solves to O(log u), no better than a balanced tree (Exercise 24.8). + +```python +class VEB: + """van Emde Boas tree over the universe {0, ..., 2**k - 1}.""" + + def __init__(self, k): + self.k = k + self.min = None # kept here only, never inside a cluster + self.max = None # cached copy; the max also lives in a cluster + if k > 1: + self.lo_bits = k // 2 # bits of low(x); clusters have universe 2**lo_bits + self.clusters = {} # high(x) -> VEB(lo_bits), nonempty clusters only + self.summary = None # VEB of nonempty cluster numbers, built on demand + + def high(self, x): + return x >> self.lo_bits + + def low(self, x): + return x & ((1 << self.lo_bits) - 1) + + def index(self, h, l): + return (h << self.lo_bits) | l + + def member(self, x): + if x == self.min or x == self.max: + return True + if self.k == 1 or self.min is None: + return False + c = self.clusters.get(self.high(x)) + return c is not None and c.member(self.low(x)) + + def insert(self, x): + if self.min is None: # empty: O(1), no recursion + self.min = self.max = x + return + if x == self.min or x == self.max: # already present + return + if x < self.min: + x, self.min = self.min, x # x becomes the min; push the old min down + if self.k > 1: + h, l = self.high(x), self.low(x) + c = self.clusters.get(h) + if c is None: # new cluster: record it in the summary + c = self.clusters[h] = VEB(self.lo_bits) + if self.summary is None: + self.summary = VEB(self.k - self.lo_bits) + self.summary.insert(h) # the one real recursive call + c.insert(l) # O(1) if c was empty, else the real call + if x > self.max: + self.max = x + + def successor(self, x): + """Smallest element greater than x, or None.""" + if self.min is not None and x < self.min: + return self.min + if self.k == 1: + return 1 if x == 0 and self.max == 1 else None + h, l = self.high(x), self.low(x) + c = self.clusters.get(h) + if c is not None and l < c.max: # answer is in x's own cluster + return self.index(h, c.successor(l)) + if self.summary is None: # only the min is stored, and x >= min + return None + nxt = self.summary.successor(h) # else: the next nonempty cluster + if nxt is None: + return None + return self.index(nxt, self.clusters[nxt].min) + + def delete(self, x): + """Remove x, which must be present.""" + if self.min == self.max: # x is the only element + self.min = self.max = None + return + if self.k == 1: + self.min = self.max = 1 - x + return + if x == self.min: # promote the smallest clustered element + h = self.summary.min + x = self.min = self.index(h, self.clusters[h].min) + h, l = self.high(x), self.low(x) + c = self.clusters[h] + c.delete(l) + if c.min is None: # cluster emptied (that delete was O(1)) + del self.clusters[h] + self.summary.delete(h) + if self.summary.min is None: + self.summary = None + if x == self.max: + if self.summary is None: + self.max = self.min + else: + h = self.summary.max + self.max = self.index(h, self.clusters[h].max) +``` + +Delete follows the same pattern. Deleting the min promotes the smallest clustered key (the min of the summary's min cluster, found in O(1)) to be the new min, and deletes that key from its cluster instead. If the cluster delete empties the cluster, it was O(1), because the cluster held one key; the one real recursive call then removes the cluster number from the summary. The base case k = 1 is a universe {0, 1} described entirely by `min` and `max`. Predecessor is not quite the mirror image of successor, because the minimum lives outside the clusters; Exercise 24.9 works it out. + +The class was checked against a sorted Python list on random sequences of insert, delete, member and successor, for universes of 2 to 2^20 keys, comparing `min` and `max` after every operation. + +**Space, and the hashing fix.** van Emde Boas's structure stores the clusters in an array with a slot for every possible cluster, empty or not. Its space satisfies S(u) = (√u + 1) · S(√u) + Θ(√u), which is Θ(u). For 32-bit keys that is billions of words to hold even a handful of keys; for 64-bit keys it cannot be built. The fix is the one the code above already uses: keep only the nonempty clusters, in a hash table keyed by cluster number (the `dict`), and create a summary only when the first cluster appears. An insert creates at most one new structure per level of recursion (the cluster it found empty), so the space is O(n log log u) words. On random keys the class above uses about 2.6, 3.6 and 4.6 structures per key for 16-, 32- and 64-bit universes (n = 1000): one more per doubling of the word size, as the bound predicts. The price is that the time bounds now rest on hashing: O(log log u) expected for queries, and expected amortized for updates (tables resize). Getting down to O(n) space takes one more idea, bucketing, which is exactly the step from x-fast to y-fast tries below. + +**Worked example (u = 16).** Insert S = {2, 3, 9, 13, 14, 15} into `VEB(4)`. Every key splits into 2 high bits and 2 low bits, so there are four clusters of four keys. + +
+{{#include ../images/veb-tree.svg}} +
A vEB tree for u = 16: the minimum 2 lives only at the top, the summary records which clusters are nonempty, and the empty cluster 1 costs nothing. The green steps are successor(9).
+
+ +| Structure | Holds | min | max | +|-----------|-------|-----|-----| +| V (u = 16) | 2 at the top, the other keys in clusters | 2 | 15 | +| summary (u = 4) | cluster numbers 0, 2, 3 | 0 | 3 | +| cluster 0 (u = 4) | low 3 (key 3) | 3 | 3 | +| cluster 1 | not stored | | | +| cluster 2 (u = 4) | low 1 (key 9) | 1 | 1 | +| cluster 3 (u = 4) | lows 1, 2, 3 (keys 13, 14, 15) | 1 | 3 | + +Key 2 is not in cluster 0: it is V's min. The summary and cluster 3 are vEB trees over u = 4 with the same rule. The summary keeps 0 as its min and stores 2 and 3 one level down (both in its cluster 1, since 2 = 10₂ and 3 = 11₂); cluster 3 keeps 1 as its min and stores 2 and 3 one level down. + +- `successor(9)`: 9 = 10 01₂, so h = 2 and l = 1. Cluster 2's max is 1, not larger than l, so nothing in cluster 2 follows 9. The summary is asked for `successor(2)` among the nonempty clusters {0, 2, 3} and answers 3. Cluster 3's min is 1, so the answer is 3 · 4 + 1 = **13**. +- `successor(4)`: h = 1, and cluster 1 does not exist. The summary's successor of 1 is 2, and cluster 2's min is 1, so the answer is 2 · 4 + 1 = **9**. The empty cluster was skipped without being looked at. + +Inside the summary, each query recursed once more on a universe of size 2 (into the summary's cluster 1 for `successor(2)`, into the summary's own summary for `successor(1)`) and stopped: one call per halving of the key length. + +The cache-oblivious layout of Section 24.6 carries van Emde Boas's name because it applies the same recursion to a tree's height instead of a key's bits. + +### x-Fast Tries + +Willard (1983) reached the same O(log log u) query time by a different route, and then fixed the space. + +Think of the keys as root-to-leaf paths in a complete binary trie of depth w: the path of x spells out its bits, most significant first, and the node at depth ℓ on that path is x's ℓ-bit prefix, x >> (w − ℓ). An ordinary binary trie finds where x's path leaves the set of stored paths by walking down, O(w) steps. The x-fast trie instead keeps, for each depth ℓ = 0, ..., w, a **hash table of the ℓ-bit prefixes of the keys in S**. Presence is monotone: if x's ℓ-bit prefix is present, so is every shorter prefix. So the length of x's longest present prefix can be found by **binary search over ℓ**, one hash lookup per step: O(log w) = O(log log u). + +The node p where x's path stops has one child (if it had both, the path would continue), and x would go into the missing one. If the missing child is on the right, every key below p is smaller than x and the largest of them is x's predecessor; if it is on the left, every key below p is larger and the smallest is x's successor. Willard stores a *descendant pointer* at each node with a missing child, pointing at exactly that leaf, and links the leaves into a sorted doubly linked list, so the other neighbour is one step away. The sketch below keeps the (min, max) of the keys below each node instead, which carries the same information: + +```python +def build_xfast(keys, w): + """levels[l] maps each l-bit prefix of a key to (min, max) of the keys below it.""" + levels = [{} for _ in range(w + 1)] + for x in keys: + for l in range(w + 1): + p = x >> (w - l) + lo, hi = levels[l].get(p, (x, x)) + levels[l][p] = (min(lo, x), max(hi, x)) + srt = sorted(keys) + nxt = dict(zip(srt, srt[1:] + [None])) # the leaves as a sorted linked list + return levels, nxt + +def xfast_successor(levels, nxt, w, x): + """Smallest key greater than x, or None.""" + if not levels[0]: + return None + lo, hi = 0, w # invariant: the prefix of length lo is present + while lo < hi: # binary search for the longest present prefix + mid = (lo + hi + 1) // 2 + if (x >> (w - mid)) in levels[mid]: + lo = mid + else: + hi = mid - 1 + if lo == w: # x itself is a key + return nxt[x] + mn, mx = levels[lo][x >> (w - lo)] + if (x >> (w - lo - 1)) & 1: # x leaves this node to the right of all its keys + return nxt[mx] + return mn # x leaves to the left of all its keys +``` + +Example: w = 4 and S = {2, 9, 13} = {0010, 1001, 1101}. + +| ℓ | prefixes present (min, max of the keys below) | +|---|---| +| 0 | ε (2, 13) | +| 1 | `0` (2, 2), `1` (9, 13) | +| 2 | `00` (2, 2), `10` (9, 9), `11` (13, 13) | +| 3 | `001`, `100`, `110` (one key each) | +| 4 | `0010`, `1001`, `1101` (the keys) | + +`successor(11)`, with 11 = 1011: start with lo = 0, hi = 4. Probe ℓ = 2: `10` is present, so lo = 2. Probe ℓ = 3: `101` is absent, so hi = 2. Two lookups locate node `10`. The next bit of 11 is 1, so 11 branches off to the right of everything under `10`, whose max is 9: 9 is the predecessor, and the next leaf in the list, **13**, is the successor. The code was checked against a sorted list on random sets for w from 1 to 32. + +Queries cost O(log w) hash lookups, expected. The cost is elsewhere: each key puts a prefix into each of the w + 1 tables, so the space is O(nw) = O(n log u) words, and an insert or delete must update w + 1 tables (and the min, max or descendant pointers along the path), which is O(w) = O(log u) expected. + +### y-Fast Tries + +The y-fast trie, in the same paper, removes the factor of w by **bucketing** (also called indirection). Split the sorted keys into buckets of between w/2 and 2w consecutive keys, store each bucket in a balanced BST, and give each bucket a **representative**: a value no larger than the bucket's smallest key and larger than every key in the previous bucket. Only the representatives go into an x-fast trie. That is Θ(n/w) representatives at O(w) words each, plus O(n) for the BSTs: **O(n) space**. + +- **successor(x):** find the largest representative ≤ x in the x-fast trie, O(log w). Search that bucket's BST for the successor of x, O(log w), since the bucket has O(w) keys. If nothing in the bucket is larger, the answer is the smallest key of the next bucket. (If no representative is ≤ x, it is the smallest key of the first bucket.) +- **insert / delete:** find the bucket the same way and update its BST, O(log w). When a bucket grows past 2w keys, split it and insert a new representative; when it falls below w/2, merge it with a neighbour, splitting the result again if it holds more than 3w/2 keys, and delete a representative. Each restructuring costs O(w), but it leaves every bucket involved with between about 3w/4 and 3w/2 keys, at least w/4 updates away from either limit, so it happens at most once per Ω(w) updates. Updates cost **O(log w) = O(log log u) amortized expected**. + +A representative is a boundary, not a key. Deleting the key equal to its bucket's representative leaves the representative where it is, so ordinary updates never touch the x-fast trie. + +Example, w = 4 (buckets of 2 to 8 keys): S = {1, 2, 3, 5, 8, 9, 12, 13, 14} in buckets {1, 2, 3, 5}, {8, 9, 12}, {13, 14} with representatives 0, 8 and 13. `successor(10)`: the largest representative ≤ 10 is 8, and the bucket {8, 9, 12} gives **12**. `successor(12)`: same bucket, nothing larger than 12, so the answer is the first key of the next bucket, **13**. Deleting 8 leaves the bucket {9, 12} with 2 = w/2 keys and representative 8, and the x-fast trie does not change. + +All queries in x-fast and y-fast tries are expected bounds because of the hash tables. With dynamic perfect hashing, lookups take O(1) worst case, which makes the queries worst-case O(log log u), while updates stay expected amortized. + +### Fusion Trees and Lower Bounds + +**Fusion trees** (Fredman and Willard, 1990) attack the other parameter. A fusion tree is a B-tree with fan-out B = w^(1/5). Seen as paths in the binary trie, the B keys of one node branch at fewer than B bit positions; keeping only those bits gives each key a short *sketch*, and all B sketches fit in one word. A constant number of multiplications, masks and subtractions compare a query's sketch against every sketch in the node at once, and one more constant-time step corrects for the bits the sketch throws away. Each node is searched in O(1), the height is log_B n = O(log n / log w), so a query takes **O(log_w n)** time, in O(n) space. + +Fusion trees win when w is large relative to log n; vEB and y-fast tries win when w is small. Taking whichever is better gives O(min(log_w n, log w)), which is always O(√(log n)): if log w ≥ √(log n) then log_w n = log n / log w ≤ √(log n), and otherwise log w < √(log n). Fredman and Willard used fusion trees to sort n integers in o(n log n) time, beating the comparison bound. + +**Lower bounds.** Is O(log log u) the end of the story? For static sets, Pătraşcu and Thorup (2006) gave the answer: for every combination of n, word size w and space, the optimal query time up to constant factors, as the minimum of four expressions (the first is the fusion-tree bound log_w n), with matching lower bounds in the cell-probe model (which bound every word-RAM algorithm too). The case most often quoted: for a polynomial universe (w = γ log₂ n for a constant γ > 1, so u = n^γ) and near-linear space (n · (log n)^O(1) words), the optimal query time is Θ(log w) = Θ(log log u), so van Emde Boas's bound cannot be improved there. In the same setting with n^(1+ε) words of space, Beame and Fich's structure answers in O(log w / log log w), and Pătraşcu and Thorup showed that this gap between near-linear and polynomial space is real. As a function of n alone, the best possible query time with polynomial space is Θ(√(log n / log log n)): Beame and Fich proved the lower bound, and Andersson and Thorup's exponential search trees match it dynamically, in linear space. + +### In Practice + +| Structure | Predecessor / successor | Insert / delete | Space (words) | +|-----------|-------------------------|-----------------|---------------| +| Sorted array | O(log n) worst | O(n) worst | n | +| Balanced BST, B-tree | O(log n) worst | O(log n) worst | O(n) | +| vEB tree, arrays | O(log log u) worst | O(log log u) worst | Θ(u) | +| vEB tree, hash tables | O(log log u) expected | O(log log u) expected amortized | O(n log log u) | +| x-fast trie | O(log log u) expected | O(log u) expected amortized | O(n log u) | +| y-fast trie | O(log log u) expected | O(log log u) expected amortized | O(n) | +| Fusion tree | O(log_w n) worst | static as described | O(n) | + +Here w = log₂ u is the word size. Min and max are O(1) in a vEB tree. + +On paper, O(log log u) = 6 for 64-bit keys against log₂ n ≈ 30 for a billion keys. In memory, the count of operations is the wrong measure. Each level of a hashed vEB tree or x-fast trie is a hash probe at an unpredictable address, which on a large set is a cache miss, and a y-fast query adds a walk down a BST of about 64 keys. A B-tree with 16 to 64 keys per node over 10⁹ keys is 5 to 8 levels deep, each level a few adjacent cache lines that are scanned quickly (Chapter 10); it also gives range scans by walking adjacent memory, works for any ordered key type, and is far simpler. The hashed structures also use more memory: about 39 hash entries per key for an x-fast trie on 10⁶ random 64-bit keys (Exercise 24.10). For a general-purpose ordered map, a well-tuned B-tree, or a sorted array for static data, usually matches or beats them. + +They pay off in specific places: + +- **Small or dense universes.** When u is small enough to spend u bits, the vEB idea becomes a hierarchy of bitmaps with fan-out w: each node is one word with a bit per child, and "next set bit" is a shift and a count-trailing-zeros instruction. With 64-bit words, 4 levels cover u = 2^24 in u(1 + 1/63) bits, with no hashing and no pointers. The Linux O(1) scheduler (kernel 2.6.0 until the Completely Fair Scheduler replaced it in 2.6.23) found the highest-priority nonempty run queue with a single-level version: a 140-bit bitmap of priority levels and a find-first-set instruction. Memory allocators and timer implementations use the same multi-level bitmap trick. +- **IP routing.** Longest-prefix match by binary search over prefix lengths, with one hash table per length (Waldvogel, Varghese, Turner and Plattner, 1997), is the x-fast trie's idea applied to routing tables. +- **Theory.** These structures are the basis of integer sorting and integer priority queues that beat comparison bounds, for example in Dijkstra's algorithm with integer edge weights. + +## 24.8 External Memory Data Structures ### External Memory Model @@ -162,7 +417,7 @@ Levels: L0, L1, L2, ..., L_k - Compaction merges sorted runs ``` -## 24.8 Fully Persistent Data Structures +## 24.9 Fully Persistent Data Structures ### Persistence Types @@ -189,7 +444,7 @@ class FatNode: setattr(self, field, new_value) ``` -## 24.9 Conflict-Free Replicated Data Types (CRDTs) +## 24.10 Conflict-Free Replicated Data Types (CRDTs) ### Conceptual Foundation @@ -223,7 +478,7 @@ class GCounter: | LWW-Register | Assign | Last-write-wins | | OR-Set | Add with tag, Remove | Tag-based | -## 24.10 Dynamic Graph Algorithms +## 24.11 Dynamic Graph Algorithms ### Holm-de Lichtenberg-Thorup (HDnT) @@ -246,7 +501,7 @@ class HDnTConnectivity: | Fully dynamic | O(n²) per update | | (1+ε)-approx | Near-linear | -## 24.11 String B-Trees +## 24.12 String B-Trees B-trees optimized for string keys: @@ -256,7 +511,7 @@ B-trees optimized for string keys: | Prefix search | O(log_B n + output) | | Range search | O(log_B n + output/B) | -## 24.12 Fractional Cascading +## 24.13 Fractional Cascading Accelerate searches in layered structures: @@ -273,7 +528,7 @@ def fractional_cascading_search(layers, query): **Speedup:** O(log n + k) vs O(Σ log n_i) -## 24.13 Melding Data Structures +## 24.14 Melding Data Structures Combine data structures efficiently: @@ -284,7 +539,7 @@ Combine data structures efficiently: | Leftist heap | O(log n) | | Skew heap | O(log n) amortized | -## 24.14 Research Frontiers +## 24.15 Research Frontiers ### Emerging Areas @@ -325,7 +580,7 @@ It is not succinct, for two reasons. The bits are a Python list (one object per -**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. +**24.2 ★ 2P-Set versus OR-Set.** Two replicas start empty. Replica A runs `add(x)` then `remove(x)`. Concurrently, replica B runs `add(x)`. The replicas then merge. Afterwards, A runs `add(x)` again. Using the table in Section 24.10, say whether `x` is in the set after the merge and after the re-add, (a) for a 2P-Set and (b) for an OR-Set.
Solution @@ -379,7 +634,7 @@ Real implementations usually prepend one `(` for a virtual super-root so that ev
-**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? +**24.4 ★★ Why the G-Counter converges, and why you cannot just decrement it.** (a) Show that the `merge` of Section 24.10 is commutative, associative and idempotent, and explain why that guarantees all replicas converge no matter how often or in what order they exchange state. (b) A developer adds `def decrement(self): self.counts[self.node_id] -= 1`. Replica A increments three times, sends its state to B (B merges), then decrements once, then merges B's state back. What does A report, and what should it report? (c) How do you get a counter that supports decrement?
Hint @@ -423,7 +678,7 @@ vEB order: 1 2 3 | 4 8 9 | 5 10 11 | 6 12 13 | 7 14 15
-**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? +**24.6 ★★ Read a fat node at a past time.** The `FatNode` of Section 24.9 logs every write as `(time, field, old, new)`, in increasing time order. Write `read(node, field, t)` that returns the value `node.` had after all writes with time ≤ t. What is its cost, and which row of the persistence table does this node support?
Hint @@ -536,6 +791,96 @@ Backward search needs only `C` and `occ`, never the text, which is why the FM-in
+**24.8 ★ The vEB recurrences.** (a) Solve T(u) = T(√u) + O(1) by substituting m = log₂ u, and count the levels of recursion for u = 2^32 and u = 2^64. (b) Suppose the clusters did not cache their max, so that `successor` first calls `successor` on x's cluster and, only if that returns `None`, calls `successor` on the summary. Write the recurrence for the worst case and solve it. (c) Show that the array-based version's space, S(u) = (√u + 1) · S(√u) + Θ(√u), is Θ(u). Take u = 2^(2^i) so that every square root is exact. + +
+Solution + +(a) Let S(m) = T(2^m). Since √(2^m) = 2^(m/2), the recurrence becomes S(m) = S(m/2) + c, which unrolls to c · log₂ m + S(1). So T(u) = O(log m) = O(log log u). For u = 2^32 the key lengths are 32, 16, 8, 4, 2, 1: six levels. For u = 2^64 there are seven. + +(b) In the worst case both calls happen: the cluster call runs all the way down and finds nothing, then the summary call runs. T(u) = 2T(√u) + O(1), so S(m) = 2S(m/2) + c, which is Θ(m) (the recursion tree has m leaves). That is T(u) = Θ(log u), no better than a balanced BST. The same thing happens to insert if the min is also stored in its cluster: inserting into an empty cluster would then recurse, so a new cluster would cost a full call on the summary and another on the cluster. The cached max and the "min lives only at the top" rule are each what keep the work to one call per level. + +(c) Lower bound: count the base structures (u = 2). L(u) = (√u + 1) · L(√u) ≥ √u · L(√u) with L(2) = 1, so for u = 2^(2^i), L(u) ≥ 2^(2^(i−1)) · 2^(2^(i−2)) ⋯ 2^1 = 2^(2^i − 1) = u/2. Upper bound: write the extra term as at most a√u and let s₀ = S(2). Claim S(u) ≤ cu − b with c = a + s₀ and b = c + a. The base case holds: 2c − b = 2a + 2s₀ − 2a − s₀ = s₀. For the inductive step, + +S(u) ≤ (√u + 1)(c√u − b) + a√u = cu − b + (c + a − b)√u ≤ cu − b, + +since c + a − b = 0. So S(u) = Θ(u). + +
+ +**24.9 ★★ Predecessor is not a mirror image.** Write `predecessor(V, x)`, the largest element of the `VEB` tree V smaller than x, or `None`. A natural first attempt mirrors `successor`: swap `min` with `max`, `<` with `>`, and `successor` with `predecessor`. Run that mirror on the u = 16 example of Section 24.7 for x = 3, 4 and 14, explain what goes wrong, and fix it. What is the running time of the fixed version? + +
+Hint + +Where does each structure keep its minimum? Successor never needs to look for a smaller element, so it never notices. + +
+ +
+Solution + +The mirror image returns `None` for x = 3 (the answer is 2) and for x = 4 (the answer is 3), and for x = 14 it crashes with a `TypeError` instead of returning 13. + +- x = 3: cluster 0 holds only low 3, so nothing smaller is in it; the summary has no nonempty cluster before 0; the mirror gives up. But V's min, 2, is in no cluster, so the clusters never mention it. +- x = 4: the summary is asked for its predecessor of 1. The summary's own min, cluster number 0, lives only at the summary's top, so the same bug one level down returns `None` instead of 0. +- x = 14: cluster 3 is asked for its predecessor of 2. Its min, 1, lives only at its top, its inner clusters hold 2 and 3, so the inner call returns `None` and `V.index(3, None)` fails. + +The fix: when no earlier nonempty cluster exists, the answer is the structure's own min, if that is smaller than x. + +```python +def predecessor(V, x): + """Largest element less than x, or None.""" + if V.max is not None and x > V.max: + return V.max + if V.k == 1: + return 0 if x == 1 and V.min == 0 else None + h, l = V.high(x), V.low(x) + c = V.clusters.get(h) + if c is not None and l > c.min: # answer is in x's own cluster + return V.index(h, predecessor(c, l)) + prev = predecessor(V.summary, h) if V.summary is not None else None + if prev is None: # no earlier cluster, but the min + if V.min is not None and x > V.min: # lives outside every cluster + return V.min + return None + return V.index(prev, V.clusters[prev].max) + +V = VEB(4) +for key in [2, 3, 9, 13, 14, 15]: + V.insert(key) +assert [predecessor(V, x) for x in (2, 3, 4, 10, 14, 15)] == [None, 2, 3, 9, 13, 14] +``` + +The fix adds an O(1) test and no recursive call, so predecessor is still one call on a universe of size √u plus O(1) work: O(log log u). (Checked against a sorted list on random sets for universes up to 2^12.) + +
+ +**24.10 ★★ x-fast and y-fast tries by hand.** (a) For w = 4 and S = {3, 4, 10, 12}, list the prefixes stored at each level of the x-fast trie and count the hash-table entries. (b) Find the successor and predecessor of 9 by binary search over prefix lengths. Which prefixes are probed? (c) Estimate the number of hash-table entries for n = 10⁶ random 64-bit keys in an x-fast trie, and in a y-fast trie whose buckets hold 64 keys on average. + +
+Solution + +(a) In binary, 3 = 0011, 4 = 0100, 10 = 1010, 12 = 1100. + +| ℓ | prefixes | +|---|---| +| 0 | ε | +| 1 | `0`, `1` | +| 2 | `00`, `01`, `10`, `11` | +| 3 | `001`, `010`, `101`, `110` | +| 4 | `0011`, `0100`, `1010`, `1100` | + +That is 1 + 2 + 4 + 4 + 4 = 15 entries, fewer than n(w + 1) = 20 because keys share prefixes near the root. + +(b) 9 = 1001. Start with lo = 0, hi = 4. Probe ℓ = 2: `10` is present, lo = 2. Probe ℓ = 3: `100` is absent, hi = 2. The search stops at node `10` after two probes. Its only child is `101` (key 10), and the next bit of 9 is 0, so 9 branches off to the left of every key under `10`: the successor is that subtree's min, **10**, and the predecessor is the leaf before 10 in the linked list, **4**. + +(c) Level ℓ holds at most min(2^ℓ, n) prefixes. For random keys, the levels down to about ℓ = 20 (2^20 ≈ 10⁶) are nearly full and the deeper ones hold nearly n prefixes each. The expected total is Σ over ℓ = 0..64 of 2^ℓ (1 − (1 − 2^−ℓ)^n) ≈ 39 million entries, about 39 per key. At a prefix plus two words per entry that is close to a kilobyte per key before any hash-table overhead. + +The y-fast trie puts only the 10⁶ / 64 ≈ 15,600 representatives in its x-fast trie. The same sum with n = 15,625 gives about 0.7 million entries, plus 10⁶ BST nodes for the buckets: under two stored items per key. Dividing the x-fast trie's population by w is exactly what turns O(nw) space into O(n). + +
+ --- ## Where this connects 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 0c44efd..1ed855b 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 @@ -27,6 +27,207 @@ Inverted index (term → docs): **Posting list**: Each term points to a sorted list of document IDs. +Real postings carry more than the ID: the term frequency in that document (BM25 needs it, below) and often the positions of each occurrence (for phrase queries). The ID part is the hard part to make small and fast, and the rest of this section is about it: how the lists are compressed, how two of them are intersected, how the best k documents are found without scoring every match, and how an index made of immutable compressed lists absorbs inserts and deletes. + +### Compressing Posting Lists + +A common term in a large index has a posting list of hundreds of millions of doc IDs, and a query reads every posting it touches. Stored as 32-bit integers, most of those bits are wasted, because the list is sorted: the information is in the distance from one ID to the next. + +**Step 1: d-gaps (delta encoding).** Replace each ID by its difference from the previous one, keeping the first as it is. The gaps of a list sum to its last ID, so a term that appears in a fraction f of the documents has an average gap of about 1/f: a term in 10% of documents has gaps around 10, which fit in 4 bits. Rare terms have large gaps, but their lists are short, so they cost little either way. Decoding is a running sum, which means a list can only be decoded forward from a known starting point (its beginning, or a block boundary recorded in the skip data below). + +**Step 2: variable-byte (varint) encoding.** Write each gap 7 bits at a time, lowest-order group first, and use the top bit of each byte as a continuation flag: 1 means another byte of this number follows, 0 means this is the last. Values below 128 take one byte, below 16,384 two, below 2,097,152 three. This is the layout of Lucene's VInt, the varint of Protocol Buffers, and LEB128 in DWARF and WebAssembly. (The variable-byte code in Manning, Raghavan and Schütze's *Introduction to Information Retrieval* puts the flag on the last byte instead and writes the high-order group first; the idea and the sizes are the same.) + +
+{{#include ../images/posting-list-compression.svg}} +
Delta encoding turns large sorted IDs into small gaps, and varint stores each gap in as few bytes as it needs: 9 bytes instead of 20.
+
+ +The worked example in the figure: the term "data" occurs in documents 70000, 70003, 70010, 70130 and 90000. The gaps are 70000, 3, 7, 120 and 19870. The first gap is 17 bits, `100 0100010 1110000` in binary, so it splits into three 7-bit groups; emitted lowest first with the flag prepended, they are `1·1110000` = F0, `1·0100010` = A2 and `0·0000100` = 04. The gaps 3, 7 and 120 are below 128 and take one byte each (03, 07, 78), and 19870 takes three (9E 9B 01). Total: 9 bytes, against 20 as 32-bit integers and 15 as varints of the raw IDs, since every raw ID here is at least 16,384. + +```python +from itertools import accumulate + + +def delta_encode(doc_ids, base=0): + """Sorted doc IDs -> d-gaps. The first gap is measured from `base`.""" + return [d - p for p, d in zip([base] + doc_ids, doc_ids)] + + +def delta_decode(gaps, base=0): + return list(accumulate(gaps, initial=base))[1:] + + +def varint_encode(numbers): + """7 data bits per byte, low-order group first; a set high bit means 'more bytes follow'.""" + out = bytearray() + for n in numbers: + while n >= 0x80: + out.append((n & 0x7F) | 0x80) + n >>= 7 + out.append(n) + return bytes(out) + + +def varint_decode(data): + numbers, n, shift = [], 0, 0 + for byte in data: + n |= (byte & 0x7F) << shift + if byte & 0x80: + shift += 7 + else: + numbers.append(n) + n, shift = 0, 0 + return numbers + + +postings = [70000, 70003, 70010, 70130, 90000] +gaps = delta_encode(postings) +assert gaps == [70000, 3, 7, 120, 19870] +encoded = varint_encode(gaps) +assert encoded.hex(" ") == "f0 a2 04 03 07 78 9e 9b 01" +assert len(encoded) == 9 and len(varint_encode(postings)) == 15 # vs 20 bytes as int32 +assert delta_decode(varint_decode(encoded)) == postings +``` + +Encoding and decoding are O(total bytes), linear in the list. A 32-bit gap takes at most 5 bytes. + +**Bit-packing in blocks.** Varint has two weaknesses: it cannot use less than a byte (a gap of 3 still takes 8 bits), and its decoder takes a data-dependent branch on every byte, which the CPU mispredicts often when gap sizes vary. Modern engines instead cut the gap sequence into fixed-size blocks and pack each block at one bit width b, the width of the block's largest gap. A block of 128 gaps then takes exactly 16b bytes, and unpacking it is straight-line shifts and masks with no branches, which compilers unroll and vectorize with SIMD instructions. This is **frame-of-reference (FOR)** coding: each value is stored as a fixed-width offset from a per-block reference value; for d-gaps the reference is 0 and the choice of b is the whole scheme. Its weakness is outliers: one large gap forces every value in the block to the wide width. **PForDelta** ("patched" FOR, Zukowski, Héman, Nes and Boncz, 2006) picks b so that most of the block fits, say 90%, and stores the few values that do not fit as exceptions that are patched in after the fast unpacking pass. Lucene's postings format packs doc-ID gaps in blocks of 128 at one bit width per block, uses patched FOR for the term frequencies, and writes the final partial block of fewer than 128 entries as VInts. + +```python +def for_pack(block): + """Frame of reference: every value in the block is stored in the same b bits.""" + b = max(block).bit_length() + packed = 0 + for i, v in enumerate(block): + packed |= v << (i * b) + return b, packed.to_bytes((len(block) * b + 7) // 8, "little") + + +def for_unpack(b, data, count): + packed, mask = int.from_bytes(data, "little"), (1 << b) - 1 + return [(packed >> (i * b)) & mask for i in range(count)] + + +block = [3, 7, 1, 12, 5, 2, 9, 4] * 16 # 128 small gaps +b, data = for_pack(block) +assert (b, len(data)) == (4, 64) # 4 bits each: 64 bytes +assert for_unpack(b, data, len(block)) == block +b, data = for_pack(block[:-1] + [19870]) # one outlier... +assert (b, len(data)) == (15, 240) # ...and all 128 values pay 15 bits +``` + +The Python uses one arbitrary-precision integer as the bit buffer to stay short; real implementations shift values into 64-bit words, and Lucene generates a specialized unpacking routine for each width b. + +**Why compression makes queries faster, not only smaller.** Intersecting or scoring a posting list does a few instructions per doc ID, so a scan over uncompressed IDs is limited by how fast bytes arrive from memory or disk, not by the CPU. Compression spends a few cheap instructions per ID to move several times fewer bytes, and lets more of the index stay in the CPU caches and in RAM (the operating system's page cache, for an index on disk). Block bit-packing decoders run at billions of integers per second per core (Lemire and Boytsov, "Decoding billions of integers per second through vectorization", 2015), so decoding costs less than the memory traffic it saves, and the smaller list is also the faster one. This is the memory-hierarchy argument of [Chapter 16](../volume-3/ch16-external-memory-and-cache-oblivious-structures.md) applied to lists of integers. + +### Intersecting Posting Lists + +An AND query ("fibonacci AND heap") needs the doc IDs that appear in every query term's list. Exercise 30.1 builds the **linear merge**: two pointers walk both sorted lists, always advancing the one at the smaller ID, for O(m + n) comparisons in the worst case. That is the right algorithm when the lists have similar lengths and the wrong one when they do not: for "fibonacci AND the", with m = 1,000 and n = 10,000,000 postings, the merge reads the entire long list to find at most 1,000 matches. + +**Galloping (exponential) search.** Walk the short list, and for each element x, search the long list forward from where the previous search stopped: probe positions lo, lo + 1, lo + 3, lo + 7, ..., doubling the step, until a probe reaches a value ≥ x, then binary-search the last interval (Bentley and Yao, 1976, proposed this doubling search for unbounded lists). + +```python +from bisect import bisect_left + + +def gallop_to(arr, target, lo=0): + """Smallest i >= lo with arr[i] >= target, or len(arr). + Probes lo, lo+1, lo+3, lo+7, ... then binary-searches the last gap.""" + hi, step = lo, 1 + while hi < len(arr) and arr[hi] < target: + lo = hi + 1 # everything before lo is < target + hi += step + step *= 2 + return bisect_left(arr, target, lo, min(hi, len(arr))) + + +def intersect_gallop(short, long): + """Each element of `short` gallops forward from where the last one stopped.""" + out, pos = [], 0 + for x in short: + pos = gallop_to(long, x, pos) + if pos == len(long): + break + if long[pos] == x: + out.append(x) + return out + + +def intersect_all(lists): + """AND query: start from the rarest term; the candidate set only shrinks.""" + lists = sorted(lists, key=len) + result = lists[0] + for other in lists[1:]: + if not result: + break + result = intersect_gallop(result, other) + return result + + +long = [2, 5, 9, 12, 17, 21, 30, 44, 51, 63, 70, 88, 95, 120] +assert gallop_to(long, 63) == 9 # probes 0, 1, 3, 7 (15 is past the end), then bisects [8, 14) +assert intersect_all([long, [9, 63, 64], list(range(0, 100, 3))]) == [9, 63] +``` + +In the test, searching for 63 probes indices 0, 1, 3 and 7 (values 2, 5, 12, 44, all below 63), the next probe 15 is past the end, so it binary-searches indices 8 to 13 and stops at index 9. + +**Cost.** Say the search for the i-th element of the short list moves the long-list position forward by g_i. Doubling reaches past that distance in about log₂ g_i probes, and the binary search over the last interval, of length below g_i, takes about log₂ g_i more, so the search costs O(1 + log g_i). The g_i sum to at most n, and since log is concave, a sum of m logarithms with a fixed total is largest when all the terms are equal, at n/m. The total is O(m log(n/m) + m) comparisons in the worst case. For m = 1,000 and n = 10⁷ that is about 1,000 × 2 × log₂(10⁴) ≈ 27,000 comparisons instead of 10⁷. When m ≈ n the gaps are tiny, each search is a probe or two, and galloping costs O(n), within a small constant factor of the merge, so it never loses badly. + +**Shortest list first.** With more than two terms, `intersect_all` sorts the lists by length and folds the result through them. The running result can never be longer than the shortest list, so every step is a short list galloping through a longer one. The lengths are free: the term dictionary stores each term's document frequency, because BM25 needs it as n. + +**Skip pointers.** Galloping assumes random access, and a compressed list does not have it: varints have variable length, and d-gaps decode only as a running sum from a known starting point. The fix is **skip data**: for every block of B postings, record the block's last doc ID and the byte offset where the block starts. To advance to a target x, search the small, uncompressed array of skip entries, jump to the one block that can contain x, and decode only that block. Blocks with no candidate are never decoded at all. Moffat and Zobel (1996) placed skips every √n postings or so; in block-packed formats the skip interval is simply the block size, and Lucene interleaves skip data with its 128-posting blocks, with a second, coarser level above it. + +```python +from bisect import bisect_left + + +class CompressedPostings: + """Doc IDs as varint d-gaps in blocks of `block`, plus one skip entry per + block: the block's last doc ID and the byte offset where it starts.""" + + def __init__(self, doc_ids, block=128): + self.data, self.last_docs, self.offsets = bytearray(), [], [] + prev = 0 + for i in range(0, len(doc_ids), block): + chunk = doc_ids[i:i + block] + self.offsets.append(len(self.data)) + self.data += varint_encode(delta_encode(chunk, base=prev)) + prev = chunk[-1] + self.last_docs.append(prev) + self.offsets.append(len(self.data)) + self.blocks_decoded = 0 + + def decode_block(self, k): + self.blocks_decoded += 1 + base = self.last_docs[k - 1] if k else 0 + raw = self.data[self.offsets[k]:self.offsets[k + 1]] + return delta_decode(varint_decode(raw), base) + + def intersect(self, short): + """Decode only the blocks that could hold an element of `short`.""" + out, k, block_no, docs = [], 0, -1, [] + for x in short: + k = bisect_left(self.last_docs, x, k) # skip whole blocks + if k == len(self.last_docs): + break + if k != block_no: + block_no, docs = k, self.decode_block(k) + i = bisect_left(docs, x) + if docs[i] == x: + out.append(x) + return out + + +common = list(range(0, 1_000_000, 3)) # in a third of all documents +rare = [7, 300_000, 300_003, 999_999] # in four documents +pl = CompressedPostings(common) +assert pl.intersect(rare) == [300_000, 300_003, 999_999] +assert len(pl.data) == 333_334 # 1 byte per gap, vs 1,333,336 as int32 +assert len(pl.last_docs) == 2605 and pl.blocks_decoded == 3 +``` + +The rare term's four IDs cost four searches of the skip array and three block decodes out of 2,605 blocks (300,000 and 300,003 share a block); the other 2,602 blocks are never decoded. With m short-list elements, the cost is O(m log(n/B)) for the skip searches (less if they gallop over the skip array instead of calling `bisect`) plus O(B) for each decoded block, and at most min(m, n/B) blocks are decoded. The `len(pl.data)` assertion is the compression side of the same example: a term in every third document out of a million has gaps of 3, one byte each, so the list takes a quarter of its 32-bit size. + ### BM25 Scoring Probabilistic relevance ranking: @@ -42,6 +243,108 @@ Where: - IDF = log((N - n + 0.5) / (n + 0.5)) ``` +### Top-k Retrieval: WAND and Block-Max WAND + +A search page shows the k best documents by score, not every match, and for an OR query ("fibonacci heap data") nearly every document matches some term. Exhaustive evaluation scores every document in the union of the posting lists and keeps the best k in a size-k min-heap, the top-k pattern of [Chapter 9](../volume-1/ch09-heaps-and-priority-queues.md) §9.8. Its cost is proportional to the total length of all the lists, and that total is dominated by the common terms, which contribute least to any score. + +The heap supplies the key quantity: the score θ of the current k-th best document, at its root. A new document matters only if it scores more than θ. **WAND** ("weak AND", Broder, Carmel, Herscovici, Soffer and Zien, 2003) adds one number per term, computed at index time: the upper bound UB_t, the largest score contribution term t makes to any document. (BM25's contribution is bounded for each term; Exercise 30.2(a) computes the limit.) A document's score is at most the sum of UB_t over the terms whose lists contain it. WAND keeps one cursor per term, pointing at its current doc ID, and repeats: + +1. Sort the cursors by current doc ID. +2. Add up UB_t in that order until the sum exceeds θ. The cursor where that happens is the pivot, and its doc ID is the pivot document p. If no prefix exceeds θ, stop: no remaining document can enter the top k. +3. A document d < p can only appear in the lists of cursors before the pivot (every other cursor is already past d), and those bounds sum to at most θ. So no document before p can qualify. If some cursors are still before p, move them directly to p, using skip pointers, so the postings in between are never decoded. +4. Otherwise every cursor up to the pivot is on p: score p in full, and push it into the heap if it beats θ. + +The answer is exactly the exhaustive top k, not an approximation, because WAND only skips documents it has proved cannot qualify. As the heap fills with good documents θ rises, and more is skipped. + +```python +import heapq +from bisect import bisect_left + + +def wand_top_k(index, k): + """index: term -> (doc_ids, scores), the term's posting list with each + document's precomputed score contribution. Returns the top k (score, doc).""" + ub = {t: max(sc) for t, (_, sc) in index.items()} # stored at index time + pos = {t: 0 for t in index} + heap = [] # min-heap of (score, doc) + fully_scored = 0 + + def cur(t): + docs = index[t][0] + return docs[pos[t]] if pos[t] < len(docs) else float("inf") + + while True: + theta = heap[0][0] if len(heap) == k else float("-inf") + terms = sorted(index, key=cur) + pivot, bound = None, 0.0 + for t in terms: # smallest prefix that could beat theta + if cur(t) == float("inf"): + break + bound += ub[t] + if bound > theta: + pivot = cur(t) + break + if pivot is None: + break # no remaining document can enter the top k + if cur(terms[0]) == pivot: # every term up to the pivot is on it + score = 0.0 + for t in terms: + if cur(t) == pivot: + score += index[t][1][pos[t]] + pos[t] += 1 + fully_scored += 1 + if len(heap) < k: + heapq.heappush(heap, (score, pivot)) + elif score > theta: + heapq.heapreplace(heap, (score, pivot)) + else: # nothing before the pivot can win: skip + for t in terms: + if cur(t) < pivot: + pos[t] = bisect_left(index[t][0], pivot, pos[t]) + return sorted(heap, reverse=True), fully_scored + + +index = { + "fibonacci": ([3, 9], [4.0, 3.5]), + "heap": ([1, 3, 5, 7, 9, 11], [1.5, 2.0, 1.0, 1.8, 1.2, 2.0]), + "data": (list(range(1, 13)), [0.5] * 12), +} +top, fully_scored = wand_top_k(index, k=2) +assert top == [(6.5, 3), (5.2, 9)] and fully_scored == 6 # docs 1, 2, 3, 5, 7, 9 +``` + +The trace of that example, with k = 2: + +| term | doc IDs | score contribution | UB | +|---|---|---|---| +| fibonacci | 3, 9 | 4.0, 3.5 | 4.0 | +| heap | 1, 3, 5, 7, 9, 11 | 1.5, 2.0, 1.0, 1.8, 1.2, 2.0 | 2.0 | +| data | 1 to 12 | 0.5 each | 0.5 | + +Docs 1 (score 2.0) and 2 (0.5) fill the heap, so θ = 0.5. Doc 3 scores 6.5 and evicts doc 2: θ = 2.0. The cursors are now data at 4, heap at 5, fibonacci at 9. The bound of data alone is 0.5 ≤ 2.0, data plus heap is 2.5 > 2.0, so the pivot is heap's cursor and p = 5: data jumps from 4 to 5, and doc 4 is never scored (it contains only "data", worth at most 0.5). Doc 5 scores 1.5 and does not get in. Doc 6 is skipped the same way, doc 7 scores 2.3 and evicts doc 1 (θ = 2.3), doc 8 is skipped, and doc 9 scores 5.2 (θ = 5.2). Now fibonacci is exhausted and data plus heap is 2.5 ≤ 5.2: no remaining document can reach the top 2, so WAND stops. It fully scored 6 of the 12 matching documents; docs 10, 11 and 12 were never touched, although doc 11 matches two of the three terms. + +**Block-max WAND.** The weakness of WAND is that UB_t is a maximum over the whole list: if "heap" scores 2.0 in one document, every "heap" posting looks as if it could be worth 2.0. Block-max WAND (Ding and Suel, 2011) also stores the maximum score within each block of postings, next to that block's skip entry. After WAND picks a pivot with the global bounds, it adds up the block maxima of the blocks containing p in the pivot terms' lists. If that tighter bound is still ≤ θ, no document from p up to the nearest of those block ends (or up to the next cursor after the pivot, if that comes first) can qualify, so the cursors skip there without decoding anything. Lucene 8.0 (2019) added block-max WAND, storing per-block "impacts" in the skip data (the competitive pairs of term frequency and document length, from which a block's maximum BM25 score follows). The price of skipping is that the engine no longer knows the exact number of matching documents; Elasticsearch 7.0 changed its default to count hits exactly only up to 10,000 for this reason. + +WAND has no better worst-case bound than exhaustive evaluation: if every document scores close to θ, nothing can be skipped. Its gains depend on the score distribution, and on real queries, where a few documents score far above the rest, θ rises fast and most postings of the common terms are skipped. + +### Segments, Merging, and Deletes + +Everything so far describes a static index: sorted, compressed, block-packed lists with skip data and block maxima. That layout cannot absorb an insert in the middle of a packed block. Lucene's answer (and so that of Elasticsearch, OpenSearch and Solr, which are built on it) is the same as the LSM tree's in [Chapter 29](ch29-system-design-as-data-structure-composition.md) §29.4 and [Chapter 16](../volume-3/ch16-external-memory-and-cache-oblivious-structures.md) §16.4: never modify anything in place; write new immutable pieces and merge them in the background. + +- **Segments.** A segment is a complete, self-contained inverted index over a subset of the documents: its own term dictionary, compressed posting lists and stored fields, with doc IDs 0 to n − 1 local to the segment. Dense local IDs are also what keeps the d-gaps small. New documents are buffered in memory and flushed as a new, small segment; in Elasticsearch this is the refresh, every second by default, which is what makes a new document searchable within a second ("near-real-time" search). A query runs against every segment and combines the per-segment results; a document's global ID is its segment's base offset plus its local ID. +- **Deletes as bitsets.** A segment's files are never rewritten, so a delete cannot remove postings. Instead each segment has a live-docs bitset ([Chapter 3](../volume-1/ch03-arrays-the-foundation-of-contiguous-storage.md) §3.5) with one bit per document, written as a new generation of a small file when deletes arrive. Queries still decode the postings of deleted documents and drop them with one bit test each. An update is a delete of the old version plus an add of the new one, which lands in a new segment. +- **Merging.** A background merge reads several segments and writes one. It merges their sorted term dictionaries (a k-way merge, [Chapter 9](../volume-1/ch09-heaps-and-priority-queues.md) §9.8), and for each term concatenates the posting lists while renumbering doc IDs: each source segment's documents get a new base offset, deleted documents are dropped, and later IDs shift down to fill the holes. Each source segment's documents become one contiguous range of IDs in the result, so the concatenated lists are already sorted and the merge is a single sequential pass, linear in the size of its input. Lucene's default `TieredMergePolicy` merges segments of similar size (by default it tolerates about 10 segments per size tier), so each document is rewritten a logarithmic number of times over the life of the index, as in a size-tiered LSM tree, and it favors segments with many deletions, because a merge is the only way to reclaim their space. + +| LSM tree (Chapter 29) | Lucene index | +|---|---| +| memtable | in-memory indexing buffer | +| immutable SSTable | immutable segment | +| compaction | segment merge | +| delete = tombstone written to a newer run | delete = bit cleared in the live-docs bitset of the segment that holds the document | +| point read checks runs newest first and can stop early | every query visits every segment | + +The last two rows differ because of the access pattern. A key-value read wants the newest version of one key, so an LSM tree records a delete as a tombstone in the newest run and resolves versions at read time. A search reads all the matching documents in all the segments anyway, so Lucene resolves the delete once, when the buffered deletes are applied, by finding the document in the older segments and clearing its bit; after that a query needs only a bit test and never compares versions across segments. The cost pressure differs too: an LSM point read can stop at the first run that holds the key (and skip most runs with Bloom filters), but a search pays for every segment on every query. Keeping the segment count small is therefore as much about query latency as about disk space, and an index that will not change again is often force-merged down to a single segment. + ### Fenced and Sharded Indexes **Sharding by document**: Different shards contain different documents. Parallel query all shards, merge results. @@ -522,6 +825,86 @@ Exact rollups: count, sum, min and max combine exactly (add, add, min, max), and +**30.8 ★ Compress a posting list by hand.** A term occurs in documents 5, 130, 131 and 16515. (a) Write the d-gaps and their varint bytes in hex, using the encoding of §30.1. How many bytes is that, against 32-bit integers and against varints of the raw IDs? (b) Pack the four gaps as one frame-of-reference block. What bit width does the block need, and how many bytes? (c) What would PForDelta do with this block? + +
+Hint + +16,384 is 2¹⁴, the smallest number that needs a third varint byte. + +
+ +
+Solution + +(a) The gaps are 5, 125, 1 and 16384. 5, 125 and 1 are below 128, so they take one byte each: 05, 7D, 01. 16384 = 2¹⁴ is `1 0000000 0000000` in binary, three 7-bit groups; lowest first with continuation flags, that is 80 80 01. Total 6 bytes, against 16 as 32-bit integers. The raw IDs as varints are 05, 82 01, 83 01, 83 81 01, 8 bytes: 130 and 131 need two bytes and 16515 three. + +(b) The width is that of the largest gap: 16384 needs 15 bits, so 4 × 15 = 60 bits, 8 bytes, worse than varint. The other three gaps need at most 7 bits (125 < 128) but pay for the outlier. + +(c) PForDelta picks the width that fits most of the block, here 7 bits: 4 × 7 = 28 bits, 4 bytes, and records 16384 separately as an exception (its position in the block and its value), patched in after the block is unpacked. On a real block of 128 gaps a single exception costs a few bytes, while widening the whole block from 7 to 15 bits would cost 128 extra bytes. + +```python +# Checked with the functions from §30.1 +assert varint_encode(delta_encode([5, 130, 131, 16515])).hex(" ") == "05 7d 01 80 80 01" +assert len(varint_encode([5, 130, 131, 16515])) == 8 +assert for_pack([5, 125, 1, 16384])[0] == 15 and for_pack([5, 125, 1])[0] == 7 +``` + +
+ +**30.9 ★★ When does galloping pay?** (a) Intersect a list of m = 1,000 doc IDs with one of n = 10,000,000. Estimate the comparisons for the linear merge and for galloping. (b) Prove the O(m log(n/m) + m) bound from §30.1 for the case where every one of the m searches advances the long-list position by the same amount, and explain why unequal advances cannot cost more. (c) When the two lists have about the same length, which method is faster in practice, and how do implementations choose between them? + +
+Solution + +(a) The merge advances one of the two pointers on every comparison and can end only when one list runs out, so it does up to m + n ≈ 10⁷ comparisons (it may stop early if the short list's last element is small, but in general it reads most of the long list). Galloping does about 2 log₂(n/m) = 2 log₂(10⁴) ≈ 27 comparisons per element of the short list, about 27,000 in total: a 370-fold reduction. + +(b) If every search advances the position by g = n/m, each search costs about log₂ g probes to overshoot and log₂ g more to binary-search the last interval, so the total is about 2m log₂(n/m), plus O(1) per element for the first probe. With unequal advances g₁, ..., g_m summing to at most n, the cost is Σ O(1 + log g_i). Since log is concave, Jensen's inequality gives (1/m) Σ log g_i ≤ log((1/m) Σ g_i) ≤ log(n/m), so Σ log g_i ≤ m log(n/m): spreading the same total distance unevenly can only lower the sum of logs. + +(c) The merge. When n ≈ m the gaps are about 1, so galloping does O(1) work per element and has the same O(n) bound, but each search still costs a probe or two plus the loop and `bisect` setup, while the merge does one comparison and one pointer increment per step. Both are linear, and the merge has the smaller constant. Implementations choose by the length ratio: merge when the lists are close in size, gallop when one is much shorter. (Python's `list.sort` uses the same idea in reverse: its merge switches into galloping mode once one run keeps winning.) Search engines rarely face this choice on raw arrays; they advance through compressed blocks with skip data, and the shortest-list-first rule keeps the driving list short. + +
+ +**30.10 ★★ Merge two segments.** Represent a segment as `(postings, live)`, where `postings` maps each term to its sorted local doc IDs and `live` is a list of booleans, one per document (False means deleted). Write `merge_segments(segments)` that returns the postings of a single merged segment containing only live documents, with IDs renumbered 0, 1, 2, ... in segment order, plus the merged document count. Test it on segment A with `{"data": [0, 1, 2], "heap": [1]}`, live `[True, False, True]`, and segment B with `{"data": [1], "trie": [0, 1]}`, live `[True, True]`. Why does no posting list need re-sorting? + +
+Solution + +```python +def merge_segments(segments): + """segments: list of (postings, live) with postings: term -> sorted local + doc IDs and live: list of bools, one per document in the segment. + Returns the postings of one merged segment with no deleted documents.""" + remaps, base = [], 0 + for _, live in segments: + remap = {} + for local, alive in enumerate(live): + if alive: + remap[local] = base + base += 1 + remaps.append(remap) + merged = {} + for (postings, _), remap in zip(segments, remaps): # segment order = ID order + for term, docs in postings.items(): + new_ids = [remap[d] for d in docs if d in remap] + if new_ids: + merged.setdefault(term, []).extend(new_ids) + return dict(sorted(merged.items())), base + + +seg_a = ({"data": [0, 1, 2], "heap": [1]}, [True, False, True]) +seg_b = ({"data": [1], "trie": [0, 1]}, [True, True]) +merged, n_docs = merge_segments([seg_a, seg_b]) +assert n_docs == 4 +assert merged == {"data": [0, 1, 3], "trie": [2, 3]} # "heap" only had a deleted doc +``` + +The remap gives A's live documents 0 and 2 the new IDs 0 and 1, and B's documents 0 and 1 the IDs 2 and 3. Deleted document A1 gets no new ID, so its postings disappear, and "heap", which occurred only there, disappears from the merged dictionary: this is how a merge reclaims the space of deletes. + +No list needs re-sorting because the renumbering preserves order twice over: within a segment, the remap is increasing (later live documents get larger IDs), and across segments, every ID from A is smaller than every ID from B. So appending each segment's remapped list in segment order produces a sorted list, and the whole merge is one sequential pass over the inputs, O(total postings + total documents). A real merge also streams the term dictionaries in sorted order (a k-way merge of the segments' sorted term lists) instead of building a dictionary and sorting it at the end, and writes the merged lists straight into compressed blocks. + +
+ --- ## Where this connects diff --git a/src/volume-5/ch31-real-world-case-studies.md b/src/volume-5/ch31-real-world-case-studies.md index b6058e4..412dea7 100644 --- a/src/volume-5/ch31-real-world-case-studies.md +++ b/src/volume-5/ch31-real-world-case-studies.md @@ -83,7 +83,7 @@ Partition heals. Neither vector dominates the other Dynamo pushes reconciliation to the application, and for a shopping cart the resolution is a set union, which is why a deleted item famously sometimes reappears. That is the visible cost of choosing availability, and it is a deliberate trade, not a bug. -**Merkle trees** solve the other problem: detecting divergence without comparing everything. Each replica hashes its key range into a tree; two replicas compare root hashes, and if they match (the common case)they are identical and nothing more transfers. If they differ, they descend only into subtrees whose hashes disagree. Comparing two replicas of a million keys with one difference takes about 20 hash comparisons instead of a million. The same structure, for the same reason, is how Git compares trees and how BitTorrent verifies pieces. +**Merkle trees** solve the other problem: detecting divergence without comparing everything. Each replica hashes its key range into a tree; two replicas compare root hashes, and if they match (the common case) they are identical and nothing more transfers. If they differ, they descend only into subtrees whose hashes disagree. Comparing two replicas of a million keys with one difference takes about 20 hash comparisons instead of a million. The same structure, for the same reason, is how Git compares trees and how BitTorrent verifies pieces. **Structures in play**: consistent hashing with virtual nodes ([Chapter 27](ch27-distributed-data-structures.md)), vector clocks, Merkle trees, and per-node LSM or B-tree storage. Dynamo's design became DynamoDB, Cassandra, Riak, and Voldemort. @@ -146,7 +146,7 @@ Delta Lake solves a problem created by cloud object storage: S3 gives cheap, dur The fix is to stop treating the file listing as the source of truth. **The transaction log is the table**; the Parquet files are just content addressed by it. A reader replays the log to compute the current file set, and a file not named in the log does not exist as far as the table is concerned, so a failed job leaves orphaned files that are simply invisible, rather than corruption. -This makes the table state a **persistent data structure** in exactly the sense of [Chapter 17](../volume-3/ch17-persistent-data-structures.md): each log entry produces a new version, old versions remain valid, and unchanged files are shared between them. "Time travel" (querying the table as of last Tuesday)is not a feature bolted on but a direct consequence of the representation. +This makes the table state a **persistent data structure** in exactly the sense of [Chapter 17](../volume-3/ch17-persistent-data-structures.md): each log entry produces a new version, old versions remain valid, and unchanged files are shared between them. "Time travel" (querying the table as of last Tuesday) is not a feature bolted on but a direct consequence of the representation. Replaying the entire log would get slow, so Delta periodically writes a **checkpoint** (a Parquet file holding the full state at version N), and readers start from the newest checkpoint and replay only the entries after it. This is the same log-plus-snapshot pattern used by Raft, Redis AOF with RDB, and every event-sourced system in [Chapter 30](ch30-advanced-system-patterns-and-case-studies.md). @@ -190,7 +190,7 @@ Two structural ideas do most of the work here. The origin shield exists for a specific failure mode: without it, a popular object expiring simultaneously across 300 edge PoPs sends 300 requests to the origin at once, a **thundering herd**. The shield collapses them into one. The general technique is *request coalescing*: concurrent misses for the same key wait on a single in-flight fetch rather than each issuing their own. -**Cache key design is where correctness lives.** Include too much in the key (a tracking parameter, a session cookie)and the hit rate collapses because every request is unique. Include too little and users are served each other's content, which is a security incident rather than a performance problem. The `Vary` header is the standard mechanism, and getting it wrong is one of the more common ways to leak data between users. +**Cache key design is where correctness lives.** Include too much in the key (a tracking parameter, a session cookie) and the hit rate collapses because every request is unique. Include too little and users are served each other's content, which is a security incident rather than a performance problem. The `Vary` header is the standard mechanism, and getting it wrong is one of the more common ways to leak data between users. ## 31.6 What the Five Have in Common diff --git a/src/volume-5/ch32-synthesis-and-future-directions.md b/src/volume-5/ch32-synthesis-and-future-directions.md index 007b135..88e52d6 100644 --- a/src/volume-5/ch32-synthesis-and-future-directions.md +++ b/src/volume-5/ch32-synthesis-and-future-directions.md @@ -52,7 +52,7 @@ Training: Supervised learning on key distributions Prediction: Binary search within confidence bounds ``` -The reframing is genuine: an index is a function from key to position, and a model can approximate a function. A B-tree assumes nothing whatsoever about the key distribution, which makes it robust and also means it throws away information. Real key distributions (timestamps, auto-increment IDs, sorted identifiers)are highly regular, and a model that captures that regularity beats a structure that ignores it. +The reframing is genuine: an index is a function from key to position, and a model can approximate a function. A B-tree assumes nothing whatsoever about the key distribution, which makes it robust and also means it throws away information. Real key distributions (timestamps, auto-increment IDs, sorted identifiers) are highly regular, and a model that captures that regularity beats a structure that ignores it. The honest status, five years on from the original paper: **learned indexes remain mostly research, and the parts that shipped are elsewhere.** Updates are the hard problem. The original design was read-only, and while ALEX and the PGM-index support updates, distribution shift can force retraining. Worst-case bounds disappear, which matters for anything adversarial. And "neural network" oversells it: the models that work are staged linear regressions, because inference has to cost nanoseconds. @@ -83,7 +83,7 @@ The realistic near-term position: quantum computing will likely matter first for Two shifts already underway deserve to be added, because they are changing decisions today rather than eventually. -**Vector search became infrastructure in about three years.** Embedding models turned similarity search from a niche problem into a default component of application architecture, and the structures that serve it (HNSW graphs, IVF, product quantization)went from papers to production defaults faster than almost anything in this book's history. Note what drove it: not a better algorithm, but a change in what data looked like. Structures follow workloads. +**Vector search became infrastructure in about three years.** Embedding models turned similarity search from a niche problem into a default component of application architecture, and the structures that serve it (HNSW graphs, IVF, product quantization) went from papers to production defaults faster than almost anything in this book's history. Note what drove it: not a better algorithm, but a change in what data looked like. Structures follow workloads. **NVMe is quietly reopening settled questions.** A great deal of received wisdom: B-trees over hash indexes on disk, LSM trees over in-place updates, "random I/O is catastrophic". Was calibrated against spinning disks where a seek cost 10ms. On NVMe a random read costs about 10μs, a thousandfold improvement, and the gap between sequential and random access narrows from 10,000× to something closer to 10×. Several tradeoffs that were obvious in 2005 are now genuinely arguable. When the hardware assumptions under a piece of conventional wisdom change by three orders of magnitude, the wisdom deserves rechecking.