CComputer Science, Built

Act IV · Algorithms

Part 17 of 61

Data Structures

Degreestarts at this level47 min of film18 chaptersprerequisites: Part 2, Part 9, Part 16

Can a program look a word up in constant time, however many words it has seen?

Part 16's sorted Job made about a hundred million word comparisons, but the Job never needed its words in order: it needed a dictionary that can insert, look up and count. On this corpus that is 4,609,954 lookups for 57,895 distinct words. Hashing answers in expected constant time under assumptions the part states one by one: the birthday bound says collisions come early, universal hashing chooses the function at random so that no fixed set of keys is bad, and linear probing pays Knuth's (1 + 1/(1 - a)^2)/2 probes as the load a approaches one. Cuckoo and perfect hashing buy worst-case lookups. Search trees keep order instead: a random binary search tree is quicksort in disguise, AVL and red-black trees bound the height, treaps and skip lists do it by coin flips, splay trees by amortization, and B-trees by counting block transfers. Heaps, union-find with its inverse-Ackermann bound, tries, succinct rank directories and persistence complete the catalogue, each instrumented and measured. The Job is rewritten with a hash table in the Pebble language, and a model fitted to emulator passages projects about 0.794 seconds for the next ledger row; the frontier asks how good a data structure can be.

What you need. Part 16's counting (O-notation, expected values, amortization) and modular arithmetic. Part 9's cache hierarchy explains the timings but is not required.

Mathematics, ideas and history
universal hashing, linear probing, cuckoo hashing, balanced trees, splay trees, B-trees, Fibonacci heaps, union–find and α(n)
What we build or compute
the Job v2 (a hash table)

What you will be able to do

Degree

  • Estimate when the first collision arrives with the birthday bound, and compute expected chain lengths at a given load.
  • Insert and look up by hand in a linear-probing table and in a binary search tree, and say what sorted input does to each.
  • Run union by rank with path compression on a small forest.

Graduate

  • Prove that ((ax + b) mod p) mod m is a universal family and say what the proof assumes about the keys.
  • Bound an AVL tree's height through Fibonacci trees, and read a red-black tree as a 2-3-4 tree.
  • Prove the splay access lemma with the potential function, including the final zig's extra one.

Research

  • State the dynamic optimality conjecture and what the known competitive bounds do and do not settle.
  • Separate an open-addressing theorem's model (uniform probing, greedy or non-greedy insertion, reordering) from an experiment at fixed occupancy.

Industry

  • Choose between a hash map and an ordered map for a workload, and check the hash function's defence against flooding by untrusted keys.
  • Size a B-tree's fan-out from the block size and count the block transfers of a lookup.
  • Benchmark complete equivalent tasks, and say what a timing alone cannot show about cache misses.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 22 min · Graduate 44 min · Research 47 min · Industry 31 min.

  1. 0Can counting be constant-time?Degree2 min
  2. 1The dictionary, and the birthday boundDegree3 min
  3. 2Chaining and universal hashingDegree3 min
  4. 3Open addressingDegree3 min
  5. 4Cuckoo hashing and perfect hashingGraduate3 min
  6. 5Binary search treesDegree2 min
  7. 6Balanced trees: AVL and red-blackDegree3 min
  8. 7Treaps and skip listsGraduate2 min
  9. 8Splay treesGraduate3 min
  10. 9B-treesIndustry2 min
  11. 10Priority queuesGraduate2 min
  12. 11Union-findDegree2 min
  13. 12Tries and succinct structuresGraduate3 min
  14. 13Persistence, and the memory hierarchyIndustry2 min
  15. 14Hash tables in practiceIndustry2 min
  16. 15The Job, hashedIndustry3 min
  17. 16Frontier: how good can a data structure be?Research4 min
  18. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Can counting be constant-time?Degree2 min

Where we left the ledger. Part sixteen projected about five seconds for sorting then counting on one core, using full-corpus event counts, a passage-fitted instruction model, and sampled core throughput. That was not a full-corpus machine execution. The native event counter recorded just under one hundred million word comparisons. But the Job never needed words in order. It needed to find each word's count.

Strip the Job to its operations. For each word, look for an entry; create it if absent, otherwise increment its count. This corpus has four million six hundred and nine thousand nine hundred and fifty-four word occurrences and fifty-seven thousand eight hundred and ninety-five distinct words. They give one lookup-or-insert attempt per occurrence, not that many successful finds plus separate inserts. A dictionary supports those keyed operations. We ask whether the table work can be constant under appropriate assumptions, while still paying to read and hash the characters.

Here is where we are going. Hashing, which makes insert and find constant time on average, and the attack that breaks a careless hash function. Donald Knuth's first analysis of an algorithm, linear probing, checked against measurement. Balanced trees, which trade expectations for guarantees. Structures that are fast only on average over a sequence: splay trees, Fibonacci heaps and union–find. And the Job with a hash table: ledger row eight.

1The dictionary, and the birthday boundDegree3 min

A dictionary specifies operations before choosing a representation. An unsorted list can append a new entry in constant amortized time, but locating a key scans the list. A sorted array uses logarithmic comparisons to search and linear shifting to insert. A balanced tree offers logarithmic operations and sorted traversal. Hash tables offer expected constant table work under hashing and load assumptions; resizing adds an amortized qualification. Hashing a long string still reads its characters. Abstract data types let us choose the representation behind that interface. Liskov and Zilles helped formalize this separation in 1974.

The idea is older than most of computing: Hans Peter Luhn proposed it at IBM in 1953. Turn the key into a number with a hash function, and use that number, reduced to the table's size, as the place to store it. Then finding a key is computing its hash and looking in one place, whatever the size of the table. The catch is that two keys can land in the same slot. Everything in the next three chapters is about what to do then, and the first question is how soon it happens.

Suppose each key independently chooses one of m slots uniformly. For n at most m, the chance of no collision is this product: each new key avoids every earlier choice. The exponential approximation retains n times n minus one over two m. It is accurate when the small-factor approximation is appropriate; the exponential also gives a one-sided bound. Under the equal, independent birthday model, twenty-three people have about a fifty point seven percent chance of a shared birthday. Collisions become likely around the square-root scale. Likely is not certain, and a deterministic hash requires a separate analysis.

Here are two different quantities on the same vocabulary. Independent uniform hashes would give n choose two over m expected colliding pairs. Our polynomial hash is fixed, so its count is a deterministic observation, not a random-family guarantee. On fifty-seven thousand eight hundred and ninety-five distinct words, the full hash has one hundred and one colliding pairs. Reducing it to the slot table gives twelve thousand four hundred and ninety-five pairs. Excess keys and colliding pairs are different statistics if three keys share a value, even though the full-hash counts coincide here. The table must compare complete keys and resolve collisions; a matching hash alone never proves equality.

2Chaining and universal hashingDegree3 min

The simplest answer is to keep a chain of keys at each slot. A collision adds another entry to that slot's list. The load factor is n over m. With suitable random hashing, a fixed slot has expected chain length alpha. A successful search for a resident key also accounts for that key itself. Expected lookup work is order one plus alpha, excluding the cost to hash and compare long keys. Keeping alpha bounded by geometric resizing gives amortized expected constant table work. The randomness assumption and the amortized resizing statement are separate.

Here is one seeded experiment with ten thousand and seven keys and as many slots. Each bar counts the slots with a given chain length. The dots are a Poisson reference from independent balls into bins. This universal family guarantees pairwise collision control, not full independence, so agreement with that curve is an observation rather than its theorem. The displayed maximum is measured in this table.

A fixed public hash can expose a large colliding key set. Carter and Wegman's remedy chooses a random function from a family after the key set is fixed. Universality bounds the collision probability for every distinct pair by one over m. For a resident key, the expected number of other colliders is at most n minus one over m; include the key itself for a successful-chain bound. This affine family works on distinct residues from zero through p minus one, with prime p, nonzero a, and uniformly chosen b. Before the final reduction, two distinct inputs produce a uniformly chosen ordered pair of different residues. Counting pairs in the same output bucket gives the bound. Two fixed keys across twenty thousand random functions illustrate that rate; this finite check is not the proof, and adaptive attackers that learn the chosen function fall outside the fixed-key guarantee.

This is not a theoretical worry. Take the fixed hash x mod m and feed it two thousand multiples of m. Every key lands in slot zero: one chain of two thousand, and finding them all takes two million probes. The same keys under a random universal hash scatter into chains of one or two. In 2011, Alexander Klink and Julian Wälde showed that web servers in PHP, Java, Python and Ruby stored request parameters in hash tables with fixed functions. One request full of colliding names could keep a server's core busy for minutes. The fix was a hash with a secret random key. SipHash, designed by Jean-Philippe Aumasson and Daniel Bernstein, has been Python's string hash since version 3.4.

3Open addressingDegree3 min

Chains cost a pointer per key and a jump in memory per step. Open addressing keeps every key in the table itself. On a collision, linear probing tries the next slot, and the next, until it finds a free one; a find follows the same path until it finds the key or an empty slot. It is one array with no pointers, and the next probe is almost always in the same cache line, which is why it is so fast in practice. Its weakness is visible in these snapshots of a sixty-four-slot table filling up. Full slots form runs, and a key that lands anywhere in a run joins its end, so long runs grow faster than short ones and merge. This is primary clustering.

Knuth analyzed linear probing under random home addresses. The first expression is the large-table expected successful-search reference at load alpha. The second is the unsuccessful-search or insertion reference, which grows with the square of one over the free fraction. These are not exact finite-table identities for every fixed hash. Uniform permutation probing is a separate model; its reciprocal-free-fraction expression is also an asymptotic reference, with finite corrections. At half load the linear references are one point five and two point five; at ninety percent they are five point five and fifty point five. The rapid growth explains why leaving free space matters. Resizing, deletions, key hashing and adversarial choices need their own accounting.

Each load uses a new key set and a universal affine hash, which controls pair collisions but does not supply fully independent home addresses. The red observations count unsuccessful searches at fixed load; they are the probe cost of one more insert before the table changes. Actual n over m is recorded, and the reference formulas use that value. A single table per load cannot establish a confidence interval or explain a deviation's cause. Successful searches are sampled uniformly from resident keys. Double hashing uses a second step size. It may resemble a uniform-probing reference here, but it does not generate an independent uniform permutation for each key.

One refinement redistributes displacement. Robin Hood hashing lets the key farther from its home slot displace the key closer to home, then carries the displaced key onward. For a controlled comparison we use identical keys, insertion order and home hash. Both tables occupy exactly the same slots and have the same total displacement, so their mean successful scan length agrees exactly. The variance and maximum differ as displayed. That does not make every lookup equal, and implementations can use an additional early-stop rule. Modern grouped-control-byte tables are another design choice; they should not all be identified with this Robin Hood rule.

4Cuckoo hashing and perfect hashingGraduate3 min

In 2001 Rasmus Pagh and Flemming Rodler found a way to make every lookup cost two probes, not on average, but always. Keep two tables and two independent hash functions. Every key lives either at h one of x in the first table, or at h two of x in the second. A find looks in those two places and nowhere else. To insert, put the key in its first-table slot. If that slot was taken, the old key is kicked out, like a cuckoo's egg, to its place in the other table, possibly kicking out another. Usually the chain of kicks ends quickly. If it runs into a cycle, the pair of hash functions is bad: choose new ones and rebuild.

The classical two-choice cuckoo threshold is a random-graph statement, not a finite kick limit. Here we run forty seeded trials per load on two tables of two thousand slots, stopping when an insertion exceeds five hundred kicks. The plotted fraction is that experimental failure event. Model each slot as a vertex and each key's two choices as an edge. A placement can orient each edge toward a distinct occupied vertex. In the ideal independent-choice model, excess edges in a component obstruct placement, and the asymptotic threshold is near one half of total slots. Our cutoff can stop a long insertion without proving such an obstruction. A production implementation needs a safe rebuild or stash; this experiment stops immediately on failure.

A fixed key set permits a stronger lookup guarantee. FKS hashing chooses functions during construction and retries until its tested conditions hold. The abstract scheme has constant worst-case lookup with linear space under the stated word and hashing model. First hash n keys into n buckets. In this six-key example the bucket sizes are two, one, zero, three, zero, zero. Allocate the square of each bucket's size for its secondary table: fourteen slots in this particular outcome. Over the random first-level hash, universality gives an upper bound below two n for the expected sum of squares. A single outcome can exceed its expectation, so construction also retries a first level whose sum is too large. A fresh universal secondary hash into b squared slots has collision probability less than one half by a union bound. Retrying gives a collision-free mapping. Our finite construction experiment checks these mappings and counts slots and retries. It does not implement a stored dictionary query interface; the two-hash lookup statement belongs to the complete FKS scheme.

5Binary search treesDegree2 min

Hash tables give up order: they cannot list keys alphabetically, or find the next key after a given one. A binary search tree keeps it. Each node holds a key, with smaller keys in its left subtree and larger ones in its right. To find a key, start at the root, compare, and go left or right: one level per comparison. And walking the tree left, node, right lists every key in sorted order, so the tree also answers range queries and finds neighbours. The cost of a find is the depth of the key, and the shape of the tree depends entirely on the order the keys arrived in.

Random insertion order gives an expectation, not a guarantee for every tree. The table measures mean node depth in edges; the root has depth zero. The exact expectation over all insertion orders is two times one plus one over n times the harmonic number, minus four. As n grows its leading term is two natural log n. The rounded one point three nine factor is a leading-term comparison with log base two n, not a finite equality. Maximum depth also grows logarithmically under random insertion, with a different leading constant. Sorted insertion instead creates a chain: a thousand keys have maximum depth nine hundred and ninety-nine. Deep searches cost linear work; a root search still costs one visited node.

That two natural log n should look familiar. When the tree is built, the first key becomes the root and is compared with every key that comes after it. When quicksort runs with the first element as pivot, that element is compared with every other key. Both then split the rest into the smaller and the larger keys and do the same thing to each part, in the same order. So they compare exactly the same pairs. A binary search tree is quicksort's recursion, frozen into a data structure. We checked it on two thousand random keys: the counts are identical. Part 16's two n natural log n is the total depth of a random tree.

6Balanced trees: AVL and red-blackDegree3 min

Every balanced tree is built from one operation. Here is a node y whose left child x has subtrees A and B; y's right subtree is C. A right rotation makes x the parent and y its right child, and the subtree B changes parents. The order is preserved: everything in A is less than x, B lies between x and y, C is greater than y. It is still a search tree. Only three pointers change, and the depths shift: A moves up a level, C moves down. Balanced trees rotate to keep every path short.

AVL trees enforce a local height rule. Every node's two subtree heights differ by at most one. After insertion, rotations restore that invariant while preserving key order. Count height in node levels: an empty tree has height zero and a leaf height one. The sparsest height-h tree has subtree heights h minus one and h minus two. Thus its minimum node count is Fibonacci h plus two, minus one. The exact logarithmic coefficient is one over log base two of the golden ratio; one point four four zero five is only a rounded guide. This gives logarithmic worst-case height, unlike a random-tree expectation.

The balanced tree in most standard libraries is the red–black tree, and it is easiest to understand as something else. A two–three–four tree lets a node hold one, two or three keys, and keeps every leaf at exactly the same depth: when a node overflows it splits and pushes a key up. Perfectly balanced, but awkward to code. Leonidas Guibas and Robert Sedgewick saw in 1978 that each big node can be drawn as a little binary tree, with its internal links coloured red. The rules follow: no two red links in a row, and the same number of black links on every path, because the black links are the two–three–four tree. So the height is at most twice log n, and splitting a node is just flipping colours. Java's TreeMap and C++'s std::map are red–black trees. Sedgewick's later left-leaning variant writes insertion in a dozen lines.

These are measured heights for seeded insertion orders. The balanced-tree heights count node levels, so subtract one to compare with an edge depth. Sorted insertion can make the plain tree linear while the balanced variants remain logarithmic. The displayed rotations are insertion counters for these implementations and workloads, not a deletion benchmark. A shorter height can reduce visited nodes, but elapsed lookup or update time also depends on layout, metadata, branches and the implementation. These counts alone do not prove which tree is faster. AVL and red-black invariants provide logarithmic-height guarantees for ordinary dictionary search, insert and delete with bounded-cost keys. Traversal and range reporting still pay for the output.

7Treaps and skip listsGraduate2 min

Chapter five showed that a search tree built in random order is shallow. Raimund Seidel and Cecilia Aragon found a way to get random order whatever order the keys really arrive in. Give each key a random priority when it is inserted. Keep the keys in search-tree order and the priorities in heap order, every parent's priority above its children's. Those two rules fix the shape completely. And that shape is exactly the tree you would get by inserting the keys in order of priority, which is a random order. So a treap is always a random binary search tree, with expected depth two natural log n, even for sorted input. To insert, add the key as a leaf and rotate it up while its priority beats its parent's.

William Pugh's skip list gets the same expected behaviour without a tree at all. Start with a sorted linked list. Flip a coin for each node: heads, it also joins a second, sparser list above. Flip again for a third level, and so on. About half the nodes are on level two, a quarter on level three. To search, run along the top level until the next key would overshoot, drop a level, and repeat. Each level skips about half of what is left. The expected search is about two log n steps, and each key costs two pointers on average. There are no rotations, and that locality makes skip lists easy to update concurrently, which is why Java's concurrent sorted map is one.

These seeded measurements illustrate randomized shapes. Treaps receive sorted keys, but random priorities independent of the keys choose their shape. With distinct priorities, the shape is the BST obtained by inserting in priority order. Expected logarithmic behavior is over the internal randomness for fixed keys or a suitable nonadaptive operation sequence. It does not make every realized tree shallow or defeat every attacker who learns its randomness. The skip-list comparison counts, treap edge depths and node-level heights are different counters, as labeled.

8Splay treesGraduate3 min

Sleator and Tarjan's splay tree stores no balance metadata. After an access it rotates the node to the root. A zig is one rotation when the parent is the root. In a zig-zig, node and parent face the same direction: rotate the grandparent, then the parent. In a zig-zag they bend: rotate the accessed node up twice. A single deep access can still take linear work. In this five-node example, two zig-zigs move node one from depth four to zero, but node three moves down from depth two to three. Splaying does not halve every path node's depth. A potential argument bounds a whole sequence. From an arbitrary initial tree we must include initial potential, giving order m plus n times log of n plus one for m accesses.

The proof uses actual work plus a change in potential. Give every node a strictly positive weight. Subtree weight is s, rank is its logarithm, and potential is the sum of those ranks. Revisit the five-node example with unit weights. Before splaying, subtree sizes multiply to one hundred and twenty. Afterward they multiply to forty. Four rotations therefore cost four minus log base two of three in amortized units, about two point four. For a double rotation, the case analysis bounds amortized cost by three times the accessed node's rank increase. A final single zig needs an extra one. Telescoping gives the access lemma: at most three times the initial root-to-node rank difference, plus one. With unit weights, arbitrary initial potential adds an n log n term to the total bound. Weights belong to the proof, so frequency-based positive weights yield static optimality with setup costs included. Never assign weight zero and take its logarithm.

Here are four finite access workloads on the same two thousand keys. Repeated sorted scans are inexpensive for the splay tree, consistent with the sequential-access theorem. On this uniform random workload it does more logical node work than AVL. That is a measured workload, not the worst possible sequence. Skewed and hot-key workloads favor adaptation. The table's splay counter counts node visits and rotations, whereas AVL counts visited nodes; neither is a count of every Python predicate or a wall-clock benchmark. Dynamic optimality asks for a constant comparison to the best offline binary-search-tree execution on every sequence, with model and setup conventions. Selected 2026 progress appears in the frontier chapter; it does not settle constant competitiveness.

9B-treesIndustry2 min

Binary trees assume that following a pointer is cheap. On a disk, every node visited is a read that takes thousands of times longer than a comparison. Rudolf Bayer and Edward McCreight's B-tree, from 1970, makes the nodes wide. A node holds many keys in sorted order, and has one child between each pair. Every node except the root is at least half full. All leaves are at the same depth, so the height is the logarithm of n to the base of the fan-out. The fan-out is chosen so that a node fills a disk block, and a search reads one block per level. This is the external-memory model from Part 16: what matters is the number of block transfers, and comparisons inside a block are nearly free.

How does a B-tree stay perfectly balanced? When a node is full and another key arrives, the node splits into two half-full nodes, and its middle key moves up into the parent. If the parent overflows it splits too, and if the root splits, a new root appears above it. The tree grows at the top, never at the bottom, which is why every leaf is at the same depth. With at most three keys per node, this is exactly the two–three–four tree that red–black trees encode.

Here are seeded B-trees with two hundred thousand keys. The measured height column counts node levels, including the root. Larger nodes reduce the number of blocks along a search path, while doing more work inside a node. A rough billion-key capacity illustration uses fan-out two hundred and fifty-six; its four levels are not a worst-case bound for every half-full tree. Occupancy, root exceptions and cached top levels change the I/O count. B-plus trees are widely used in databases and file systems, alongside log-structured, hash, inverted and spatial indexes. The external-memory model prices block transfers; it does not erase computation within a block.

10Priority queuesGraduate2 min

A priority queue supports a precise operation set. Binary heaps have logarithmic worst-case insert, delete-min and decrease-key with handles. Lazy binomial variants and Fibonacci heaps offer amortized bounds. Fibonacci decrease-key is constant amortized time in the pointer model. Pairing-heap bounds depend on the exact variant and allowed operations; this table avoids combining them into one generic claim. On nonnegative-weight graphs, Dijkstra can perform a delete-min per reached vertex and relax many edges. Including isolated vertices and initialization, the usual bounds are order m plus n times log n with a binary heap, and m plus n log n with Fibonacci heaps. A dense graph makes the asymptotic difference more significant.

The Fibonacci heap delays work, while marks limit damage to its trees. Insert adds a singleton root. Delete-min eventually links roots of equal degree. Here node four is marked because it lost one child earlier. Lower seven's key to zero: heap order is violated, so cut that node into the root list. Four has now lost its second child, so cut four too and clear its mark. Cuts can cascade upward. A decrease that preserves heap order does not need a cut. The potential is the number of roots plus twice the number of marked nodes. In this example it stays three: two extra roots replace one mark. The invariant forces a degree-k subtree, including its root, to contain at least Fibonacci k plus two nodes. Logarithmic degrees and the potential yield the theoretical bounds with constant-time pointer operations. Our educational Python implementation uses lists; its key-comparison counts do not certify those time bounds.

What do these three graphs show? We count key comparisons inside each educational heap and verify all shortest-path distances independently with a heapq implementation. The displayed comparison savings depend on the graph. Comparisons are not time. Published native heap studies also report workload-dependent outcomes; no universal fastest heap follows. Use theoretical bounds to understand scaling, then measure complete equivalent tasks on the workload and implementation that matter.

11Union-findDegree2 min

Disjoint-set union tracks which items belong together. Each set is a parent-pointer tree, with the root as representative. Find follows parents to the root. Union links two distinct roots. Union by rank attaches the smaller rank under the larger and increments rank only when equal ranks merge. Without compression rank equals height; after compression it is an upper bound, not necessarily the current height. A rank-r root represents at least two to the r elements. Applications include Kruskal's spanning trees and equivalence classes; richer type unification needs additional structure.

Path compression makes an extra pass. After following parents to the root, point every visited node directly at that root. While the root stays the same, another find from those nonroot nodes traverses one edge. Later unions can move the root and add work again. Compression helps a sequence of operations; it does not promise every future find costs one step.

Here is one seeded sequence: forty thousand random unions, followed by forty thousand finds on twenty thousand elements. The table counts upward parent edges during those finds. It excludes the second compression pass, stores, and the earlier unions. Both heuristics dramatically reduce that particular counter. With initialization and the usual operation-count conventions, union by rank plus compression has an amortized inverse-Ackermann bound. Matching lower bounds are model-dependent sequence results, not a claim that every individual operation must take that long on every input.

Ackermann growth gives a useful scale comparison. Use exactly the displayed recurrence; different texts define variants. Its small values already jump from three to five to thirteen to sixty-five thousand five hundred and thirty-three. The next displayed value is two to sixty-five thousand five hundred and thirty-six, minus three. Formal union-find bounds may use a two-parameter inverse and setup terms; those conventions differ by small constants, not by practical growth. A worst-case sequence lower bound does not make every operation superconstant. The iterated logarithm is a simpler comparison: the table counts base-two logarithms needed to reach one. Neither this tiny table nor a finite timing experiment proves the asymptotic theorem.

12Tries and succinct structuresGraduate3 min

Hash tables and search trees treat a key as an opaque value to hash or compare. A trie, Edward Fredkin's name from 1960, uses the key's letters as directions. The root has one edge per possible first letter, each child one edge per second letter, and a word is a path; nodes where a word ends are marked. Finding a word of L letters takes L steps, however many words are stored. Words that share a prefix share a path, so a trie answers prefix queries directly: autocomplete, and the longest-prefix match that routes every internet packet. Chains of nodes with a single child waste space, and a radix tree merges each chain into one edge labelled with a string.

Here is the Job's vocabulary, all fifty-eight thousand distinct words, in a trie. The words have about four hundred and fifty thousand letters, but the trie needs far fewer nodes, because so many words share beginnings. The radix tree needs fewer still, under two nodes per word. Yet each node, stored the obvious way, costs a pointer per child, eight bytes each. The last idea of this chapter is to store the tree's shape itself in a couple of bits per node.

Succinct tree theory stores topology in about two bits per node, plus a lower-order navigation index. Here is a concrete six-node tree. In breadth-first order, write one for each child, then zero. Its eleven bits are exactly two n minus one. Node IDs and bit positions are different. Rank counts ones before a bit position; select gives the position of a numbered occurrence. Every index here starts at zero. Node one's block starts at bit three. Two ones precede it, so its first child has node ID three. The rank of zeroes before the one for node five gives its parent, node three. Our code implements rank with counts every five hundred and twelve bits, finer counts every sixty-four, and a bounded population count. It does not implement select. All sixty-five thousand five hundred and thirty-seven rank positions pass an independent prefix-sum check, including zero and the full length. The displayed overhead is a logical packed-bit estimate, excluding Python objects. This fixed directory is not Jacobson's lower-order construction. Compressed indexes later exploit entropy or repetition; they need not shrink every input.

13Persistence, and the memory hierarchyIndustry2 min

A mutable update normally discards the previous state. Path copying preserves it: copy the search path to the new leaf, and let the copies point to unchanged old subtrees. Two roots now describe two complete search trees sharing most nodes. Old versions remain searchable. Persistent structures are common in functional programming, copy-on-write systems and content-addressed trees such as Git. They do not imply that every value in every functional language uses this particular representation. Driscoll, Sarnak, Sleator and Tarjan developed a general persistence framework in 1989.

Is it expensive? We kept every version of a tree through a hundred thousand random inserts. Each insert copied about twenty-one nodes, the length of one path, which is chapter five's depth of a random tree. Copying the whole tree for each version would cost fifty thousand nodes per insert. So a hundred thousand complete versions cost about twenty nodes each. Chris Okasaki's book showed how far the idea goes: queues, heaps and more, persistent and still efficient.

Counting steps does not predict elapsed time by itself. These four implementations answer the same seeded successful uint32 lookups, with last assignment winning for duplicate keys. We check every returned value outside the timer, including distinct keys twelve and thirteen. The timer includes lookups and writing the result vector, and excludes construction, query generation, and verification. Each point is the minimum of three repeats on this host. Actual unique-key counts and open-table loads are recorded. The curves show different costs on this workload, not a universal ranking. Layout, branches, allocation, hashing and cache behavior can all matter. We did not collect hardware performance counters, so these timings alone do not identify the number of cache misses or prove which mechanism caused the gap.

14Hash tables in practiceIndustry2 min

Library designs share ideas but differ in guarantees. CPython uses open addressing and a compact insertion-ordered entry array; insertion order became a language guarantee in three point seven. Java HashMap can treeify long bins, with collision benefits depending on key ordering. Common C++ unordered-map implementations use nodes to satisfy reference stability, but the standard does not require one particular chain layout. Rust uses a SwissTable-derived design. Abseil's SIMD example scans sixteen metadata bytes; Go one point twenty-four uses eight-slot groups. Randomization is not universal: CPython string hashes and Rust's default hasher are seeded, whereas Java hashCode and ordinary C++ std hash are not generally secret-key defenses. Check the exact library, key type, version and configuration before relying on attack resistance.

Here is the complete word-count task natively on this host. Each implementation counts the same corpus and selects the top twenty, breaking ties by first appearance. Every repeat's complete report matches the reference. The bars show the minimum of three Python repeats or five native repeats. File reading, compiler startup and output formatting are excluded; allocation, tokenization, counting and report selection are included. The displayed throughput uses that timed scope. Languages, parsers, hash functions, allocation and containers all differ. These results compare complete implementations; they do not isolate the cost of Python's dictionary or prove one collision scheme universally faster.

15The Job, hashedIndustry3 min

Here is the Job rewritten around a hash table. As each letter arrives it is mixed into a hash: thirty-three times the hash so far, plus the letter, modulo a prime. The Pebble language has no bitwise operators, so a prime modulus does the mixing. At the end of a word, the table is probed linearly from the hash modulo its size. Each occupied slot names an entry; the stored hash is compared first, then the length, and only then the letters. A new word gets an entry, and when the table would pass half full it doubles and re-inserts every entry by its stored hash, Part 16's amortized doubling. Entries are created in order of first appearance, so the report, the twenty largest counts with ties to the earliest word, is exactly the output of version zero.

Separate observed events from predicted instructions. A native event counter processes all thirty novels and reproduces the complete reference report. It records the displayed word, comparison and slot counts. The sort and hash comparison counters follow different control paths, so read their definitions. The low average slot count reflects this fixed polynomial hash and this frequency-weighted access stream, not a random-key guarantee at the final load. We compile one explicitly corpus-sized image and use it for all forty-eight emulator passages and three core samples. Thirty-six passages fit a least-squares instruction model; twelve are held out. Their errors are displayed. Correlated features make coefficients nonunique, and full-corpus features exceed the training range. Full-corpus instructions remain an extrapolation, not an exact executed count.

The ledger adds a projected row. Its time combines native corpus events, fitted instructions, three-passage core throughput and an partial cache trace at the ledger clock. The number on screen is the scenario estimate; the full corpus was not executed by the emulator or core. The displayed speed ratios compare those ledger estimates under their stated assumptions. They illustrate the possible benefit of changing the algorithm, with model uncertainty carried forward.

Both hardware and algorithms change the cost of a task. The first bar compares earlier hardware ledger rows on the same corpus. The second compares the compiled list-based baseline with this projected hash-table row on one core. They use different baselines, so do not multiply the bars as independent measured gains. The educational result is the change in work: replacing repeated linear search with a suitable dictionary can remove enormous lookup effort. The exact runtime benefit still depends on inputs, hashing, implementation, and the machine model.

16Frontier: how good can a data structure be?Research4 min

Nearly full hashing needs careful model choices. First, a finite experiment: hold occupancy fixed and probe a fresh uniform permutation until the first empty slot. With m slots and f free, the exact expected count is m plus one over f plus one. Five thousand independent trials per point follow that expectation. We do not average insertions taken at different loads, and double hashing is not this uniform-permutation model. The 2025 funnel and elastic hashing results use per-key random probe sequences without moving existing keys. Funnel achieves squared logarithmic worst-case expected query and insertion bounds. Elastic hashing gives constant amortized expected positive-query probes, plus logarithmic worst-case expected query and insertion bounds. These are expectation statements with load-range assumptions, not deterministic per-operation caps. Selected 2026 preprints explore full occupancy, reordering, and braided cuckoo hashing under other models. We checked their stated claims, not every proof, and implemented none of those new schemes. Their bounds belong on theorem cards, not as constant-free timing curves beside this experiment.

Dynamic optimality remains a demanding sequence question. Can an online binary-search-tree algorithm stay within a constant factor of the best offline execution, under the same model and initialization convention? Splay and Greedy are central candidates. Splay already has strong locality theorems; those do not establish constant competitiveness on every sequence. Tango's log-log competitive ratio is a historical benchmark for general trees. Selected 2026 preprints state improved sublogarithmic competitive bounds specifically for Splay and Greedy. We identify their preprint status and checked scope in the notes. The geometric view asks for arborally satisfied point sets, a precise rectangle condition, rather than saying every rectangle is nonempty. None of these selected statements resolves the constant-factor conjecture. This is a dated snapshot, not an exhaustive literature survey.

Two directions sharpen the design questions. Cell-probe predecessor bounds depend on key universe, word size, available space and query model. Dynamic partial-sums lower bounds likewise relate update and query costs with explicit word-size and amortization assumptions. A bare logarithm per operation hides those trade-offs. Learned indexes predict a position from a model of the key distribution. A useful implementation also verifies or corrects that prediction, handles updates, and accounts for memory. Some data sets benefit; distribution shift and adversarial inputs can change the outcome. The research question is which complete guarantees a particular structure provides under a particular model, not whether learned structures have any guarantees at all.

Ask each open question with its model attached. Can Splay, Greedy, or any online BST achieve constant competitiveness? Which pairing-heap variant, operation set and pointer model are we analyzing? Bounds for different variants cannot be combined into one generic claim. For high-load hashing, does the model permit reordering, deletions, adaptive probes or special hash assumptions? Recent constant expected bounds make a blanket impossibility claim inappropriate. For learned indexes, what correction, update and distribution assumptions make the guarantees useful? The research exercise is an investigation plan. The notes do not contain a solution to dynamic optimality.

Recap, problems, and where this comes backAll tracks3 min

What this part connects. Birthday probabilities under independent uniform choices; universal hashing for fixed keys independent of the chosen random function; collision resolution and its load assumptions. Search trees preserve order, balanced trees control height, and splaying uses a sequence potential rather than per-node depth halving. B-trees price block transfers. Heap and union-find bounds require their operation models. Tries expose key structure, and succinct theory distinguishes topology bits from navigation redundancy. Finally, native event counts and sample-checked models project the Job's new ledger row. Every number and bound carries its scope.

Where this comes back. Part 18's graph algorithms run on heaps and union–find. Part 20 builds Bloom filters and sketches from universal hash families. Part 21 turns tries into suffix trees and compressed indexes. Part 33 makes hash maps and skip lists safe for many threads. Parts 34 and 35 build storage engines on log-structured merge trees and B-plus trees. Part 41's Git is a persistent tree, and Part 47's search engine is an inverted index.

In practice, match the interface to the workload. Use an ordered map when ranges or neighbors matter. For untrusted keys, check the actual hash and attack defenses rather than assuming the library randomizes everything. Measure complete equivalent tasks, including the memory and update costs that matter to your service. Databases also use log-structured, inverted, spatial and other indexes besides B-trees and hashing. Query plans reveal which access path is actually used. Heaps, tries and union-find are tools to recognize, not universal answers.

Six exercises appear in the notes: four proof exercises, a build sketch, and a research prompt. Pause on any of them. The build exercise replaces the per-letter division using explicitly defined wrapping arithmetic, then checks the complete output and measures core samples. It is a proposal, not a completed benchmark. The final exercise asks about dynamic optimality; its notes outline how to explore small sequences, not a solution to an open problem.

Next time. Euler invented the graph to walk the bridges of Königsberg, and graphs are now the shape of road maps, the internet and compilers. Breadth-first and depth-first search; Dijkstra's algorithm on this part's heaps, and the recent proof that it is universally optimal; spanning trees with union–find; and flows and cuts, two faces of one theorem. Part 18, Graphs.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 18's Dijkstra and Kruskal run on this part's heaps and union-find. Part 20 builds Bloom filters and sketches from universal hash families, Part 21 turns tries into suffix trees and compressed indexes, Part 33 makes hash maps and skip lists safe for many threads, Parts 34 and 35 build storage engines on log-structured merge trees and B+ trees, and Part 47's search engine is an inverted index.

Key results

The part's results in one place, for revision.

Birthday bound\(\displaystyle \Pr[\text{some }\allowbreak \text{collision }\allowbreak \text{among } n \text{ keys }\allowbreak \text{in } m \text{ slots}]\approx 1-e^{-n^{2}/2m}\)
Universal hashing (a, b random, x and y distinct)\(\displaystyle h(x)=((ax+b)\bmod p)\bmod m:\quad\allowbreak \Pr[h(x)=h(y)]\le \frac1m\)
Linear probing at load alpha\(\displaystyle \text{miss}\approx\tfrac12\Bigl(1+\frac{1}{(1-\alpha)^{2}}\Bigr),\qquad\allowbreak \text{hit}\approx\tfrac12\Bigl(1+\frac{1}{1-\alpha}\Bigr)\)
Random binary search tree\(\displaystyle \mathbb{E}[\text{depth }\allowbreak \text{of }\allowbreak \text{a }\allowbreak \text{node}]=2\Bigl(1+\frac1n\Bigr)H_n-4\ \approx\ 1.39\lg n\)
AVL height\(\displaystyle h<1.4405\,\lg(n+2)\)
Union-find\(\displaystyle m \text{ operations }\allowbreak \text{on } n \text{ elements }\allowbreak \text{cost } O\bigl(m\,\alpha(n)\bigr)\)

Try it

Lab 17 · Probes against load, and the depth of a random search tree

With the series' instrumented tables, fill linear-probing and double-hashing tables step by step and count the probes of hits and misses at each load against Knuth's formulas; then build random binary search trees and compare their mean depth with 2(1 + 1/n)H_n - 4, their comparisons with quicksort's, and their height on sorted input with an AVL tree's.

Figure produced by Lab 17: Probes against load, and the depth of a random search tree
Produced by the lab below, seed 0, in 0.6 s.
python -m videos.cs.labs 17 needs numpy, scipy, matplotlib · download lab17.py · source on GitHub
load 0.5: probes for a miss, linear probing  2.49   (Knuth 2.50)
load 0.5: probes for a miss, double hashing  2.01   (1/(1 - a) = 2.00)
load 0.5: probes for a hit, linear probing   1.47   (Knuth 1.50)
load 0.7: probes for a miss, linear probing  5.98   (Knuth 6.06)
load 0.7: probes for a miss, double hashing  3.35   (1/(1 - a) = 3.33)
load 0.7: probes for a hit, linear probing   2.12   (Knuth 2.17)
load 0.9: probes for a miss, linear probing  41.37   (Knuth 50.50)
load 0.9: probes for a miss, double hashing  9.99   (1/(1 - a) = 10.00)
load 0.9: probes for a hit, linear probing   5.04   (Knuth 5.50)
longest cluster at load 0.9                  413 of 4096 slots
random BST, 2,000 keys: mean depth           12.42   (2(1 + 1/n)H_n - 4 = 12.36)
comparisons to build it                      23,223, the same as quicksort with the first key as pivot
height on sorted input                       plain BST 500 levels for 500 keys; AVL 11 levels for 2,000   (bound 15.8)

Open addressing is constant-time only while the table has room: at load a a miss costs about (1 + 1/(1 - a)^2)/2 probes under linear probing and 1/(1 - a) without clustering; a search tree's depth is logarithmic on random input, and balancing makes it so on every input.
The code (116 lines; it asserts its own result)
"""Lab 17: fill hash tables to nine loads and count probes against Knuth's formulas; grow random search trees."""

from videos.coursekit import labs
import math
import random

import numpy as np

from explainer.cs.algo import ds, sorts

TITLE = "Probes against load, and the depth of a random search tree"
GOAL = ("With the series' instrumented tables, fill linear-probing and double-hashing tables step by step and "
        "count the probes of hits and misses at each load against Knuth's formulas; then build random binary "
        "search trees and compare their mean depth with 2(1 + 1/n)H_n - 4, their comparisons with quicksort's, "
        "and their height on sorted input with an AVL tree's.")
TASKS = [
    "Replace ds.LinearProbing by ds.RobinHood and compare the mean and the largest probe count of a hit at load 0.9. Which one changes?",
    "Hash with k % 1024 instead of k % M into the same table (all homes in the first quarter). What happens to misses at load 0.2?",
    "Insert the sorted keys into ds.Treap and ds.LLRB as well. How do their heights compare with the AVL bound 1.4405 lg(n + 2)?",
]
M, TABLES, PROBES = 4096, 6, 1500
LOADS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)


def harmonic(n):
    return sum(1 / k for k in range(1, n + 1))


def run(seed=0):
    rng = np.random.default_rng(seed)
    pyrng = random.Random(seed)
    lab = labs.Lab()

    # 1. open addressing: the same keys into a linear-probing and a double-hashing table
    miss = {"linear": np.zeros(len(LOADS)), "double": np.zeros(len(LOADS))}
    hit = np.zeros(len(LOADS))
    longest = 0
    for _ in range(TABLES):
        keys = [int(k) for k in rng.integers(0, 1 << 40, int(LOADS[-1] * M))]
        lin = ds.LinearProbing(M, lambda k: k % M)
        dbl = ds.DoubleHashing(M, lambda k: k % M, lambda k: k // M)
        done = 0
        for j, load in enumerate(LOADS):
            while done < int(load * M):
                lin.insert(keys[done])
                dbl.insert(keys[done])
                done += 1
            fresh = [int(k) for k in rng.integers(0, 1 << 40, PROBES)]
            miss["linear"][j] += np.mean([lin.find(k) for k in fresh]) / TABLES
            miss["double"][j] += np.mean([dbl.find(k) for k in fresh]) / TABLES
            hit[j] += np.mean([lin.find(k) for k in keys[:done]]) / TABLES
        longest = max(longest, max(lin.clusters()))
    a = np.array(LOADS)
    knuth_miss, knuth_hit, uniform = 0.5 * (1 + 1 / (1 - a) ** 2), 0.5 * (1 + 1 / (1 - a)), 1 / (1 - a)
    for j in (4, 6, 8):
        lab.row(f"load {LOADS[j]}: probes for a miss, linear probing", f"{miss['linear'][j]:.2f}   (Knuth {knuth_miss[j]:.2f})")
        lab.row(f"load {LOADS[j]}: probes for a miss, double hashing", f"{miss['double'][j]:.2f}   (1/(1 - a) = {uniform[j]:.2f})")
        lab.row(f"load {LOADS[j]}: probes for a hit, linear probing", f"{hit[j]:.2f}   (Knuth {knuth_hit[j]:.2f})")
    lab.row("longest cluster at load 0.9", f"{longest} of {M} slots")
    assert np.all(np.abs(miss["linear"][:7] / knuth_miss[:7] - 1) < 0.12), "misses should follow (1 + 1/(1 - a)^2)/2"
    assert np.all(np.abs(hit[:7] / knuth_hit[:7] - 1) < 0.08), "hits should follow (1 + 1/(1 - a))/2"
    assert np.all(np.abs(miss["double"][:8] / uniform[:8] - 1) < 0.08), "double hashing should behave like uniform probing"
    assert np.all(miss["linear"][5:] > 1.2 * miss["double"][5:]), "clustering should cost linear probing extra"

    # 2. binary search trees
    n, trees = 2000, 20
    depth = []
    for _ in range(trees):
        xs = [pyrng.random() for _ in range(n)]
        t = ds.BST()
        for x in xs:
            t.insert(x)
        depth.append(np.mean(t.depths()))
        assert t.cmp == sorts.quicksort(xs, "first")[1]["cmp"], "a BST's insertions are quicksort's comparisons"
    theory = 2 * (1 + 1 / n) * harmonic(n) - 4
    chain, avl = ds.BST(), ds.AVL()
    for x in range(500):
        chain.insert(x)
    for x in range(n):
        avl.insert(x)
    lab.row(f"random BST, {n:,} keys: mean depth", f"{np.mean(depth):.2f}   (2(1 + 1/n)H_n - 4 = {theory:.2f})")
    lab.row("comparisons to build it", f"{t.cmp:,}, the same as quicksort with the first key as pivot")
    lab.row("height on sorted input", f"plain BST {chain.height()} levels for 500 keys; AVL {avl.height()} levels for "
                                      f"{n:,}   (bound {1.4405 * math.log2(n + 2):.1f})")
    assert abs(np.mean(depth) / theory - 1) < 0.06, "random BST depth should be about 2 ln n"
    assert chain.height() == 500 and avl.height() < 1.4405 * math.log2(n + 2)
    lab.note = ("Open addressing is constant-time only while the table has room: at load a a miss costs about "
                "(1 + 1/(1 - a)^2)/2 probes under linear probing and 1/(1 - a) without clustering; a search tree's "
                "depth is logarithmic on random input, and balancing makes it so on every input.")

    fig, ax = labs.figure(2, size=(11, 4.4))
    grid = np.linspace(0.05, 0.92, 100)
    ax[0].plot(grid, 0.5 * (1 + 1 / (1 - grid) ** 2), color=labs.GOLD, label="Knuth: (1 + 1/(1 - a)²)/2")
    ax[0].plot(grid, 1 / (1 - grid), color=labs.GREY, ls="--", label="uniform probing: 1/(1 - a)")
    ax[0].plot(a, miss["linear"], "o", color=labs.BLUE, label="linear probing, measured")
    ax[0].plot(a, miss["double"], "s", color=labs.GREEN, ms=5, label="double hashing, measured")
    ax[0].set(title=f"Probes for an unsuccessful search ({M:,} slots)", xlabel="load a = keys / slots",
              ylabel="probes (log scale)", yscale="log")
    ax[0].legend()
    sizes = np.array([50, 100, 200, 400, 800, 1600, 3200])
    means = []
    for size in sizes:
        d = []
        for _ in range(4):
            t = ds.BST()
            for x in rng.random(int(size)).tolist():
                t.insert(x)
            d.append(np.mean(t.depths()))
        means.append(np.mean(d))
    ax[1].plot(sizes, [2 * (1 + 1 / s) * harmonic(int(s)) - 4 for s in sizes], color=labs.GOLD, label="2(1 + 1/n)H_n - 4")
    ax[1].plot(sizes, np.log2(sizes + 1) - 2, color=labs.GREY, ls="--", label="a perfectly balanced tree: about lg n - 2")
    ax[1].plot(sizes, means, "o", color=labs.BLUE, label="random BSTs, mean depth")
    ax[1].set(title="Mean depth of a node, in edges", xlabel="keys n (log scale)", ylabel="depth", xscale="log")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Replace ds.LinearProbing by ds.RobinHood and compare the mean and the largest probe count of a hit at load 0.9. Which one changes?
  2. Hash with k % 1024 instead of k % M into the same table (all homes in the first quarter). What happens to misses at load 0.2?
  3. Insert the sorted keys into ds.Treap and ds.LLRB as well. How do their heights compare with the AVL bound 1.4405 lg(n + 2)?

Problems, with solutions

Try each problem before opening its solution.

  1. Universal hashing. Prove that h_{a,b}(x) = ((ax + b) mod p) mod m, with a uniform in {1, …, p − 1} and b uniform in {0, …, p − 1}, p prime and distinct keys in {0, …, p − 1}, satisfies Pr[h(x) = h(y)] ≤ 1/m for x ≠ y.

    Solution

    Let r = (ax + b) mod p and s = (ay + b) mod p. Then r − s ≡ a(x − y) (mod p), which is nonzero because p is prime and neither a nor x − y is divisible by p; so r ≠ s. Conversely, each pair r ≠ s comes from exactly one (a, b): a = (r − s)(x − y)⁻¹ mod p and b = (r − ax) mod p. So (a, b) ↦ (r, s) is a bijection from the p(p − 1) choices onto the p(p − 1) ordered pairs of distinct residues, and (r, s) is uniform over them. For each r, the values s ≠ r with s ≡ r (mod m) number at most ⌈p/m⌉ − 1 ≤ (p − 1)/m. Hence Pr[h(x) = h(y)] ≤ p · ((p − 1)/m) / (p(p − 1)) = 1/m.

  2. Linear probing. From the insertion cost U(α) = ½(1 + 1/(1 − α)²), derive the successful-search cost S(α) = ½(1 + 1/(1 − α)).

    Solution

    A key is found by retracing the probes of its insertion, so finding the key inserted when the load was x costs U(x). Averaging over the keys, inserted as the load rose from 0 to α: S(α) = (1/α) ∫₀^α U(x) dx = (1/2α) [x + 1/(1 − x)]₀^α = (1/2α)(α + 1/(1 − α) − 1) = (1/2α)(α + α/(1 − α)) = ½(1 + 1/(1 − α)). (Knuth's 1963 derivation of U is the hard part; it counts the ways clusters form.)

  3. Union by rank. Show that union by rank keeps every tree's height at most lg n, and that unions without it can build a tree of height n − 1.

    Solution

    Claim: a root of rank r has at least 2^r nodes. A new node has rank 0 and 1 node. Ranks change only when two roots of equal rank r are joined; the result has rank r + 1 and at least 2^r + 2^r = 2^{r+1} nodes. A node's rank bounds its tree's height (height rises only in the same event), so n ≥ 2^h and h ≤ lg n. Without ranks, union(1, 0), union(2, 1), …, linking each time the old tree's root under the new singleton, builds the path n − 1, …, 0, of height n − 1; a find on node 0 then walks n − 1 parents (the chain case in compute.py).

  4. AVL height. Prove that an AVL tree with n nodes has height h < 1.4405 lg(n + 2).

    Solution

    Let N(h) be the fewest nodes in an AVL tree of height h. Its root's subtrees have heights h − 1 and (at least) h − 2, each minimal: N(h) = N(h − 1) + N(h − 2) + 1, with N(1) = 1 and N(2) = 2. Then N(h) + 1 satisfies the Fibonacci recurrence with N(1) + 1 = 2 = F₃ and N(2) + 1 = 3 = F₄, so N(h) = F_{h+2} − 1. Since F_k > φ^k/√5 − 1, we get n + 2 ≥ N(h) + 2 = F_{h+2} + 1 > φ^{h+2}/√5, so h + 2 < log_φ(√5 (n + 2)), that is h < log_φ(n + 2) + log_φ √5 − 2 = lg(n + 2)/lg φ + log_φ √5 − 2. The leading coefficient 1/lg φ is approximately 1.44042; 1.4405 is a rounded, weaker upper coefficient.

  5. Build: a hash without a division per letter. Rewrite the Job v2 so that it divides once per word instead of once per letter, in the Pebble language, and measure its instructions per cycle and its ledger row on Part 8's core.

    Build sketch, not a measured result. Keep the multiplier 33 and define a 32-bit wrapping hash explicitly, then normalize at the word boundary before slot reduction. Check Pebble's runtime and constant-folding semantics at overflow; native C/C++ probes must use defined unsigned arithmetic. Replacing the hash changes collisions and probe paths, so preserve full keys, test long words, ties and growth, and check every complete output. Refit event counts with held-out samples of one corpus-sized image, then measure core samples. Do not promise an IPC or runtime gain before those checks. The existing corpus has 19.4 million letters, but this exercise has not produced a new ledger row.

  6. ★ Research: dynamic optimality. Prove that splay trees are dynamically optimal (within O(1) of the best binary-search-tree algorithm on every access sequence), or give any BST algorithm that is o(log log n)-competitive.

    Where to start. The conjecture: Sleator and Tarjan, "Self-adjusting binary search trees" (1985). Lower bounds on the optimum: Wilber (1989), the interleave and funnel bounds; Lecomte and Weinstein (2020) relate them. O(log log n)-competitive trees: tango trees (Demaine, Harmon, Iacono and Pătraşcu, 2004), multi-splay trees (Wang, Derryberry and Sleator, 2006). The geometric view: Demaine, Harmon, Iacono, Kane and Pătraşcu, "The geometry of binary search trees" (2009), with the Greedy algorithm (Lucas 1988, Munro 2000) as the other candidate. Surveys: Iacono, "In pursuit of the dynamic optimality conjecture" (2013); Levy and Tarjan (2019). Open: (a) any O(1)-competitive BST, splay or Greedy or another; (b) whether Wilber's funnel bound is within a constant of the optimum; (c) here, measure: compare splay, Greedy (simulated geometrically) and an offline optimum on small n by search, and look for a sequence where the ratio grows.

Notes and sources

Glossary

字典 dictionary · 抽象数据类型 abstract data type · 哈希 hashing · 哈希函数 hash function · 冲突 collision · 生日界 birthday bound · 装填因子 load factor · 链地址法 chaining · 全域哈希 universal hashing · 哈希洪水攻击 hash flooding · 带密钥的哈希 keyed hash · 开放寻址 open addressing · 线性探查 linear probing · 一次聚集 primary clustering · 双重哈希 double hashing · 均匀探查 uniform probing · 罗宾汉哈希 Robin Hood hashing · 布谷鸟哈希 cuckoo hashing · 完美哈希 perfect hashing · 二叉搜索树 binary search tree · 旋转 rotation · AVL 树 AVL tree · 斐波那契树 Fibonacci tree · 红黑树 red–black tree · 2–3–4 树 2–3–4 tree · 树堆 treap · 跳表 skip list · 伸展树 splay tree · 访问引理 access lemma · 静态 最优性 static optimality · 动态最优性 dynamic optimality · B 树 B-tree · 扇出 fan-out · 优先队列 priority queue · 减小键 decrease-key · 二项堆 binomial heap · 斐波那契堆 Fibonacci heap · 级联切断 cascading cut · 配对堆 pairing heap · 并查集 union–find · 按秩合并 union by rank · 路径压缩 path compression · 阿克曼函数 Ackermann's function · 迭代对数 iterated logarithm · 字典树 trie · 基数树 radix tree · 简洁数据结构 succinct data structure · 秩与选择 rank and select · 持久化 persistence · 路径复制 path copying · 学习型索引 learned index

Sources

Canon. Books: Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, chapters 10–13, 18–19, 21; Knuth, The Art of Computer Programming, volume 3, chapter 6; Sedgewick & Wayne, Algorithms, chapter 3; Tarjan, Data Structures and Network Algorithms (1983); Mehlhorn & Sanders, Algorithms and Data Structures; Okasaki, Purely Functional Data Structures (1998); Navarro, Compact Data Structures (2016).

Papers: Luhn's IBM memorandum (1953); Knuth, "Notes on 'open' addressing" (1963); Adelson-Velsky & Landis (1962); Galler & Fischer (1964); Bayer & McCreight, "Organization and maintenance of large ordered indices" (1970); Hopcroft & Ullman (1973); Liskov & Zilles, "Programming with abstract data types" (1974); Tarjan, "Efficiency of a good but not linear set union algorithm" (1975); Vuillemin (1978); Guibas & Sedgewick, "A dichromatic framework for balanced trees" (1978); Carter & Wegman, "Universal classes of hash functions" (1979); Gonnet (1981); Fredman, Komlós & Szemerédi, "Storing a sparse table with O(1) worst case access time" (1984); Sleator & Tarjan, "Self-adjusting binary search trees" (1985); Yao, "Uniform hashing is optimal" (1985); Celis, Robin Hood Hashing (1986); Fredman, Sedgewick, Sleator & Tarjan, pairing heaps (1986); Fredman & Tarjan, "Fibonacci heaps" (1987); Jacobson, "Space-efficient static trees and graphs" (1989); Driscoll, Sarnak, Sleator & Tarjan, "Making data structures persistent" (1989); Fredman & Saks (1989); Seidel & Aragon, "Randomized search trees" (1989); Pugh, "Skip lists" (1990); Pagh & Rodler, "Cuckoo hashing" (2001); Sedgewick, "Left-leaning red–black trees" (2008); Klink & Wälde, "Efficient denial of service attacks on web application platforms" (28C3, 2011); Aumasson & Bernstein, "SipHash" (2012); Larkin, Sen & Tarjan, "A back-to-basics empirical study of priority queues" (2014).

Frontier. Farach-Colton, Krapivin & Kuszmaul, "Optimal bounds for open addressing without reordering" (2025); Bender, Conway, Farach-Colton, Kuszmaul & Tagliavini, "Tiny pointers" (2021); Demaine, Harmon, Iacono & Pătraşcu, "Dynamic optimality—almost" (2004); Demaine, Harmon, Iacono, Kane & Pătraşcu, "The geometry of binary search trees" (2009); Pătraşcu & Demaine, "Tight bounds for the partial-sums problem" (2004); Pătraşcu & Thorup, "Time-space trade-offs for predecessor search" (2006); Kraska, Beutel, Chi, Dean & Polyzotis, "The case for learned index structures" (2018).

Sources

Selected primary-source checks, 10 November 2026

中文范围说明:这些是注明日期的部分原始来源核对,不是穷尽综述或所有证明的审核。期望、摊还、以高概率、装填区间、 是否允许重排,以及字长和操作集合都属于结论的一部分。预印本身份与未实现的新方案在画面及旁白中单独说明。

About this partfrom its README

Part 17 of the 61-part series, in Act IV, Algorithms. The running word-count task needs a dictionary rather than sorted output. This episode connects hashing, ordered trees, priority queues, disjoint sets, tries, persistence and the memory hierarchy through worked diagrams and instrumented implementations. English and Chinese narration use the same 81 source blocks.

The visual examples include collision lanes, a 42-pair universal-family grid, matched-home Robin Hood tables, a BST/quicksort split, the actual five-node splay potential change, a cascading cut, and a valid six-node LOUDS tree beside its 11 encoding bits. A six-bucket FKS example distinguishes one outcome from an expectation. The instruments are ds.py, job2.py, compute.py and measurements.py; regressions are in test_cs17_ds.py.

Measurements and models have different scopes:

  • The corpus has 24,971,555 bytes, 4,609,954 word occurrences and 57,895 distinct words. The fixed polynomial hash produces 101 full-hash collision pairs and 12,495 reduced-slot pairs. Independent uniform-hash expectations are separate reference quantities; pair counts and excess-key counts differ for triples.
  • Robin Hood and linear probing use the same keys, insertion order and home hash for the variance comparison. Their occupied patterns, displacement sums and means agree. Other probing plots are finite seeded illustrations; an affine universal family is not fully independent random hashing.
  • The lookup microbenchmark preserves zero and distinguishes keys 12 and 13. Duplicate keys use last assignment wins in every implementation. Every result vector is checked outside the timer. Three raw repeats and actual unique-key loads are retained; the reported value is each implementation's minimum. The largest open table is 29.8% full, not 50%. Lookup plus result-vector writes are timed; construction and verification are excluded. Timing alone does not measure cache misses or establish a causal explanation.
  • Native word counters include allocation, tokenization, counting and top-20 selection, excluding file input, compiler startup and output formatting. Every complete report matches the reference. On this host the minima were about 1.073 s for Python (three repeats), 0.222 s for C++ and 0.103 s for C (five repeats each). These compare complete implementations, not isolated collision schemes. Compiler/interpreter versions, source hashes and all repeats are stored in the cached payloads. C++ prints timings to six significant digits.
  • The Job's static image explicitly accommodates this corpus: 452,740 letter bytes including a temporary-word margin, 57,896 entry slots, 131,072 hash slots, a 1,904,816-byte image and 4 MiB modeled memory. The same image runs every emulator/core sample. Full corpus native event counts reproduce the complete report; the full corpus has not been executed by the emulator or core.
  • A 27-event least-squares instruction model uses 36 of 48 emulator passages, with 12 held out. The event matrix has rank 22 of 28 columns including the intercept; correlated coefficients do not identify unique category costs. The largest held-out relative error is about 0.0132%, and 22 full-corpus features exceed their training maximum. Roughly 954.2 million full-corpus instructions are an extrapolation, not an exact executed count.
  • Three passage core samples give weighted IPC about 1.472. A separate partial data-access trace uses an assumed array layout and toy caches. Adding its miss penalties to fitted instructions divided by sampled IPC projects about 0.794 s at the ledger clock. It omits overlap, may count sampled stalls twice, and is not a proved upper bound. The speed ratios inherit those assumptions and use different baselines.

Theory is scoped beside its diagrams. Hash-table bounds require appropriate hashing, load and key-cost models; fixed keys must be independent of a chosen random family. The cuckoo curve records a 500-kick cutoff over 40 seeded trials, not proof of a cycle or the asymptotic threshold. Its diagnostic insertion stops immediately on failure. The FKS experiment validates construction hashes and counts space/retries; it does not implement a stored dictionary query interface. Random BST depth is in edges, while balanced/B-tree height tables use node levels, with conversions explicit. Splay bounds include positive proof weights, final-zig +1 and initial potential. Pairing-heap bounds depend on the variant. Heap comparisons do not realize Python list costs; all displayed Dijkstra graphs are checked with independent heapq shortest paths, with a Bellman–Ford regression. Union-find counts upward discovery edges, excluding compression's second pass and stores; roots can move later.

The fixed 512/64-bit rank directory checks every position, including 0 and n. Its 13,312-bit directory estimate for 65,536 input bits excludes Python object memory. It implements rank, not select, and fixed proportional redundancy is not an asymptotic o(n)-bit construction. LOUDS uses zero-based node and bit indices with rank/select conversions shown. Succinct theory and data-dependent compressed indexes are separate claims.

The frontier distinguishes a fixed-occupancy uniform-permutation experiment (5,000 independent trials per point, exact finite expectation (m+1)/(f+1)) from theorem statements. No funnel, elastic or 2026 hashing implementation is benchmarked. The literature snapshot is dated 10 November 2026; selected statements/abstracts were checked, not every proof or the entire literature. Constant dynamic optimality is not resolved by the cited bounds.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Abstract data types against implementations (Liskov & Zilles 1974); Luhn's hashing (1953); the birthday bound, 1 − e^{−n²/2m} (derived), and on our vocabulary (101 full-hash collisions predicted 100; 12,495 slot pairs predicted 12,786).
  2. Chaining against Poisson; universal hashing (Carter & Wegman 1979), ((ax + b) mod p) mod m proved universal and checked; a flooding attack on a fixed hash; Klink & Wälde (2011) and SipHash.
  3. Open addressing: linear probing's ½(1 + 1/(1 − α)²) (Knuth 1963), measured over α, with primary clustering shown; double hashing against uniform probing; Robin Hood hashing's variance; Swiss tables.
  4. Cuckoo hashing (Pagh & Rodler 2001): two probes, kicks animated, the failure threshold at load ½ (the cuckoo graph, Erdős–Rényi); FKS perfect hashing (1984) in about three slots per key.
  5. BSTs: random BSTs have expected depth 2(1 + 1/n)Hₙ − 4, measured; height (Devroye); sorted input; the bijection with quicksort, counted (24,944 both ways).
  6. Rotations; AVL trees, with height < 1.4405 lg(n + 2) via Fibonacci trees; red–black trees as 2–3–4 trees (Guibas & Sedgewick 1978); left-leaning red–black trees (Sedgewick 2008); heights and rotations measured.
  7. Treaps (Seidel & Aragon 1989) on sorted input, and skip lists (Pugh 1990), measured.
  8. Splay trees (Sleator & Tarjan 1985): the three steps; the access lemma by potential; static optimality; splay against AVL on sequential, uniform, Zipf and hot-set sequences; the dynamic optimality conjecture.
  9. B-trees (Bayer & McCreight 1970): fan-out and height log_t n, splitting at the root, five fan-outs measured; a billion keys in four levels (Part 35).
  10. Priority queues: binary, binomial, Fibonacci heaps (Fredman & Tarjan 1987) with cascading cuts, pairing heaps; Dijkstra with each, counted; why the Fibonacci heap loses in practice (Larkin, Sen & Tarjan 2014).
  11. Union–find (Galler & Fischer 1964): union by rank and path compression, 2,312 parent steps per find against 1.0; O(m α(n)) (Tarjan 1975), optimal (Fredman & Saks 1989); Ackermann's function and log*.
  12. Tries (Fredkin 1960) and radix trees on the vocabulary; rank and select in O(1) with a 20% directory (Jacobson 1989); LOUDS (Part 21 builds on them).
  13. Persistent structures (path copying, Driscoll et al. 1989; Okasaki); lookups timed on this machine from 10³ to 10⁷ keys (red–black tree 2.3 µs, sorted array 0.33 µs, chaining 74 ns, open addressing 31 ns: callback to Part 9).
  14. Hash tables in practice: Python, Java, C++, Rust and Go; the Job natively (Python 0.91 s, C++ 0.19 s, C 0.11 s).
  15. The Job v2, a hash table in the Pebble language: 1.06 slots per word on the corpus; an exact 27-event instruction model (0.01% on held-out passages); the corpus through Part 9's caches (+6%); ledger row 8 (0.794 s projected: 6.3× row 7, 72× row 5, 15× row 4); rows 0 → 4 against rows 5 → 8. Frontier: Yao's conjecture refuted (Farach-Colton, Krapivin & Kuszmaul 2025) against measured uniform probing; dynamic optimality and tango trees; cell-probe lower bounds; learned indexes; open problems. Outro.

Computed: probe counts against Knuth's formula over α; chain lengths against Poisson; cuckoo failure rates; FKS space; BST depths and the quicksort bijection; AVL and red–black heights and rotations; treaps and skip lists; splay costs on four sequences; B-tree heights; Dijkstra's heap comparisons; union–find path lengths; the vocabulary's trie; persistence; lookups and the Job timed natively; the Job v2 on the emulator, its model, the corpus counted in C and run through Part 9's caches. Visuals: buckets filling while clusters form; chains; cuckoo kicks; rotations; 2–3–4 ↔ red–black; a treap and a skip list; B-tree splits; a union–find path compressing; a trie; path copying. In practice: hash maps and their DoS hardening, B-trees in every database, priority queues in schedulers and timers, union–find in compilers and image processing. Reading: CLRS ch. 10–13, 18–19, 21; Knuth, TAOCP 3 ch. 6; Sedgewick & Wayne, Algorithms ch. 3; Tarjan, Data Structures and Network Algorithms; Mehlhorn & Sanders, Algorithms and Data Structures; Okasaki, Purely Functional Data Structures; Navarro, Compact Data Structures; Carter & Wegman 1979; Pagh & Rodler 2004; Sleator & Tarjan 1985; Fredman & Tarjan 1987; Farach-Colton, Krapivin & Kuszmaul 2025.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 全域哈希。 证明 h_{a,b}(x) = ((ax + b) mod p) mod m(a 在 {1, …, p − 1} 中均匀,b 在 {0, …, p − 1} 中均匀,p 为 素数,键小于 p)对 x ≠ y 满足 Pr[h(x) = h(y)] ≤ 1/m。

    解答

    令 r = (ax + b) mod p,s = (ay + b) mod p。则 r − s ≡ a(x − y)(mod p),由于 p 是素数而 a 与 x − y 都不被 p 整除,它不为零,所以 r ≠ s。反过来,每一对 r ≠ s 恰好来自一个 (a, b):a = (r − s)(x − y)⁻¹ mod p,b = (r − ax) mod p。所以 (a, b) ↦ (r, s) 是从 p(p − 1) 种选择到 p(p − 1) 个不同剩余有序对的双射,(r, s) 在其上均匀分布。对每个 r,满足 s ≠ r 且 s ≡ r(mod m)的 s 至多 ⌈p/m⌉ − 1 ≤ (p − 1)/m 个。故 Pr[h(x) = h(y)] ≤ p · ((p − 1)/m) / (p(p − 1)) = 1/m。

  2. 线性探查。 由插入代价 U(α) = ½(1 + 1/(1 − α)²) 推出成功查找的代价 S(α) = ½(1 + 1/(1 − α))。

    解答

    找到一个键就是重走它插入时的探查,所以找到在装填率为 x 时插入的键要花 U(x)。对装填率从 0 升到 α 时插入的所有 键取平均:S(α) = (1/α) ∫₀^α U(x) dx = (1/2α) [x + 1/(1 − x)]₀^α = (1/2α)(α + 1/(1 − α) − 1) = (1/2α)(α + α/(1 − α)) = ½(1 + 1/(1 − α))。(高德纳1963年推导 U 才是难的部分;它要数簇的各种形成方式。)

  3. 按秩合并。 证明按秩合并使每棵树的高度至多为 lg n,并证明不用它的合并能造出高度为 n − 1 的树。

    解答

    断言:秩为 r 的根至少有 2^r 个结点。新结点秩为 0、有 1 个结点。秩只在两个秩同为 r 的根合并时改变,结果秩为 r + 1,至少有 2^r + 2^r = 2^{r+1} 个结点。结点的秩是其树高的上界(树高只在同一事件中增加),所以 n ≥ 2^h,h ≤ lg n。 不用秩时,依次 union(1, 0)、union(2, 1)……,每次把旧树的根挂到新的单点下,就造出路径 n − 1, …, 0,高度为 n − 1; 对结点 0 做一次查找要走 n − 1 个父指针(compute.py 中的 chain 情形)。

  4. AVL 树的高度。 证明有 n 个结点的 AVL 树高度 h < 1.4405 lg(n + 2)。

    解答

    设 N(h) 是高度为 h 的 AVL 树最少的结点数。它的根的两棵子树高度为 h − 1 和(至少)h − 2,且各自最少: N(h) = N(h − 1) + N(h − 2) + 1,N(1) = 1,N(2) = 2。于是 N(h) + 1 满足斐波那契递推,N(1) + 1 = 2 = F₃,N(2) + 1 = 3 = F₄,所以 N(h) = F_{h+2} − 1。由 F_k > φ^k/√5 − 1 得 n + 2 ≥ N(h) + 2 = F_{h+2} + 1 > φ^{h+2}/√5,故 h + 2 < log_φ(√5 (n + 2)),即 h < log_φ(n + 2) + log_φ √5 − 2 = lg(n + 2)/lg φ + log_φ √5 − 2。主项系数 1/lg φ 约为 1.44042,1.4405 只是取整后稍宽的上界系数。

  5. 动手:每个字母不做除法的哈希。 用 Pebble 语言把任务 v2 改写成每个单词只做一次除法而不是每个字母一次,并在第8部分 的核心上测量它的每周期指令数和账本行。

    构建思路,并非实测结果。 保留乘数 33,明确定义三十二位回绕哈希,在单词边界规范化后再约简到槽。 核对 Pebble 运行时和常量折叠的溢出语义;原生 C/C++ 探针使用有定义的无符号算术。改变哈希也会改变冲突与探查路径, 所以要保存完整键,测试长词、平局和扩容,并核对每次完整输出。使用同一个全语料容量镜像,重新拟合事件模型、留出验证, 再测核心段落。检验之前不要承诺 IPC 或时间提升。现有语料约有 1940 万字母,但这道练习没有生成新的账本行。

  6. ★ 研究:动态最优性。 证明伸展树是动态最优的(在每个访问序列上与最好的二叉搜索树算法相差 O(1) 倍以内),或者给出 任何一个 o(log log n) 竞争比的 BST 算法。

    从哪里开始。 猜想:斯莱特与塔扬,《自调整二叉搜索树》(1985)。最优值的下界:威尔伯(1989)的交错界与漏斗界; 勒孔特与温斯坦(2020)理清了二者的关系。O(log log n) 竞争比的树:探戈树(德迈纳、哈蒙、亚科诺与珀特拉什库,2004), 多重伸展树(王、德里贝里与斯莱特,2006)。几何观点:德迈纳、哈蒙、亚科诺、凯恩与珀特拉什库,《二叉搜索树的几何》 (2009),以 Greedy 算法(卢卡斯 1988,芒罗 2000)作为另一个候选。综述:亚科诺,《追寻动态最优性猜想》(2013); 列维与塔扬(2019)。尚未解决的:(a)任何 O(1) 竞争比的 BST,无论伸展树、Greedy 还是别的;(b)威尔伯的漏斗界是否 与最优值相差常数倍以内;(c)在这里动手测量:对小的 n,用搜索比较伸展树、Greedy(用几何方式模拟)与离线最优, 寻找比值增长的序列。

Build the film

python -m videos.cs.cs17.compute        # the part's numbers, into .cache/cs17
python tools/build.py cs17                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs17 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs17. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs17.compute           # every number in the part (about ten minutes)
python tools/build.py cs17 -q l            # a 480p preview
python tools/build.py cs17                 # 1080p