Algorithms in Modern CS

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.

Route a problem to its chapter

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

Name the Shape First

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.

Grow the input

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.

1,000,000

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.

  1. Do I look up one item by its key? Hash table or B-tree (Chapters 1 and 8).
  2. Do I need order, or only the best few? Sort or heap (Chapter 2).
  3. Are the items linked to each other? A graph algorithm (Chapters 3 and 4).
  4. Do I build the best answer from smaller choices? Greedy or dynamic programming (Chapters 5 and 6).
  5. Do I work with huge numbers? Number theory (Chapter 7).
  6. Is no fast exact method known? A heuristic or an approximation (Chapter 9).

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.

The road

  1. Find one item by its key: hash tables and B-trees, in PostgreSQL.
  2. Keep only the best few: heaps, quicksort and merging, in PostgreSQL's sort.
  3. Put work in a safe order: topological sort, in Python's graphlib.
  4. Route around a broken link: Dijkstra in OSPF, Bellman-Ford in RIP.
  5. Give common symbols short codes: Huffman's greedy code, in DEFLATE.
  6. Reuse the answers to smaller problems: edit distance, git diff and the query planner.
  7. Raise a number to a huge power: repeated squaring, in RSA.
  8. Add a server without moving every key: consistent hashing, in Dynamo.
  9. Know when perfect costs too much: graph coloring for registers.
  10. The field guide: the map, the checklist, the code, every source.
You double the input and a job takes four times as long. Which growth rate does that suggest?

Chapter 1

Find One Item by Its Key

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.

Say it aloud

h equals the ceiling of log base m of N.

h
h the levels of the tree: the pages one search reads.
⌈ ⌉
the ceiling of round up to the next whole number, because a part level is still a page.
logm
log base m how many times you multiply by m to reach the number.
N
N the number of keys in the index.
In plain words

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 numbers

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.

Ask for one key, then a range

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.

100 million

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.

A query asks for all orders between two dates. Which index can serve it?

Chapter 2

Keep Only the Best Few

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.

Say it aloud

C is about n times log base two of k.

C
C the comparisons the heap makes in the worst case.
n
n the items that stream past.
log2
log base two how many times you halve to get to 1: the levels of the heap.
k
k how many of the best items you keep.
In plain words

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 numbers

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.

Stream scores past a heap

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.

5

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.

You keep the top 10 of a stream in a min-heap. A new score arrives that is smaller than the root. What happens?

Chapter 3

Put Work in a Safe Order

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.

Build in waves

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.

Kahn's method empties its queue, but two targets still have in-degree 1. What does that prove?

Chapter 4

Route Around a Broken Link

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).

Say it aloud

d of v becomes the smaller of d of v, and d of u plus w of u v.

d(v)
d of v the cheapest cost from A to router v found so far.
min
the smaller of keep whichever of the two costs is lower.
d(u)
d of u the final cost from A to router u, just settled.
w(u, v)
w of u v the cost of the link from u to v.
In plain words

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.

With numbers

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.

Cut a link, then reroute

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.

d(D) is 10. Router B is settled with d(B) = 3, and the link B to D costs 5. What is d(D) after relaxing that link?

Chapter 5

Give Common Symbols Short Codes

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.

Merge the two rarest

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).

Say it aloud

B of T equals the sum over each letter c of f of c times d of c.

B(T)
B of T the bits the code tree T needs for the whole file.
Σc
the sum over c add one term for each letter.
f(c)
f of c how many times letter c appears.
d(c)
d of c the depth of c in the tree: the bits in its code.
In plain words

Multiply each letter's count f by its code length d. Add the products. That is B, the size of the coded file.

With numbers

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.

The heap holds subtrees with counts 9, 12, 14 and 30. Which two does Huffman merge next?

Chapter 6

Reuse the Answers to Smaller Problems

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.

Say it aloud

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.

E(i, j)
E of i j the fewest edits from the first i letters of a to the first j letters of b.
min
the smallest of try all three last moves and keep the cheapest.
E(i−1, j) + 1
E of i minus one j, plus one delete a-i.
E(i, j−1) + 1
E of i j minus one, plus one insert b-j.
[ai ≠ bj]
one if a-i differs from b-j keep the letter for free, or swap it for one edit.
In plain words

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.

With numbers

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.

Fill the edit table

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.

E(2, 2) = 1, E(2, 3) = 2, E(3, 2) = 2, and a3 = b3. What is E(3, 3)?

Chapter 7

Raise a Number to a Huge Power

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.

Say it aloud

c equals m to the e, mod n.

c
c the ciphertext, a number below n.
m
m the message, written as a number below n.
e
to the e the public exponent: multiply m by itself e times.
mod
mod keep only the remainder after dividing by n.
n
n the modulus, the product of two secret primes p and q.
In plain words

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 numbers

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.

Square your way through the bits

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.

An exponent is 1011 in binary. How many multiplications does repeated squaring make, starting from m?

Chapter 8

Add a Server Without Moving Every Key

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.

Say it aloud

M is about K over N plus one.

M
M the keys that move when one server joins the ring.
K
K all the keys stored.
N + 1
N plus one the servers after the new one joins.
In plain words

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 numbers

With K = 10,000 and N = 100: M ≈ 10,000 / 101 ≈ 99 keys move. With mod N, about 9,900 move: 100 times more.

Add a server to the ring

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.

A ring holds 12,000 keys on 5 servers. You add a sixth. About how many keys move?

Chapter 9

Know When Perfect Costs Too Much

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.

  1. Simplify. A node with fewer than k neighbours can always get a color later. Remove it and push it on a stack.
  2. Spill. If every node left has k or more neighbours, pick one to spill and remove it.
  3. Select. Pop the stack and give each node the lowest color its neighbours do not use.

Give out the registers

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.

With k = 3 registers, a node has 2 neighbours left in the graph. What can the heuristic do with it?

Chapter 10

The Field Guide

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.

ProblemQuestionToolReal system and source
Find a row by idLook up by key, on diskB-tree, CLRS 18PostgreSQL default index (manual, Index Types)
Match one exact keyLook up by key, no rangesHash table, CLRS 11PostgreSQL hash index, equality only (same page)
Top k of manyOnly the best fewMin-heap, CLRS 6PostgreSQL top-N heapsort (tuplesort.c)
Sort more than memoryFull orderQuicksort runs, k-way merge, CLRS 7, CLRS 2PostgreSQL external sort (tuplesort.c)
Build orderLinked items, order of workTopological sort, CLRS 22Python graphlib.TopologicalSorter (docs)
Route packetsLinked items, cheapest pathDijkstra, Bellman-Ford, CLRS 24OSPF (RFC 2328), RIP (RFC 2453)
Compress a fileBest answer, greedy is safeHuffman code, CLRS 16DEFLATE (RFC 1951), in gzip (RFC 1952)
Show a diffBest answer from smaller onesEdit distance, CLRS 15git diff, Myers by default (git-diff manual)
Encrypt with RSAHuge numbersRepeated squaring, CLRS 31RFC 8017; Python three-argument pow
Grow a cache clusterLook up by key, many machinesConsistent hashing, CLRS 11Dynamo (DeCandia and others, 2007)
Assign registersNo fast exact methodColoring heuristic, CLRS 34, 35Chaitin (1982)
Wire offices cheaplyLinked items, cheapest treeMinimum spanning tree, CLRS 23No product claim
Match riders to driversLinked items, pairingMax flow, CLRS 26No product claim

The checklist

  1. Write the hot step as one sentence: what goes in, what comes out.
  2. Ask the six questions in order, and note every yes.
  3. Price the naive way and the chosen tool at your real size.
  4. Check the failure the chapter names. Examples: a range on a hash, k near n, a cycle, a negative cost, greed without proof.
  5. Measure on real data. If the time grows faster than you priced, go back to step 2.

The core, in Python

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

The series

Each chapter of this capstone leaned on one or two full lessons. The rest of the series fills in the tools behind them.

The takeaway. Name the shape before you write the code. Six questions lead to a chapter, and the chapter's numbers tell you if the plan will hold at your real size.
A service must return the 50 cheapest flights out of 2 million fares, many times a second. Which tool fits first?

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.

Sources

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.

CLRS Capstone · Algorithms in Modern CS
Back to the start of the series · Back to Gleams