A real problem never says which algorithm it needs. Ask six questions about its shape and it points to a CLRS chapter. The right chapter turns 100 million row reads into 3 page reads.
Pick a problem. Watch it fall through the six questions and land on a chapter, with the cost of the naive way beside the cost of the right tool. Then we walk each question on one real system, built from parts you already know.
You need a little Python and some of the CLRS series; each chapter links the full lesson it uses.
The capstone of our series on Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Every claim about a real system is checked against its documentation, its source code or its paper; the Field Guide lists them. Previous: Approximation Algorithms. Start of the series: Getting Started.
Costs are counts of basic steps for the sizes named in each problem, worked in the chapter it links. The bars use a log scale; a bar that runs off the right edge is larger than 1020. The sizes are illustrative; the algorithms and systems are real.
Chapter 0
See how the shape of a job, not the speed of the code, decides whether it finishes
You run a site with a million users. Each night a job compares every account with every other account to find duplicate emails. It takes 17 minutes. Next year you have ten million users, and the same job takes more than a day.
The code is fine. The shape of the job is wrong. Comparing all pairs costs about n2 steps for n accounts. Sort the accounts by email first, and equal emails sit side by side; one pass over the sorted list finds them. That costs about n log2 n steps.
Each bar is the time one job takes at a billion steps per second, on a log scale. Drag n and watch the n squared bar run away from the rest.
Illustrative: one step per nanosecond, constants ignored. Real code is slower by a constant factor; the gaps between the rows stay.
At a million accounts, n2 is 1012 steps: 1,000 seconds. n log2 n is about 20 million steps: 20 milliseconds. No faster machine closes a gap of 50,000 times. Picking the chapter that fits the shape does.
Every CLRS chapter is a tool for one shape. This capstone does not re-teach them. It trains the step before: look at a problem and ask which shape it has. Six questions cover most of what you will meet.
The failure. Symptom: a job that was fine on test data slows down much faster than the data grows. Measure: time it at n and at 2n. If the time quadruples, it is quadratic. Fix: find the step that touches every pair, and ask which of the six questions it answers.
Chapter 1
Choose between a hash table and a B-tree by asking whether you will ever need a range
A user logs in with id 48,213,907. The users table holds 100 million rows on disk. Checking every row means 100 million reads. How does the database find one row in a few?
Two CLRS structures answer this. A hash table (CLRS 11) turns the key into a slot number and looks only there. A B-tree (CLRS 18) keeps the keys sorted in wide nodes, one disk page each, so each read picks one child out of hundreds.
PostgreSQL offers both. Its manual says CREATE INDEX builds a B-tree by default. A B-tree handles equality and range queries. A hash index stores only a 32-bit hash code of each value, so it handles only equality.
How many pages does a B-tree search read? Call the number of keys N. Call the fan-out, the number of children of a node, m. Call the number of levels, which is the number of pages one search reads, h.
h equals the ceiling of log base m of N.
Each level multiplies the reach by m. Count how many times you must multiply by m to cover N keys, and round up. That count is h.
With N = 100,000,000 and m = 500: log base 500 of N is 2.96, so h = 3 page reads. A binary tree has m = 2, so h = 27.
Each bar counts the reads to reach the first matching row, on a log scale. Switch the query to a range and watch the hash index fall back to a full scan.
Worst case, nothing cached. B-tree fan-out m = 500 is illustrative; real fan-out depends on page and key size. A hash probe is counted as 1 read. For a range, the B-tree then walks the matching leaves in order.
The failure. Symptom: a report filtered by created > '2026-01-01' stays slow, though the column has an index. Measure: EXPLAIN shows a sequential scan. Fix: if the index is a hash index, it cannot serve a range; build a B-tree on the column.
Chapter 2
Use a small heap when you need the top k, and a full sort only when you need everything in order
A game has a million scores. The home page shows the top 10. Sorting all million scores to show ten throws away almost all of the work.
Keep a min-heap (CLRS 6) of the 10 best scores so far. Its root is the smallest of the ten: the bar to beat. Compare each new score with the root. If it loses, drop it. If it wins, it replaces the root and sinks to its place in about log2 10 levels.
Call the number of items n, the number you keep k, and the comparisons the heap makes C.
C is about n times log base two of k.
Each of the n items costs at most one trip down a heap of k items. That trip is log base two of k levels. A full sort pays log base two of n for each item instead.
With n = 1,000,000 and k = 10: log2 10 = 3.32, so C ≈ 3.3 million. A full sort costs n log2 n ≈ 20 million comparisons, 6 times more.
Thirty scores arrive left to right. The heap keeps the best k; its root, in warm, is the score to beat. Press Play, then change k.
The scores are a fixed made-up stream. Comparisons are counted inside a real binary heap; the full sort cost is the estimate n log2 n.
PostgreSQL does exactly this. Its sort module, tuplesort.c, switches to a "bounded heap" when the query has a LIMIT and the input passes twice the limit; EXPLAIN calls it top-N heapsort. A sort that fits in work_mem uses quicksort (CLRS 7). A larger one writes sorted runs to disk and joins them with a balanced k-way merge. That is the merge step of CLRS 2, run on many lists at once.
The failure. Symptom: the heap version is no faster than sorting. Measure: compare k with n. Fix: when k nears n, log k nears log n, so sort instead. PostgreSQL's "twice the limit" rule is this check.
Chapter 3
Turn a list of needs into a build order, and catch the loop that makes any order impossible
You build seven software targets. lib needs core. app needs net and ui. Build app first and it fails, because its parts do not exist yet.
The targets and their needs form a directed acyclic graph (DAG): an arrow from each target to every target that needs it, and no loop. A topological order (CLRS 22) lists the targets so that every arrow points forward.
Kahn's method finds one. Count each target's unmet needs: its in-degree. Build every target at zero. When a target is done, subtract one from each target that needed it. Repeat until nothing is left.
Each badge is a target's unmet needs. Press Step to build every target at zero. Then add the loop and try again.
A made-up project of 7 targets and 8 needs. Each wave builds every target whose needs are met; with enough workers, a wave runs in parallel.
The worked number. Kahn's method touches each target once and each arrow once. With 7 targets and 8 arrows, that is 7 + 8 = 15 steps. The waves are: core; utils and lib; net and ui; app; tests. Five waves, so five rounds with enough workers.
Python ships this method. The standard library's graphlib.TopologicalSorter takes a map from each node to its predecessors. Its get_ready() returns the nodes whose needs are met, which can be built in parallel. Its documentation states that a complete order exists only if the graph has no directed cycle.
The failure. Symptom: the build stops with targets left over, or Python raises CycleError. Measure: list the targets whose in-degree never reached zero; the loop is among them. Fix: break the loop, for example by moving the shared code into a new target that both can need.
Chapter 4
Settle routers one at a time from nearest to farthest, and see why the map must be complete
Links with costs join six routers. Packets from A should reach F by the cheapest path. Then the link from B to D fails, and every router must find a new path.
OSPF, the routing protocol of RFC 2328, gives every router the full map of links. Each router then builds a tree of shortest paths with itself as the root. The RFC names the method: Dijkstra's algorithm (CLRS 24).
One step does the work. Call the best known distance from A to a router v d(v). Call the cost of the link from u to v w(u, v).
d of v becomes the smaller of d of v, and d of u plus w of u v.
You have just settled router u. For each neighbour v, price the route that goes through u: d of u plus the link cost w. If that beats d of v, keep it. This step is called relaxing the link.
From A, the direct link gives d(B) = 4. Then Dijkstra settles C with d(C) = 2. The link C to B costs 1. So d(B) = min(4, 2 + 1) = 3: B is now reached through C.
Dijkstra's algorithm repeats one move: settle the unsettled router with the smallest d, then relax its links. A min-heap finds that router fast. Costs must not be negative, or a settled router could later get cheaper.
Numbers on the links are costs; numbers by the routers are d. Pick a broken link, then press Play to settle the routers in order.
A made-up network. Settled routers turn green; the warm links form the shortest-path tree; the pink path is the route from A to F.
All links up, the route is A, C, B, D, E, F at cost 13. Cut B to D and it becomes A, C, D, E, F at cost 15. Each router needs only its own map to recompute.
The failure, in the other family. RIP (RFC 2453) is based on Bellman-Ford: each router hears only its neighbours' distances. When a network becomes unreachable, routers can raise their costs to it slowly, one exchange at a time. The RFC calls this "counting to infinity". RIP sets infinity to 16 to stop it soon, so a RIP network cannot be more than 15 hops wide.
Chapter 5
Merge the two rarest symbols again and again, and get the shortest prefix code there is
A file uses six letters. Out of every 100 letters, a appears 45 times, b 13, c 12, d 16, e 9 and f 5. A fixed code gives each letter 3 bits, so 100 letters cost 300 bits. Can common letters get shorter codes?
They can, if no code is the start of another, so the reader always knows where a letter ends. Such a code is a prefix code, and it is a binary tree. Each letter is a leaf. Its code is the path from the root: 0 for left, 1 for right.
Huffman's algorithm (CLRS 16) builds the best tree greedily. Put every letter in a min-heap by count. Take out the two smallest, join them under a new node whose count is their sum, and put it back. Stop when one tree is left.
The top line is the heap of subtree counts. Teal marks the two smallest, which merge next. Press Step until one tree is left, then read the codes.
The six counts are the example of CLRS section 16.3. Ties do not occur in this example; with ties, other trees of the same cost are possible.
How good is a tree? Call a letter c, its count f(c), and the length of its code, which is its depth in the tree, d(c). Call the total bits for the file B(T).
B of T equals the sum over each letter c of f of c times d of c.
Multiply each letter's count f by its code length d. Add the products. That is B, the size of the coded file.
The Huffman tree gives a 1 bit, b, c and d 3 bits, e and f 4 bits. B = 45 × 1 + (13 + 12 + 16) × 3 + (9 + 5) × 4 = 45 + 123 + 56 = 224 bits, 25% less than 300.
This is in your files today. DEFLATE (RFC 1951), the method inside gzip (RFC 1952), compresses each block with LZ77 and Huffman coding. LZ77 first replaces repeated strings with back references; Huffman codes then shrink the symbols that remain.
The failure: greed without proof. Make 6 cents from coins of 1, 3 and 4. Greedy takes the biggest coin first: 4 + 1 + 1, three coins. The best is 3 + 3, two coins. Measure: compare the greedy answer with an exact one on small cases. Fix: use greedy only where CLRS 16 proves it safe; otherwise use the next chapter.
Chapter 6
Fill a table once instead of solving the same small problem millions of times
You change a file and run git diff. It shows the fewest lines to delete and add to turn the old file into the new one. Under it sits a question from CLRS 15: what is the smallest number of edits between two sequences?
Take two words, a and b. Call the edits needed to turn the first i letters of a into the first j letters of b E(i, j). Call letter i of a ai and letter j of b bj.
E of i j is the smallest of: E of i minus one j, plus one; E of i j minus one, plus one; and E of i minus one j minus one, plus one if a-i differs from b-j.
The last move is a delete, an insert, or a keep-or-swap. Each leaves a smaller problem whose answer is already in the table. Add the cost of the last move and keep the cheapest. E with an empty word is the other word's length.
kitten to sitting: E(6, 7) = 3 (swap k for s, swap e for i, insert g). The table has 7 × 8 = 56 cells, each filled once.
Each cell reads the three cells above and to the left, in warm. Press Play; at the end, the pink path is the edit script.
Plain recursion counts are computed exactly for each pair. git compares lines, not letters, but the question is the same.
Real tools build on this. git's default diff is Myers' algorithm, which its manual calls "the basic greedy diff algorithm". Myers' 1986 paper solves the same shortest edit problem. Its time grows with the number of differences, not with the table size. PostgreSQL's planner chooses a join order by a near-exhaustive search that, its manual says, IBM's System R introduced. Selinger and colleagues (1979) built that search as dynamic programming over sets of tables. For 12 or more tables PostgreSQL switches to a genetic search (geqo_threshold).
The failure. Symptom: a recursive solution that gets far slower with each extra letter. Measure: count the calls. Plain recursion on kitten and sitting makes 29,737 calls for 56 distinct answers. On two 20-line files it makes about 3.9 × 1014 calls for 441 cells. Fix: store each answer the first time.
Chapter 7
Read the exponent in binary and square, so a 2048-bit power costs thousands of steps, not more than atoms in the universe
Your browser encrypts a key with RSA. RFC 8017, the RSA standard, writes the encryption step in one line. Call the message, as a number, m, the public exponent e, the public modulus n, and the ciphertext c.
c equals m to the e, mod n.
Raise m to the power e, divide by n, and keep the remainder. That remainder is c. Decryption does the same with the private exponent d in place of e.
With toy primes 61 and 53: n = 3,233, e = 17, d = 2,753. The message m = 65 gives c = 6517 mod 3,233 = 2,790, and 2,7902,753 mod 3,233 = 65 again.
Multiplying m by itself e − 1 times is hopeless when e has 2048 bits. Repeated squaring (CLRS 31) reads e in binary from the left. Start with m for the leading 1. For each later bit, square the result; if the bit is 1, also multiply by m. Take the remainder mod n after every step, so no number grows past n2.
Each box is one bit of the exponent. Warm marks the bit being read. Press Play and compare the count with e − 1 plain multiplications.
Toy key from primes 61 and 53, all values mod 3,233. Real keys use moduli of thousands of bits; this toy one factors at a glance.
The count. e = 17 is 10001 in binary: four squarings and one multiply, 5 multiplications instead of 16. d = 2,753 has 12 bits: 15 instead of 2,752. A 2048-bit exponent needs at most 2 × 2047 = 4,094. Python's pow(base, exp, mod) does this; its documentation says it is "computed more efficiently than pow(base, exp) % mod".
The failure. Symptom: the code runs out of memory or never returns. Measure: look for m ** e % n. Even the toy 652,753 has 4,991 digits before the remainder. Fix: reduce mod n after every multiplication, or call the three-argument pow.
Chapter 8
Put keys and servers on one hash ring, so a new server takes keys only from its neighbour
A cache spreads 10,000 keys over 100 servers with the rule server = hash(key) mod 100. Traffic grows, and you add server 101. Now the rule is hash(key) mod 101, and almost every key maps to a different server. The cache is suddenly empty.
A key stays put only if its hash leaves the same remainder for 100 and for 101. That holds for about 1 key in 101. So about 9,900 of the 10,000 keys move. In our test with MD5 hashes, 9,918 moved.
Consistent hashing uses the same hash functions as CLRS 11 in a new way. Hash the servers and the keys onto one circle, the ring. Each key belongs to the first server clockwise from it. A new server takes over only the arc just before it, which was its clockwise neighbour's.
Call the number of keys K, the number of servers before the change N, and the keys that move M.
M is about K over N plus one.
After the join there are N + 1 servers, each owning about an equal share of the ring. Only the new server's share moves. So divide K by N + 1.
With K = 10,000 and N = 100: M ≈ 10,000 / 101 ≈ 99 keys move. With mod N, about 9,900 move: 100 times more.
Dots are 200 keys; purple ticks are server positions. Press Add server; keys that change server turn red. Switch to mod N and add again.
200 made-up keys and up to 12 servers, placed by a 32-bit FNV-1a hash. Keys keep their place on the circle under both rules; only their owner changes.
Amazon's Dynamo paper (DeCandia and others, SOSP 2007) partitions its data this way. It states the gain plainly: "departure or arrival of a node only affects its immediate neighbors".
The failure. Symptom: with few servers, one server holds far more keys than the rest. Measure: compare the busiest server's keys with the average. Fix: give each server many ring positions, called virtual nodes, as Dynamo does. Turn them off above and watch the busiest server grow.
Chapter 9
Recognise a problem with no known fast exact method, and switch to a heuristic that can spill
A compiler must put 8 variables into a CPU's registers. Two variables that are alive at the same moment cannot share a register. With too few registers, some variables must be spilled: kept in memory, which is slower.
Draw a node for each variable and a line between any two that are alive together. This is the interference graph. Giving registers is now graph coloring: give each node one of k colors, so that no line joins two nodes of the same color. Chaitin set register allocation up this way in 1982.
Deciding whether a graph can be colored with 3 colors is NP-complete (CLRS 34). No one knows a method that is fast for every graph. So Chaitin's allocator uses a heuristic.
Lines join variables alive at the same time. Pick how many registers, then press Play: nodes leave the graph, then come back with a register or a spill.
A made-up graph of 8 variables and 12 conflicts. This toy spills the node with the most neighbours; real allocators weigh how often each variable is used.
The worked number. With 3 registers, every node simplifies and all 8 get a register. With 2, the heuristic spills e and c. No 2-coloring exists anyway: a, b and c are all joined, a triangle, and a triangle needs 3 colors. Trying every coloring of 40 variables with 16 registers would mean 1640, about 1.5 × 1048, tries.
The failure. Symptom: an exact search that is fine on small inputs and never ends on larger ones. Measure: add a few items and see if the time multiplies each time. Fix: check if the problem is NP-complete; if it is, use a heuristic, or an approximation with a proven bound, as in CLRS 35.
Chapter 10
Keep the map from problem shape to chapter, the checklist, the core code and every source
A real system is many small tools joined together. Name the shape of each hot step, pick the chapter, then check the cost with numbers. Here is the map this capstone used, with the source for each real system.
| Problem | Question | Tool | Real system and source |
|---|---|---|---|
| Find a row by id | Look up by key, on disk | B-tree, CLRS 18 | PostgreSQL default index (manual, Index Types) |
| Match one exact key | Look up by key, no ranges | Hash table, CLRS 11 | PostgreSQL hash index, equality only (same page) |
| Top k of many | Only the best few | Min-heap, CLRS 6 | PostgreSQL top-N heapsort (tuplesort.c) |
| Sort more than memory | Full order | Quicksort runs, k-way merge, CLRS 7, CLRS 2 | PostgreSQL external sort (tuplesort.c) |
| Build order | Linked items, order of work | Topological sort, CLRS 22 | Python graphlib.TopologicalSorter (docs) |
| Route packets | Linked items, cheapest path | Dijkstra, Bellman-Ford, CLRS 24 | OSPF (RFC 2328), RIP (RFC 2453) |
| Compress a file | Best answer, greedy is safe | Huffman code, CLRS 16 | DEFLATE (RFC 1951), in gzip (RFC 1952) |
| Show a diff | Best answer from smaller ones | Edit distance, CLRS 15 | git diff, Myers by default (git-diff manual) |
| Encrypt with RSA | Huge numbers | Repeated squaring, CLRS 31 | RFC 8017; Python three-argument pow |
| Grow a cache cluster | Look up by key, many machines | Consistent hashing, CLRS 11 | Dynamo (DeCandia and others, 2007) |
| Assign registers | No fast exact method | Coloring heuristic, CLRS 34, 35 | Chaitin (1982) |
| Wire offices cheaply | Linked items, cheapest tree | Minimum spanning tree, CLRS 23 | No product claim |
| Match riders to drivers | Linked items, pairing | Max flow, CLRS 26 | No product claim |
The standard library holds most of these tools. One line each:
pythonimport heapq, bisect from graphlib import TopologicalSorter users = {48213907: "ada"} # hash table: one exact key (Ch 1) scores = [72, 95, 88, 61] ids = sorted(users); i = bisect.bisect_left(ids, 48000000) # sorted keys: a range starts here (Ch 1) top10 = heapq.nlargest(10, scores) # bounded heap: top k (Ch 2) order = list(TopologicalSorter({"lib": ["core"], "app": ["lib"]}).static_order()) # (Ch 3) c = pow(65, 17, 3233) # repeated squaring: 2790 (Ch 7) def dijkstra(graph, src): # graph: {u: [(v, w), ...]}, w >= 0 (Ch 4) d, pq = {src: 0}, [(0, src)] while pq: du, u = heapq.heappop(pq) if du > d[u]: continue # a stale heap entry for v, w in graph[u]: if du + w < d.get(v, float("inf")): # relax the link d[v] = du + w; heapq.heappush(pq, (d[v], v)) return d def edit(a, b): # the table of Ch 6, one row at a time prev = list(range(len(b) + 1)) for i, x in enumerate(a, 1): cur = [i] for j, y in enumerate(b, 1): cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y))) prev = cur return prev[-1] # edit("kitten", "sitting") == 3
Each chapter of this capstone leaned on one or two full lessons. The rest of the series fills in the tools behind them.
Now press Present or Teach. Take three problems from your own work and route each one through the six questions out loud. Then go back to the router and check your answers.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press. The Huffman counts are the example of section 16.3.
Systems: PostgreSQL manual, Index Types, Genetic Query Optimizer and geqo_threshold; PostgreSQL source, tuplesort.c; Python documentation, graphlib, pow and heapq; RFC 2328 (OSPF), RFC 2453 (RIP), RFC 1951 (DEFLATE), RFC 1952 (gzip), RFC 8017 (RSA); git-diff manual.
Papers: G. DeCandia and others, "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007; G. J. Chaitin, "Register Allocation and Spilling via Graph Coloring", SIGPLAN Symposium on Compiler Construction, 1982; E. W. Myers, "An O(ND) Difference Algorithm and Its Variations", Algorithmica, 1986; P. G. Selinger and others, "Access Path Selection in a Relational Database Management System", SIGMOD 1979. The devices, toy networks and graphs are our own.