Answers

The answers to each chapter’s self-check problems, chapter by chapter.

Contracts and cost models

The keys to the exercises, under the numbers the chapter gives them.

Exercises

Exercise 1

Which build broke it? Builds 0 to 100: build 0 works, build 100 crashes, and once a build crashes every later one does. Find the first build that crashes.

  • fewest tests: Seven. The first crashing build is one of 1 to 100, so the tests must tell 100 answers apart. Each test has two answers, so six tests reach at most 2^6 = 64 leaves, too few, and seven reach 2^7 = 128. The sentence is “the first crashing build is after lo and at most hi”, where lo is a build known to work and hi one known to crash, starting from 0 and 100. The tests go 50 works, 75 crashes, 62 works, 68 works, 71 works, 73 crashes, 72 works. That is seven tests, and the answer is 73.
  • two machines: Two tests at builds a < b can never come back “a crashes, b works”, because once a build crashes every later one does. So an hour has three possible answers, not four. Since 3^4 = 81 < 100, four hours cannot always be enough. Five are, since 3^5 = 243. Test the two builds that cut the candidates into three near-equal parts, and keep the part the answers point to. It is the nine balls on the balance scale, with two tests in place of one weighing.
  • checking the answer: Builds 72 and 73. Run 72 and see it work, run 73 and see it crash. Two tests check an answer that took seven to find. With builds 40 to 49 crashing, the search still tests 50 first, sees it work, and reports 73 after the same seven tests. The colleague’s check still holds, since 72 works and 73 crashes, so build 73 really did break something. But it is not the first crashing build. That is 40. The sentence relied on “once a build crashes, every later one does”. Without it, the search still finds a working build followed by a crashing one, but not necessarily the first.

Exercise 2

Heavier or lighter. Why does distinguishing 2n possibilities change the bound, and how many weighings do twelve balls need?

  • why: each of the n balls can be the odd one in two ways, heavier or lighter, so a strategy’s tree needs at least 2n leaves, one per possibility. A weighing has three outcomes, so k weighings reach at most 3^k leaves, and the bound becomes \lceil \log_3 (2n) \rceil weighings.
  • twelve balls: three. Two weighings give at most 3^2 = 9 leaves, fewer than 24; three give 27.
  • a strategy that does it in three: weigh 1–4 against 5–8.
    • They balance: the odd ball is among 9–12. Weigh 9, 10, 11 against 1, 2, 3 (known to be good). If that balances, 12 is the odd ball, and weighing it against 1 says heavier or lighter. If 9–11 go down, the odd ball is heavy among them: weigh 9 against 10, and the heavier one, or 11 if they balance, is it. If 9–11 go up, the same with lighter.
    • 1–4 go down (by symmetry the same when 5–8 go down): the odd ball is a heavy one of 1–4 or a light one of 5–8. Weigh 1, 2, 5 against 3, 6, 9. Left down: 1 or 2 is heavy, or 6 is light; weigh 1 against 2, and the heavier is it, or 6 if they balance. Right down: 3 is heavy or 5 is light; weigh 3 against 9: if 3 goes down it is heavy, and if they balance 5 is light. Balance: 4 is heavy, or 7 or 8 is light; weigh 7 against 8, and the lighter is it, or 4 if they balance.

Exercise 3

Close the gap. Prove the \Omega(n \log n) sorting bound cleanly from \log_2(n!), using Stirling’s approximation.

  • the bound: a comparison sort is a tree with at least n! leaves, one per order of the input, and each comparison has two outcomes, so its worst case makes at least \log_2(n!) comparisons.
  • Stirling: \ln(n!) = n \ln n - n + O(\log n), so \log_2(n!) = n \log_2 n - n \log_2 e + O(\log n), with \log_2 e \approx 1.443. The leading term is n \log_2 n, so \log_2(n!) = \Theta(n \log n), and every comparison sort makes \Omega(n \log n) comparisons in its worst case.
  • a check without Stirling: the largest n/2 factors of n! are each at least n/2, so n! \ge (n/2)^{n/2} and \log_2(n!) \ge \tfrac{n}{2} \log_2 \tfrac{n}{2}, which is already \Omega(n \log n).

Exercise 4

What makes it true? “Hashing is O(1)”, “appending to a growable array is O(1)”, “a binary search on disk is fast”.

  • hashing is O(1): true as an expected cost, with a hash function that spreads keys at random, a table kept from filling up, and keys that fit in a word, so hashing one is one step. False in the worst case: keys that all land in one place make a lookup cost as much as the keys it holds. False too when a key is long, since computing its number reads all of it.
  • appending is O(1): true amortized, over a run of appends (Exercise 6). False in the worst case for one append: the one that doubles the array copies everything.
  • binary search on disk is fast: true when you count steps, about \log_2 n comparisons. False when you count block transfers, the model for a disk: nearly every probe lands in a different block, so it costs about \log_2 n slow trips, where a structure built for blocks (the search chapter’s B-tree) needs far fewer.

Exercise 5

How does it fail? For binary search, a hash table and the small yes-or-no summary, name the assumption and the failure mode. Which of the three fail silently, and how would you notice?

  • binary search: assumes the list is sorted. Without it, it can answer “not here” about a key that is there. Silent: nothing crashes. You notice by checking the order, or by catching a “not here” for a key you know is present.
  • hash table: assumes the hash function spreads the keys. Without it, keys pile up in a few places and operations slow down toward a scan of everything. The answers stay right; only the cost fails, and silently. You notice by timing it, or by counting how many keys share a place.
  • small yes-or-no summary: assumes that whoever asks can live with a rare wrong “yes”. Its failure mode is a wrong “yes”: it may say “yes” when the true answer is “no”, silently, and its promise allows that. A fuller answer adds that the promised rarity holds only within its size; filled past it, wrong yeses grow more frequent. You notice only by asking the full data behind it, and you measure how often it happens by doing that on keys you know are absent.
  • which are silent: all three. None of them crashes or warns.

Exercise 6

Pay for the doubling. A growable array starts empty and doubles when full. Show that n appends cost O(n) in total, giving an amortized cost of O(1) per append, even though one append occasionally costs O(n).

  • the count: each append writes one item, n writes in all. Copies happen only when the array is full and doubles, at sizes 1, 2, 4, \ldots up to below n, and together they copy 1 + 2 + 4 + \cdots < 2n items in total. So n appends cost fewer than 3n steps: O(n) in total, O(1) amortized per append.
  • the expensive one: an append that finds the array full copies all k items it holds before writing, so that one costs O(k), up to O(n). The total stays small because each copy of k items comes only after the k/2 cheap appends that filled the second half of the array.

Exercise 7

Find the wrong one that passes. Three specifications for “remove the smallest item from a collection”.

  • wrong but meets (a): remove the largest item, or any item at all.
  • wrong but meets (b): return the smallest item and remove nothing; or return a value smaller than everything, such as -\infty, that was never in the collection.
  • why (c) admits no wrong one: the returned item was in the collection and is no larger than anything left, so it is a smallest item; the collection afterwards holds exactly what it held, minus one copy of the returned item, so exactly that one copy was removed. With ties, any copy of the smallest value is equally correct.
  • the empty collection: (c) cannot be met, because there is no item to return. It must say what happens: for example, “on an empty collection, report that it is empty and change nothing”, or state that the collection must not be empty when remove_min is called.

Exercise 8

Drop the other half. Keep only “the output is a rearrangement of the input”. Name, in one line, a wrong sort the weakened specification now admits.

  • a wrong sort it admits: return the input unchanged. It holds exactly the items it was given, and is not in order.

Search

The keys to the exercises, under the numbers the chapter gives them.

Run it and report the state

Exercise 1

Build a list that refuses duplicates by inserting 4, 9, 4, 2, 9, 7 one at a time, checking each key against the keys you have accepted so far, from the first, and stopping at a match. What does the list hold at the end, and how many key comparisons did the build cost?

  • list: [4, 9, 2, 7]
  • comparisons: 9

4 distinct keys on their own cost 4 × 3 / 2 = 6. The two duplicates add the other 3: a duplicate stops at the match rather than scanning the whole list, which is why it is not simply 6 × 5 / 2 = 15.

Exercise 2

Here is a sorted row of fifteen keys: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44. Binary search it for 14, and write down every key at which the search looks, in order.

  • probes: [23, 11, 17, 14]
  • compares: 4
  • outcome: found

Exercise 3

Here is a sorted row of fifteen keys: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44. Binary search it for 33, and write down every key at which the search looks, in order.

  • probes: [23, 35, 29, 32]
  • compares: 4
  • outcome: absent

Exercise 4

Insert 60, 30, 80, 20, 45, 70, 90, 40, 50, 42 into an empty binary search tree. How tall is it, counting nodes (a single node has height 1)? What are ceiling(55), rank(43) and select(6), counting from select(0) as the smallest key?

  • height: 5. This book counts to the empty spot below the deepest node, so a single node is a tree of height one. A text that counts edges will say 4. Accept either, provided the reader says which they used.
  • ceiling(55): 60
  • rank(43): 4
  • select(6): 60

43 is not in the tree, and rank still answers: the number of keys smaller than it.

Exercise 5

From the tree you built in Exercise 4, delete 30 by copying the successor’s key up into the node (Hibbard’s deletion, delete_hibbard in the companion library). Which key now sits where 30 was, and what hangs off it?

  • key in that slot: 40
  • its left: 20
  • its right: 45
  • where the successor’s own child went: 42, now the left child of 45
  • inorder: [20, 40, 42, 45, 50, 60, 70, 80, 90]

the other deletion, moving the successor node itself (the library’s delete), leaves the same keys in the same shape, but built from different nodes: the node that held 40 now sits where 30 was.

Exercise 6

Insert 75, 51, 79, 9, 36, 72, 40, 71, 70, 66, 4, 69 into an empty left-leaning red-black tree. Which keys have a red link into them?

  • red links into: [4, 51]
  • root: 71
  • height: 5. This book counts to the empty spot below the deepest node, so a single node is a tree of height one. A text that counts edges will say 4. Accept either, provided the reader says which they used.

Exercise 7

Starting from an empty left-leaning red-black tree, insert D, C, A, B, E, then F. After each insert, name every repair that fires (rotate left, rotate right, flip colors), in order, or say that none fires. Letters compare in alphabetical order.

  • D: ['none']
  • C: ['none']
  • A: ['rotate_right', 'flip_colors']
  • B: ['rotate_left']
  • E: ['rotate_left']
  • F: ['flip_colors', 'rotate_left']

inserting F is the one to watch: the flip sends a red link up a level, where it leans right, so a rotate left fires one level higher. A repair can cause the next one up.

Exercise 8

Build the left-leaning red-black tree from 10, 20, 30, 40, 50, 60, then delete the smallest key twice in a row. Each time, say whether move_red_left fired, and at which node, and draw the tree afterwards.

  • built: ((10 20* 30) 40 (50* 60 ·))
  • delete 10: move_red_left at [20]; tree ((20* 30 ·) 40 (50* 60 ·))
  • delete 20: no push; tree (30 40 (50* 60 ·))
  • notation: (left key right), * marks a red link into the key

Then: If the second deletion needed no push at all, explain what the first one left behind that made it unnecessary.

Answer to the follow-up:

the first walk left the link into 20 red, so the second walk found a red link already waiting and had nothing to push.

Exercise 9

Chapter 1 listed five things that a left-leaning red-black tree holds true at once, before you had met the tree. Without scrolling back, write all five. Then, for each one, name the repair in this chapter that puts it back when an insert breaks it, or say that an insert never breaks it. Check your list against the box for the left-leaning tree (The design 2.2).

The keys are in order: an insert never breaks it, since the new key goes where a search for it ends and a rotation keeps the order. The top node is black: a color flip at the top can paint it red, so the insert ends by painting it black again. A red link leans left: rotate left. No node has two red links touching it: two chained below each other, rotate right, which leaves one on each side; one on each side, flip colors, which sends the red up a level. Every path crosses the same number of black links: an insert never breaks it, since the new key arrives on a red link and every rotation and flip keeps each path’s black count. If you missed one of the five, that is the one to reread in the chapter.

Exercise 10

Insert 17, 21, 8, 48, 27, 32, 11 into an empty B-tree of minimum degree t = 2, so each node holds at most 3 keys, using the chapter’s top-down insertion. What keys are in the leftmost leaf?

  • leftmost leaf: [8, 11]
  • root: [17, 27]
  • height: 2. This book counts to the empty spot below the deepest node, so a single node is a tree of height one. A text that counts edges will say 1. Accept either, provided the reader says which they used.

Exercise 11

Build the B-tree at t = 2, top-down as in the chapter, from 17, 21, 8, 48, 27, 32, 11, 7, then delete 27 and then 48. Draw the tree after each. Each time, say which of the chapter’s moves the deletion used: replacing the key with its predecessor or successor, redistributing a key from a neighbor, or merging two nodes. Then say what decided the move each time: where the key sat, and what its children or neighbors held.

  • built: ([17, 27], [[7, 8, 11], [21], [32, 48]])
  • after deleting 27: ([17, 32], [[7, 8, 11], [21], [48]])
  • after deleting 48: ([17], [[7, 8, 11], [21, 32]])
  • moves: 27 sits in the root, so it cannot simply be removed: it is replaced by a neighbor in sorted order. Its left child is at the minimum and cannot give up the predecessor, so the successor 32 comes up from the right child, which had a key to spare; nothing is redistributed and nothing merges. 48 sits in a leaf at the minimum, so that leaf is topped up before the walk steps into it, and its only neighbor has nothing to spare either: the key between them comes down out of the parent and the two merge, then 48 is taken out. What decided it: the first key sat in an internal node, which needs a replacement, and a child could afford one; the second sat in a leaf, and no neighbor could afford anything.

Exercise 12

Give a B-tree room for three keys per node (minimum degree t = 2) and insert 1 through 20 in order, splitting top-down as the chapter does. How many splits happen, how tall is the tree at the end, and how many nodes does a search for 17 fetch? Then count the same search in the plain binary search tree that the same insertions build, and say the most that any search can fetch in a perfectly balanced binary search tree of 20 keys.

  • splits: 13
  • height: 4. This book counts to the empty spot below the deepest node, so a single node is a tree of height one. A text that counts edges will say 3. Accept either, provided the reader says which they used.
  • root: [8]
  • search for 17 fetches: 4
  • plain binary search tree: 17
  • perfectly balanced, at most: 5

Exercise 13

Keep the chapter’s list of where things are, allowing yourself three entries before a trip. In this order: the keys go in the hall bowl, the tickets go in the desk drawer, then the keys move to your coat pocket, and the spare charger goes in the car; then the tickets move to your wallet, the spare charger is thrown away, the passport goes on the top shelf, and the umbrella goes by the door. Write out both sealed pages and the list exactly as they end up. Then answer “where are the keys?”, “where is the umbrella?” and “where is the flashlight?”, counting how many pages each question touched.

  • Page 1: keys: coat pocket, spare charger: car, tickets: desk drawer
  • Page 2: passport: top shelf, spare charger: gone, tickets: wallet
  • the list: umbrella: by the door
  • keys: coat pocket, 2 pages
  • umbrella: by the door, 0 pages
  • flashlight: nowhere, 2 pages

the keys changed place before the first trip, while the list was still unsealed, so the list line was simply corrected: Page 1 holds one entry for them, not two. Only a sealed page is never changed.

Then: The keys changed place before the first trip. Does Page 1 hold one entry for them or two, and why is that allowed when a page is never changed? Then say which of the three questions a Bloom filter on each page would have made cheaper, and by how many pages.

Answer to the follow-up: One entry. Before the trip the list is not sealed, so a change corrects its line; only sealed pages are never touched. With a filter on each page, the flashlight drops from two pages to none, and the keys from two to one: Page 2’s filter says they are not there, so only Page 1 is read. Each barring a false positive. The umbrella question never reached a page, so it gains nothing.

Which promise broke

Exercise 14

The model returns the reference tree with this changed: exchange the keys 70 and 72, touching no link and no color.

  • promises now false: the keys are in order

Exercise 15

A different tree, built from 20, 10, 30: paint the top node (20) red.

  • promises now false: the top node is black

Exercise 16

On the reference tree, apply rotate_right at the root (71), exactly as the repair code does.

  • promises now false: a red link always leans left

Exercise 17

A tree of three nodes: a black link into 30, a red link into 20 as 30’s left child, and a red link into 10 as 20’s left child.

  • promises now false: no node has two red links touching it, not one on each side, and not one chained below the other

Exercise 18

On the reference tree, repaint the link into 51 from red to black.

  • promises now false: every path crosses the same number of black links

Exercise 19

The same twelve keys, inserted in this order instead: 4, 79, 69, 71, 51, 9, 40, 75, 70, 72, 36, 66.

  • promises now false: none. This tree is valid, and saying so is the answer.

Exercise 20

On the reference tree, repaint the link into 69 from black to red.

  • promises now false: a red link always leans left; no node has two red links touching it, not one on each side, and not one chained below the other; every path crosses the same number of black links

Why this exercise exists, and why the trees before it took four different kinds of edit: the promises are not independent. Of the twelve single-link repaints on this tree, only 4 break exactly one promise, and every one of those breaks black height.

  • breaks 1: every path crosses the same number of black links by repainting 51 (red→black), 4 (red→black), 66 (black→red), 72 (black→red)
  • breaks 2: a red link always leans left; every path crosses the same number of black links by repainting 40 (black→red), 70 (black→red), 79 (black→red)
  • breaks 2: no node has two red links touching it, not one on each side, and not one chained below the other; every path crosses the same number of black links by repainting 36 (black→red), 9 (black→red)
  • breaks 2: the top node is black; no node has two red links touching it, not one on each side, and not one chained below the other by repainting 71 (black→red)
  • breaks 3: a red link always leans left; no node has two red links touching it, not one on each side, and not one chained below the other; every path crosses the same number of black links by repainting 69 (black→red), 75 (black→red)

Repainting 75 creates no chain of reds, yet it breaks the two-red promise: 71’s link to 51 is already red, so 71 gets a red link on each side.

Then: Count how many promises that one repaint took down, then say whether the count means the promises are badly chosen, or something else.

Answer to the follow-up: 3. The promises are not badly chosen: they are not independent. One link’s color takes part in several of them at once (which way reds lean, whether two reds touch, how many black links a path crosses), so a single repaint can break several. Five separate promises are still the right way to state them, because each can also fail alone, as the other items show.

You supply the input

Exercise 21

Make a plain binary search tree on the keys 1 to 8 as tall as it can possibly be. Give the insertion order. Then find a second order that reaches the same height but does not look sorted, and say what all such orders have in common.

order height verdict
[4, 2, 6, 1, 3, 5, 7, 8] (a student who balanced it) 4 reject
[1, 2, 3, 4, 5, 6, 7, 8] (sorted) 8 accept
[8, 7, 6, 5, 4, 3, 2, 1] (reverse sorted) 8 accept
[1, 8, 2, 7, 3, 6, 4, 5] (zig-zag) 8 accept

The zig-zag is the one worth discussing: it looks like the least orderly of the four and reaches the same height as sorted. What matters is that every key is the smallest or the largest of the keys not yet inserted; how disordered the order looks makes no difference.

Then: How many of the 8! possible orders of the eight keys reach that height? Guess first, then count.

Answer to the follow-up: 128, which is 2 to the 7th: every key but the last must be the smallest or the largest of those still to come, a choice of two at each of seven steps. Checked by building all 40,320 orders.

Exercise 22

Now do the same to the left-leaning red-black tree: find an insertion order of 1 to 8 that makes it 8 tall, or as tall as you can. Predict what will happen before you run anything, and write the prediction down.

order height valid
[1, 2, 3, 4, 5, 6, 7, 8] (sorted) 4 True
[8, 7, 6, 5, 4, 3, 2, 1] (reverse sorted) 4 True
[1, 8, 2, 7, 3, 6, 4, 5] (zig-zag) 4 True

No order reaches 8. That refusal is the whole purchase: the repair on every insert bought the property that the adversary’s choice of order stops mattering.

Then: State what you found as a sentence about insertion orders rather than about trees.

Answer to the follow-up: Every one of the 40,320 orders of 1 to 8 gives height exactly 4, which is also the least any tree on 8 keys can have: the order the keys arrive in stopped being something anyone can use against the tree.

Exercise 23

Falsify this (find a case that shows it is false): two people who insert the same fifteen keys into a B-tree at minimum degree t = 2, in different orders, end up with the same tree. Then measure the height of every tree you built while falsifying it.

False. Over 202 insertion orders of 1 to 15 the root came out 17 different ways:

  • sorted: [1, 2, 3, 4, 5, 6]... → root [4, 8]
  • reverse: [15, 14, 13, 12, 11, 10]... → root [8, 12]
  • random: [13, 11, 7, 12, 15, 1]... → root [11]

And the part worth more than the falsification: every one of those orders gave the same height. The set of heights observed is [3].

Then: Of the two things you checked, the tree’s shape and its height, say which of them a caller is entitled to depend on, which of them the caller is not entitled to depend on, and why the second is not a bug.

Answer to the follow-up: The height. The guarantee held while the shape moved. What a caller may depend on is the height staying within its logarithmic bound; the shape is not promised, and is not a bug. That every order here gave the same height is a fact about fifteen keys, not the promise itself. The same point closes the appendix’s derivation exercise, where it costs two hours rather than a minute.

Exercise 24

Falsify this: binary search makes a sorted array beat the tree at everything, so the trees were never needed. Your answer has to name an operation and count something, not name a structure.

  • claim: a sorted array with binary search dominates the tree
  • counter-workload (one acceptable answer; the reader picks their own): 1000 keys already in place, then 100 inserts arriving in uniformly random positions
  • key moves the array pays, expected: 52475
  • key moves the array pays, one simulated run: 50927
  • key moves the tree pays: 0
  • note: lookups really are comparable, so the falsification has to name the operation rather than the structure. Accept any answer near the expected figure: the point is the order of magnitude against zero, not the third digit. A reader who answers 50000 has used 1000/2 for every insert and missed that the array grows as it absorbs them.

Then: State the workload under which the claim is actually true.

Answer to the follow-up: A static or read-only set: nothing is inserted or deleted after the array is built, so no insert ever shoves, and the array’s lookups are as fast as the tree’s with less space and better locality.

Which idea do you reach for

Exercise 25

A messaging service keeps, for every conversation, the messages in time order. Reads ask for the newest few. Writes arrive in bursts, far faster than reads, and a message is never edited once sent. Which idea do you reach for first?

  • (a) slack in the levels below
  • → (b) keep it in layers
  • (c) work in blocks
  • (d) fingerprinting

Answer: (b) Never write in place: seal each batch, reconcile at read time. You buy the write path and pay read amplification and compaction.

Then: Name the failure mode you just bought, in this chapter’s terms.

Answer to the follow-up: Either of the chapter’s two. From the choosing table: a deleted message comes back with its old value, or an accepted write is gone after a crash, and no error says so. From the box’s Assumes line: a burst that outruns the merging piles up unmerged batches until new writes have to wait. What you pay even when nothing breaks is a cost, not a failure mode: read amplification, since a read may consult several layers.

Exercise 26

A read-only dataset of 40 million records ships once a month on a disk image and is loaded into memory on arrival. Every query is a lookup by id, or asks for all records whose ids fall between two bounds. Nothing is ever inserted between shipments. Which idea do you reach for first?

  • (a) slack in the levels below
  • (b) keep it in layers
  • → (c) divide and conquer
  • (d) pay in installments

Answer: (c) Nothing changes, so the one cost a sorted array cannot pay, moving keys on insert, is never charged. Slack would be paid for nothing.

Then: What single change to this workload would make your answer wrong?

Answer to the follow-up: Inserts between shipments. Each one would shove keys along the array, and the cost the array never had to pay becomes the dominant one; slack in the levels below, or layers if the inserts come fast, is then the answer. Also right: data that outgrows memory, so every probe becomes a fetch and work in blocks wins.

Exercise 27

A service must answer “have we seen this id before?” for a stream of billions of ids, in memory that holds only a small fraction of them, where a wrong “yes” costs one wasted lookup and a wrong “no” corrupts the records. Which idea do you reach for?

  • → (a) fingerprinting
  • (b) work in blocks
  • (c) keep an invariant
  • (d) randomization

Answer: (a) One-sided error is the whole point: it may say maybe-present when the key is absent, never absent when it is present.

Then: Errors here have two directions. Say what your choice does to each of them, and why that matches this workload.

Answer to the follow-up: A wrong yes (the filter says maybe, the id is new) happens now and then and costs the one wasted lookup the workload can afford. A wrong no never happens, and that is the error that would corrupt the records.

Exercise 28

An index is a plain binary search tree, and its keys are ids chosen by whoever is calling. One caller has worked out that a particular arrival order makes every lookup slow. You cannot change the tree’s code, because it is a library on which you depend. You can change only the order in which keys are handed to it: the index is rebuilt from scratch every night from the full list of ids, and you may reorder that list before passing it on. The ids are opaque tokens: the library can compare them, but your code cannot compare them. Which idea do you reach for?

  • (a) slack in the levels below
  • (b) divide and conquer
  • → (c) randomization
  • (d) work in blocks

Answer: (c) Slack in the levels below is the better fix and is ruled out by the stem: it means replacing the structure. With only the arrival order under your control, you take the choice away from the caller, which turns a worst case they can aim at into one nobody can.

Then: Compare the guarantee you just bought against a balanced tree’s guarantee, in one sentence.

Answer to the follow-up: A balanced tree is logarithmic on every order, guaranteed; the shuffle makes it logarithmic in expectation, with a small chance of a bad tree that no caller can aim at. It holds only because you shuffle the whole list: if keys arrived in batches you could only reorder one at a time, the caller could still aim across batches, and only the balanced tree would stop that.

Exercise 29

A sorted array is the right structure for a read-heavy index, but a few hundred inserts a day do arrive, and each one shoves a large part of the array along, stalling the service for a visible moment. The total work is affordable; it is the spikes that are not affordable. Which idea do you reach for?

  • (a) pay in installments
  • (b) divide and conquer
  • → (c) spread the work out
  • (d) keep an invariant

Answer: (c) Collect the inserts to one side and merge them into the array a small piece at a time, a few steps per operation. Paying in installments is the tempting answer and the wrong one: it says the day’s total is affordable, which the question already grants, and promises nothing about the one insert that stalls. Doing the work in small pieces is what takes the spike away. The total cost is unchanged and may even rise slightly; what changes is that no single operation carries it.

Then: Name a workload where this is the wrong trade, and say what about that workload makes it wrong.

Answer to the follow-up: An insert-heavy one. Spreading the work out spreads a cost without shrinking it, so once inserts are frequent the total shoving is no longer affordable however it is spread; the structure itself has to change, to slack in the levels below. Also right: a workload where nobody waits on a single insert, such as an overnight rebuild, where spreading the work out only adds bookkeeping.

Exercise 30

An in-memory red-black tree holds a hundred million keys. A profiler says lookups spend nearly all their time waiting on memory rather than comparing: almost every node visited is a cache miss, and each miss brings in a whole cache line, typically 64 bytes, of which the node uses a fraction. Nothing moved off the machine. Which idea do you reach for?

  • (a) divide and conquer
  • → (b) work in blocks
  • (c) randomization
  • (d) keep an invariant

Answer: (b) The comparison stopped being the unit of cost; reaching a node started being it, even inside one machine. Widen the node until it fills a cache line, and the same log₂ n halvings cost far fewer misses: the B-tree’s idea, at a block of 64 bytes instead of a disk page.

Then: Name the block here, and say why a disk or a network round trip would have led you to the same idea.

Answer to the follow-up: The block is the 64-byte cache line. A disk page and a network round trip have the same shape at a larger block: reaching a node costs far more than comparing inside it, so the node is widened to fill whatever one fetch brings back.

Exercise 31

An in-memory index must support lookup, ordered iteration, and range queries, with reads and writes in about equal numbers. The keys are timestamps from thousands of sensors whose readings arrive late: each sensor’s keys come in increasing order, but a new key can land anywhere in the range already stored. You control the structure entirely. Which idea do you reach for?

  • (a) divide and conquer
  • (b) keep it in layers
  • → (c) slack in the levels below
  • (d) fingerprinting

Answer: (c) A new key can land anywhere, so a sorted array shoves on every insert, and each sensor’s increasing run is exactly the order that degrades a plain tree to a list. Room below every node absorbs an arrival wherever it lands, and a balanced tree keeps the height logarithmic whatever the order.

Then: Say why each of the three wrong answers fails here.

Answer to the follow-up: Divide and conquer over a sorted array: arrivals land anywhere, so every insert shoves. Keep it in layers: it makes writes cheap by making reads consult several levels, and writes are not the dominant cost here. Fingerprinting: it answers membership only and throws the order away, so no iteration and no ranges.

Exercise 32

You add a subtree-size field to every node so the tree can answer rank and select. Insert maintains it. A colleague now adds a delete, and a bulk-load path that builds nodes directly. What makes the field safe to read?

  • → (a) keep an invariant
  • (b) pay in installments
  • (c) work in blocks
  • (d) randomization

Answer: (a) A derived field is only as good as the weakest operation that touches a node. Every path that builds or rewrites a node has to restore it, or the field stops being a fact about the tree and becomes a fact about which code ran last.

Then: This is the same risk that the broken trees in Exercises 14 to 20 showed: a promise that holds only until a new code path touches the nodes. Say why.

Answer to the follow-up: In those exercises a refactored insert path broke a promise the old insert kept; here delete and bulk-load break one insert keeps, because nobody taught them it. Either way a promise holds only while every path that writes a node restores it.

Exercise 33

A nightly batch job appends a hundred million log events to a growable array that doubles its capacity whenever it is full. The job is judged only on when the whole run finishes; nobody waits on any single append. A reviewer objects that some appends copy the entire array. Which idea says the objection does not matter here?

  • → (a) pay in installments
  • (b) spread the work out
  • (c) work in blocks
  • (d) slack in the levels below

Answer: (a) Because the capacity doubles, all the copies together cost at most about twice the number of appends, so the run stays linear: each rare expensive append is paid for by the many cheap ones before it. Nobody waits on a single append, so a promise about the total is exactly the one needed. Spreading the copy out would add work and code to protect a latency nobody sees.

Then: Change one thing about the workload that would make (b) the right answer instead.

Answer to the follow-up: Put a caller with a deadline behind every append, say a live service logging each request as it happens. Then the one append that copies the whole array is a missed deadline, and the copy has to be done a few elements at a time.

The tests pass. What did they miss?

Exercise 34

A colleague’s key-value store is an LSM-tree: writes go into a memtable, a full memtable is flushed to a sorted file that is never edited again, deletes write tombstones, reads go newest first, and compaction merges files in the background. Three tests guard it, and all three pass: after any random sequence of writes and deletes, every read agrees with a plain dictionary given the same sequence; the same holds after every compaction; and every file on disk is sorted and unchanged once written. In its first week the machine loses power. The store restarts cleanly and every file is intact, but the last few hundred writes that the service had confirmed to its callers are gone. Name the requirement that the tests never stated, and write it as one sentence that a test could check.

Answer: Every write the store has confirmed to a caller must still be readable after the machine loses power and restarts, at any moment. All three tests ran inside one living process, so the memtable, which is memory and does not survive a power cut, never had to survive anything. The requirement is about confirmation, not about files: the files were intact, and correct for everything they held.

Then: Describe the test that would have failed, then say what the store must do to pass it and what that costs on every write.

Answer to the follow-up: The test: run a random sequence of writes and cut the power at a random point, or imitate the cut by stopping the process without warning and throwing away every write the device had not yet confirmed as landed; restart, and check that every write confirmed before the cut reads back. To pass, append each write to a write-ahead log and wait for the device to confirm it landed before confirming the write to the caller; replay the log into the memtable on restart; discard a log segment only once its memtable is flushed. The cost is the wait for the device on every confirmed write, which is why real systems group many writes into one confirmation and pay it once per group.

Fill in the contract

Exercise 35

A weather network has thousands of stations, and together they send tens of thousands of readings a second, all day. Each reading must be confirmed to its station within ten milliseconds, every time, even in the busiest minute of the year, and a confirmed reading must never be lost, even in a power cut. Reads are rare: a weekly report per station, and now and then a look at one station over one afternoon, and nobody minds if that takes a few seconds. Work out the parts of a contract for this workload, in the order in which the contracts chapter works them out, one or two sentences each, and name the assumptions that these promises need.

Answer, one line per question. Grade on the promises kept apart, not on the wording:

  1. Goal: take tens of thousands of small writes a second, confirm each one within ten milliseconds, and never lose a confirmed reading; the rare reads ask for one station over a time range.
  2. Scarce resource: time on each write’s path, because every confirmation has a deadline, and the slow part is waiting for the disk.
  3. Floor: a reading cannot be confirmed before it has reached the disk, so each confirmation waits for at least one disk write, which many readings can share.
  4. Promise: every confirmed reading can be read back afterwards, power cut or not, and a query returns exactly the confirmed readings for that station and time range. What must remain true: every confirmed reading is on disk, in the log or in a flushed file.
  5. Ideas: keep it in layers and pay in installments, so writes land in memory and the sorting and merging is charged to many writes; spread the work out, so the merging runs in the background and no write waits for it; and a write-ahead log, appended before each confirmation, so a power cut loses nothing confirmed.
  6. Cost and what it refuses: a write costs one in-memory insert, its share of one log append and of the wait for the device to confirm it, and its share of the merges that rewrite it several times on its way down; a read may look in several files and is slow.
  7. Assumes: arrivals, bursts included, stay within a bound low enough that a reading’s whole wait fits in ten milliseconds: waiting in line, waiting for its group of writes to fill, being processed, and the device confirming that the log append landed; background merging keeps up with that workload; and a write the device has confirmed survives a power cut. If merging falls behind, unmerged batches pile up until writes wait, and the deadline breaks. Reconsider when reads become frequent or must be fast (a B-tree, or Bloom filters and more merging), or when arrivals outrun merging for long stretches (split the stations across machines).

Then: This workload makes three separate promises. Name them, name the idea that keeps each one, and say which of the three costs something on every single write.

Answer to the follow-up: A cheap total: pay in installments. No long wait on any one write: spread the work out, since installments promise an average and say nothing about the write that triggers a merge. Confirmed means kept: the write-ahead log. The log is the one that costs something on every write, the wait for the disk, which is why many readings share one append. An answer that covers all three with paying in installments has kept only the first.

Fix the code, the box, or the design?

Exercise 36

An AI writes an LSM-tree from its design box. Its memtable holds two entries, every flush is merged straight into the first level, and each level may hold twice as many as the one above. Its compaction drops every tombstone it meets, in every merge. Write a to f with the values 1 to 6, then delete a and write g. A read of a returns 1. Every batch on disk is sorted and never changed, and every level is within its budget: the store’s validity check passes. Which of the three is it, and why?

Answer: fix the code. The box promises that a read gets nothing once the newest write was a delete. This read returns 1, so the code breaks the promise. The tombstone was dropped in a merge while an older batch further down still held a, and the read found that batch. A tombstone may go only in a merge with nothing older beneath it.

Then: Write a test you would keep from the AI that fails on this code, and say why checking the invariants could not catch it.

Answer to the follow-up: Run random writes and deletes on the store and on a plain dictionary, with a memtable small enough that merges reach the third level, and compare every read, deleted keys above all. The invariants are about the batches’ shape, sorted and within budget, and this bug leaves the shape right and the contents wrong, so only the promise sees it. You may also add the tombstone rule to the box as an invariant, so a check can catch it; the repair is still in the code.

Exercise 37

An AI writes a left-leaning red-black tree from its design box, as an index of 100,000 product numbers kept on disk, each node in its own block. Every check of the tree passes, and every lookup is right. But a lookup reads 16 blocks on average and up to 22, and one read from the disk costs far more than all the comparisons. A colleague says the tree must be out of balance. Which of the three is it, and why?

Answer: change the design. The tree keeps its promise and its cost: 22 is well under twice log₂ of 100,000, about 33, so it is balanced. What fails is the line Assumes: reaching any node costs about the same, as in the RAM model. On disk, reaching a node is a block read, and a node with one key uses one key of the block it costs. The B-tree fills the block with one wide node: at t = 64, the same numbers take up to 3 block reads per lookup.

Then: Rewrite the lines of the box that no longer fit the job, and say what you would measure to check the new design.

Answer to the follow-up: Goal: a search tree for memory that hands over whole blocks, each fetch costing far more than looking inside it, which is the B-tree’s goal. Idea: work in blocks, so one block read buys a whole node, as many keys as fill the block. Cost: \Theta(\log_t n) block reads per lookup in the worst case, up to 3 here at t = 64, with one node per block and nothing cached; a key found in the root costs one. Assumes: one node fills one block. Measure block reads per lookup, not comparisons, and keep the old lookup tests, since the promise has not changed.

Derive it

Exercise 38

The appendix states the standard tree’s five invariants and stops. It does not give you its repair procedure. Derive it. Then say what the analogy was: which object mapped to which, and which move mapped to which.

Given to the reader: the 2-3 tree behind LLRB, and why LLRB’s three moves are what they are; the appendix’s encoding: a black node with its red children is one node of a 2-3-4 tree (black alone = 1 key, +1 red = 2 keys, +2 reds = 3 keys); the B-tree section, where you traced splits at minimum degree t = 2

The routes

A. through the encoding — Translate the red-black tree into its 2-3-4 tree. Ask what a 2-3-4 tree does when a key lands in a node that is already full. Translate the answer back.

B. by moving LLRB’s trigger — LLRB and the standard tree run the same moves. LLRB refuses to hold a 4-node, so it splits the moment a node would hold three keys. The standard tree allows 4-nodes, so it splits one key later. Same moves, trigger moved by one.

C. through the B-tree you already traced — A B-tree of minimum degree t = 2 holds one to three keys per node. That is a 2-3-4 tree. You built one in the B-tree section and were not told what it was called. It splits on the way down, though, and the standard repair splits on the way back up: follow the B-tree’s timing and you reach a valid relative of the standard repair, not the repair itself. Move the split to after the key lands and the routes agree.

The three self-checks

Predict, before running anything: which is more common on random keys, the split (the key lands in a full node) or the absorb (the node has room)? By roughly what ratio? Then measure it.

The absorb, about two to one. Over a million inserts into standard red-black trees on random keys (ten trees of 100,000 keys): 34.3% land in a node that is already full and split it, 65.7% land in a node with room. A reader who predicted ‘splitting is rare’ is closer than one who predicted a coin flip, and the reason is that there are simply more non-full nodes than full ones at any moment.

Check your procedure against a real one. The companion library ships a standard red-black tree, built to the textbook rules rather than this chapter’s: algodesign.searching.RBTree, in red_black_standard.py. This is the oracle, the reference against which you check. First, after every insertion, check that your tree holds exactly the keys inserted and keeps the five invariants. Then run its repair over the same keys and compare the trees node by node. A mismatch may be a bug, or a different, also valid, repair procedure for the same rules: say which yours is, and why. Splitting full nodes on the way down, as this chapter’s B-tree does, is one such procedure. The next check is about exactly that.

A derivation of the standard repair agrees with it node by node. Two checks settle the derivation, in this order. First, after every insert your tree holds exactly the keys inserted and keeps the five invariants: that says your procedure is correct. Then compare node by node with RBTree: agreement says it is the standard repair, not just a valid one. A mismatch with the keys and invariants intact is not a bug: the standard rules allow a 3-node to be drawn with its red child on either side, so a repair can choose differently and stay valid. A procedure that splits on the way down disagrees with it on some sequences and is still a valid relative, not the standard repair; the third check shows where.

Now a comparison that does not come out equal. Build the same keys as a B-tree at t = 2, and group the library’s RBTree into its 2-3-4 nodes. Both are 2-3-4 trees on the same keys. They are often different 2-3-4 trees, though they never differ on eight keys or fewer. Find the smallest key sequence where they differ, say what is still true of both, and explain the difference. It comes down to one line in the two procedures.

Nine keys, and 1 to 9 in order is one of them. Exhaustive over every permutation of 1..8 – all 40,320 – the two agree; the first disagreement appears at nine. There, the B-tree gives (1)(2)(3)(4)(5)(6)(7 8 9) and the red-black grouping gives (1)(2 4 6)(3)(5)(7 8 9).

What stays true of both: same keys, every node holding one to three keys, every leaf at the same depth. Both are valid 2-3-4 trees.

The difference is WHEN each one splits. The chapter’s B-tree splits a full node on the way DOWN, before descending through it, so a node is never full when a key arrives beneath it. The red-black repair runs on the way back UP, splitting only once the key has landed. Same rule, opposite side of the descent, and the answer to the exercise’s second question counts top-down splitting as a procedure for the same rules, not a new set. Over 3,000 random 12-key orders the two disagree 48% of the time, so a reader who finds them differing has found the truth, not a bug.

The mapping the answer has to make explicit
2-3-4 tree standard red-black tree
2-3-4 tree standard red-black tree you already know it as
a node holding 1 key black node, no red children a 2-node
a node holding 2 keys black node, one red child a 3-node
a node holding 3 keys black node, two red children a 4-node, full
node is not full, absorb the key parent is black: no repair fires at all the easy case
node is full, split it: middle key rises, halves become separate nodes uncle is RED: recolor parent and uncle black, grandparent red, continue from the grandparent the split, and the rise is why the walk continues upward
node is not full, but the binary drawing of it is illegal uncle is BLACK: rotate, once or twice, to reach the legal drawing no split: only the encoding needs fixing
the root splits the root is forced black at the end the one place the tree gets taller

Punchline. ‘Uncle is red’ is not a rule about uncles. It is how a binary tree says ‘the node I am inserting into is already full’.

Q1 (How many distinct routes reach this derivation? Find as many as you can, say what each one takes as given, and show they agree.) At least three, above. They are not rephrasings: A starts from the abstract structure, B starts from an algorithm you already have and moves one trigger, C starts from a tree you already drew. A student who finds only one has not finished.

Q2 (Harder. Every structure in this family keeps the same headline promise: the height stays within a constant factor of log₂ n, so search, insert and delete are all logarithmic. How many different sets of rules keep it? Not: how many ways to derive one set. How many sets are there, and what separates them?) Infinitely many. Two you have met are red-black rule sets: the left-leaning tree this chapter builds, and the standard either-leaning tree. Splitting full nodes on the way down is a different procedure for the standard tree’s rules, not a new set. Andersson’s AA tree stores a level number in place of a color, but its rules are the left-leaning tree’s rules mirrored, so it is the same point seen in a mirror. Reflecting any of these left-for-right gives a mirror image, which is the same structure rather than a new member – a reader who counts it separately has counted one point twice. Beyond these the count never stops: allowing the two sides of every node to differ in height by up to k, for any fixed integer k ≥ 1, keeps the height within a constant factor of log₂ n, a constant that grows with k.

A reader who answers AVL is right, and the answer is better than the question deserved: AVL keeps the same headline promise with a tighter height bound, by a different mechanism, and it is already in this chapter’s own table of primitives. Take that answer.

What separates the family is not correctness. It is how many distinct broken shapes a repair must recognize, against how tight the height bound comes out, against how much work per operation is bounded. Each rule set exposes a different trade-off among those three; sharing the logarithmic bound does not settle which one is better on any of them.

Check: Build the same keys as a left-leaning tree and as a standard tree. Compare the shapes, and compare both against the height bound. Over four seeds of 400 random 63-key trials the shapes differ every single time, and both stay under 2·log₂(n+1) = 12.00 in every trial. The left-leaning tree is taller on average by about half a level – mean +0.42 to +0.57 across the four seeds – and the distinction worth keeping is that this is an average, not a rule: the two come out the same height about four times in ten, and the left-leaning tree is the shorter one about one time in twenty. The rules are not the guarantee. They are one way of keeping it.

Strings

The keys to the exercises, under the numbers the chapter gives them.

Run it and report the state

Exercise 1

Slide the pattern aab along the text aabaacaabaab by hand, comparing character by character and moving on at the first mismatch. Where does it occur, and how many character comparisons did the whole scan make?

  • occurrences: [0, 6, 9]
  • comparisons: 21

Exercise 2

The text is the digits 6404137153929 and the pattern is 153, base 10, modulus 13. Write down the fingerprint of every window of three digits, rolling each from the one before. At which positions do the fingerprints agree with the pattern’s fingerprint, and which of those are false alarms?

  • pattern fingerprint: 10
  • window fingerprints: [3, 1, 2, 10, 7, 7, 0, 10, 6, 2, 6]
  • found: [7]
  • false alarms: [3]

Exercise 3

Insert tea, ten, to, inn, in, tent into an empty trie, in that order. How many nodes does it have, root included? How many does it have after squeezing it into a Patricia tree? What does keys_with_prefix("te") return, in order?

  • trie nodes: 10
  • Patricia nodes: 9
  • keys_with_prefix(te): ['tea', 'ten', 'tent']

Exercise 4

Insert romane, romanus, romulus, rubens, ruber into an empty Patricia tree and draw it, every branch labelled. Then insert rubicon. Which branch is cut, and where? How many nodes does the tree have before and after?

  • before:

    r
      om
        an
          e (word)
          us (word)
        ulus (word)
      ube
        ns (word)
        r (word)
  • nodes before: 10

  • after:

    r
      om
        an
          e (word)
          us (word)
        ulus (word)
      ub
        e
          ns (word)
          r (word)
        icon (word)
  • nodes after: 12

Exercise 5

Write the suffix array of abracadabra$, with $ sorting before every letter. Which rows hold the suffixes that begin with abra, and which text positions are they?

  • suffix array: [11, 10, 7, 0, 3, 5, 8, 1, 4, 6, 9, 2]
  • rows: [2, 3]
  • positions, in row order: [7, 0]

Exercise 6

From the suffix array of abracadabra$ (the previous exercise), write its LCP array. What is the longest passage that occurs twice, and which entry tells you? Then fill it in Kasai’s way: visit the positions in text order, 0 to 11, carrying h. For each position, what does h start at, and what does it record?

  • LCP array: [0, 0, 1, 4, 1, 1, 0, 3, 0, 0, 0, 2]
  • longest repeat: abra
  • largest entry, at row: 3
  • h per position:
    • 0: starts at 0, records 4
    • 1: starts at 3, records 3
    • 2: starts at 2, records 2
    • 3: starts at 1, records 1
    • 4: starts at 0, records 0
    • 5: starts at 0, records 1
    • 6: starts at 0, records 0
    • 7: starts at 0, records 1
    • 8: starts at 0, records 0
    • 9: starts at 0, records 0
    • 10: starts at 0, records 0
    • 11: starts at 0, row 0: nothing to compare

Exercise 7

Sort the suffixes of aababa$ by prefix doubling. Give the tag of every position after each round, with tags starting at 1 and $ tagged lowest, until every tag is different. How many doubling rounds did it take, not counting round 0, the tagging by single letters?

  • tags after round 0: [2, 2, 3, 2, 3, 2, 1]
  • tags after round 1: [3, 4, 5, 4, 5, 2, 1]
  • tags after round 2: [3, 5, 7, 4, 6, 2, 1]
  • doubling rounds: 2
  • suffix array: [6, 5, 0, 3, 1, 4, 2]

Exercise 8

Write the Burrows–Wheeler transform of abracadabra$: sort its rotations and read the last column. Where are the runs of equal letters?

  • last column: ard$rcaaaabb
  • first column: $aaaaabbcdrr
  • runs: aaaa in rows 6–9; bb in rows 10–11

Exercise 9

A last column reads omotta$. Recover the text with the LF walk: sort the column to get F, number equal letters, start from the row whose last letter is $, and follow LF. Give the LF value of every row, and the text.

  • LF by row: [3, 2, 4, 5, 6, 1, 0]
  • text: tomato$

Exercise 10

Using only the last column of abracadabra$ (Exercise 8) and its table C, run backward search for bra. Give the interval of rows after each letter, and the count.

  • C: {'$': 0, 'a': 1, 'b': 6, 'c': 8, 'd': 9, 'r': 10}
  • intervals: ['a: [1, 6)', 'ra: [10, 12)', 'bra: [6, 8)']
  • count: 2

Exercise 11

For the bits 0110100111000101 (position 0 first), what are rank(5), rank(11) and rank(16), the number of 1s before each position, and select(0), select(4) and select(7), counting the 1s from zero?

  • rank(5), rank(11), rank(16): [3, 6, 8]
  • select(0), select(4), select(7): [1, 8, 15]

Exercise 12

The FM-index of abracadabra$ keeps a sample at every 4th text position (0, 4 and 8). Find every row whose suffix begins with a, and turn each into its text position by walking LF to a sampled row. How many steps does the longest walk take?

  • rows: [1, 6)
  • position and steps per row:
    • 1: 10 after 2
    • 2: 7 after 3
    • 3: 0 after 0
    • 4: 3 after 3
    • 5: 5 after 1
  • longest walk: 3

Exercise 13

The FM-index of abracadabra$ keeps the row of every 4th text position (0, 4 and 8). Extract the 3 letters starting at position 5, then the 2 letters starting at position 9. For each: which row do you start from, how many LF steps do you walk, and what comes out?

  • 3 letters from 5: start from the row of position 8, 3 LF steps, ‘ada’
  • 2 letters from 9: start from the row of position 0, 3 LF steps, ‘ra’

Exercise 14

Three quotes are joined into one text with a separator between them: frankly my dear, here is looking at you, may the force be with you. The fragment looking is found at one position. Which position, which quote does it fall in, numbered from 0, and which bounds do the two selects give? Then: which quotes does a search for you return?

  • hit: 24
  • quote number: 1
  • bounds: (16, 39)
  • find(you): [1, 2]

Which promise broke

Exercise 15

The suffix array of cocoa$ is 5 4 0 2 3 1.

  • verdict: broken: the rows are not in sorted order
  • detail: rows 2 and 3 are swapped: cocoa$ sorts after coa$; the array is [5, 4, 2, 0, 3, 1]

Exercise 16

The suffix array of pepper$ is 6 1 4 0 3 2 5.

  • verdict: correct
  • suffix array: [6, 1, 4, 0, 3, 2, 5]

Exercise 17

A last column reads ap$p$le, and is said to be the transform of some text.

  • verdict: broken: it holds two$, and a transform holds exactly one
  • detail: the walk would not know which row is the whole text, and the library refuses it

Exercise 18

The LCP array of cocoa$ is 0 0 0 3 0 1.

  • verdict: broken: row 3 claims 3 shared letters
  • detail: its suffix shares 2 letters with the row above; the array is [0, 0, 0, 2, 0, 1]

Exercise 19

A Patricia tree holds cart and card. Below the root it has a branch labelled ca to a node that holds no word, from there a branch r to a node that holds no word, and from there two branches, t and d, each ending a word.

  • verdict: broken: the node aftercaneither branches nor ends a word
  • detail: merge it with its child into one branchcar; the squeezed tree has 4 nodes, not 5

Exercise 20

A fingerprint search for 15 in the digits 31415926, base 10, modulus 7, reports the positions [3, 5].

  • verdict: broken: it reports every fingerprint match without checking the digits
  • detail: only [3] is the pattern; the rest are false alarms

You supply the input

Exercise 21

Find a text of 10 letters and a pattern of 4 letters, both over the letters a and b, that make the plain scan do as many character comparisons as it possibly can. How many is that?

  • maximum: 28
  • an example: text aaaaaaaaaa, pattern aaaa

Then: Say what every text and pattern that reach the maximum have in common.

Answer to the follow-up:

  • every case: every one of the 7 windows is compared to its last character: each window agrees with the pattern on its first 3 letters

Exercise 22

With base 10 and modulus 13, find two different three-digit windows that have the same fingerprint.

  • an example: 100 and 113

Then: Say the rule that decides, for any two numbers, whether they get the same fingerprint.

Answer to the follow-up:

  • the rule: two windows get the same fingerprint exactly when the difference of the numbers they spell is a multiple of 13

Exercise 23

Choose five words of four letters each so that the trie holding them has as many nodes as possible. How many is that, and how many nodes does the Patricia tree of the same words have?

  • trie nodes: 21
  • Patricia nodes: 6

Then: What does that say about when squeezing pays most?

Answer to the follow-up:

  • when squeezing pays most: when the words share nothing: no two share a first letter, so each word hangs from the root as its own chain of single-child nodes, and the Patricia tree squeezes each chain to one node

Exercise 24

Choose a text of 8 letters over a and b, with $ added at the end, that makes prefix doubling run as many rounds as possible. How many doubling rounds does it take, not counting round 0, the tagging by single letters?

  • maximum rounds: 3
  • an example: aaaaaaaa$

Then: Say which property of the text decides the number of rounds.

Answer to the follow-up:

  • the property: the length of the longest passage that occurs twice: the tags are all different once the window is longer than it

Exercise 25

A quote finder joins its quotes with a reserved separator, written | here, and refuses any quote that holds it. It does not check the fragment for which it is asked. With the quotes you had me at hello and show me the money, write a fragment that this finder reports as found, though neither quote contains it.

  • an example: hello|show

Then: Say why keeping the separator out of the quotes is not enough on its own.

Answer to the follow-up:

  • why: with the separator kept out of every quote, a fragment that holds it can only match across a boundary, so a fragment that holds it must find nothing

Which idea do you reach for

Exercise 26

A multiplayer game must check, sixty times a second, that every player’s copy of the game world is still the same as the server’s copy. Sending the whole world each time is far too slow, and a very small chance of missing a difference is acceptable.

  • → (a) fingerprinting
  • (b) divide and conquer
  • (c) sample, then walk
  • (d) work in blocks

Answer: (a) Each side sends one small number computed from its whole world. Equal numbers say almost certainly the same; anything bigger is sent only when they differ.

Exercise 27

A public web service checks whether a pasted paragraph appears in its archive using a rolling fingerprint with a fixed, published modulus. An attacker sends texts that make every window match, and the service slows to a crawl.

  • (a) carry what you know
  • → (b) randomization
  • (c) rank and select
  • (d) canonical form

Answer: (b) Draw the modulus at random for each search, so no input can be written against it in advance.

Exercise 28

A phone keyboard suggests words while you type. The team wants the stored dictionary compact, and still to be correct after words are added and removed every day.

  • (a) doubling
  • → (b) canonical form
  • (c) fingerprinting
  • (d) sample, then walk

Answer: (b) A squeezed tree whose every node branches or ends a word, restored after every insert and removal, stays at about two nodes per word.

Exercise 29

You must sort the positions of every line break in a ten-gigabyte log by what follows them, and many lines repeat long stretches word for word, so comparing strings directly keeps re-reading the same letters.

  • → (a) doubling
  • (b) randomization
  • (c) work in blocks
  • (d) rank and select

Answer: (a) Tag by short prefixes, then sort by pairs of old tags: each round covers twice as many letters without reading any.

Exercise 30

A sorted list of every street name in a country is printed in a thick book, with no index. You need the page where names starting with Mill begin.

  • (a) carry what you know
  • (b) sample, then walk
  • → (c) divide and conquer
  • (d) fingerprinting

Answer: (c) The list is sorted, so each look at the middle of what remains rules out half of it.

Exercise 31

The suffixes of a long text are sorted, one to a row. For every row you need how many opening letters its suffix shares with the suffix in the row above, and computing each one from scratch is far too slow.

  • → (a) carry what you know
  • (b) work in blocks
  • (c) randomization
  • (d) canonical form

Answer: (a) Kasai’s move: sorted order picks the partner, the suffix in the row above; text order is the order to visit the positions, keeping the length from the last one, which can drop by at most one.

Exercise 32

A map app stores, for a billion road segments, one bit saying whether each is a toll road. It must answer how many toll segments come before segment i instantly, and may use only a little more memory than the bits.

  • (a) fingerprinting
  • → (b) rank and select
  • (c) divide and conquer
  • (d) doubling

Answer: (b) That question is rank, answered from a directory of counts in little more space than the bits.

Exercise 33

Storing a running count after every bit of that billion would cost far more than the bits; counting from the start on every question is far too slow. Each question may read only two stored counts and one machine word of bits.

  • (a) sample, then walk
  • → (b) work in blocks
  • (c) randomization
  • (d) carry what you know

Answer: (b) Store counts per big block and, relative to it, per small block; count only the few bits inside one small block.

Exercise 34

A bank numbers every transaction on an account since it was opened, ten years of them, and must quickly show the balance after any numbered transaction, without storing a balance after every transaction.

  • (a) divide and conquer
  • (b) canonical form
  • → (c) sample, then walk
  • (d) rank and select

Answer: (c) Keep the balance after every 1,000th transaction, and get any other by walking through the transactions from the nearest kept one, the way locate walks to a sampled row.

The tests pass. What did they miss?

Exercise 35

A team ships a quote finder built on an FM-index. Its tests pass: for a thousand random fragments, count agrees with a plain scan of the books, and locate returns exactly the positions that the scan finds. In production, people type quotes with straight apostrophes copied from a chat, and the finder says they appear nowhere. What requirement did the tests miss?

Answer: Every test fragment was cut out of the books themselves, so every one used the books’ own bytes. The requirement nobody wrote down is what exact means for a person typing: which differences in characters must not matter.

Then: Write the requirement as a sentence that a test could check.

Answer to the follow-up: For example: a fragment that differs from the text only in the form of an apostrophe, quotation mark or space finds the same quotes.

Exercise 36

An index over song lyrics returns whole songs for a fragment, joining the songs with a reserved separator and finding where each song starts by looking for that byte. Its tests pass: every fragment cut from inside one song returns that song and every other song containing it, and a fragment that occurs nowhere returns nothing. After launch, a lyric site adds one song containing the separator byte inside a line, and from then on some searches return songs that do not contain the fragment. What requirement did the tests miss?

Answer: Every test used the corpus as it was. The requirement nobody tested is that no record may contain the separator or the end marker; without it, the stray byte is taken for a boundary between songs, and matches near it are credited to the wrong song.

Then: Say where the checks belong, and what each must do.

Answer to the follow-up: Two checks, for two different breaks. When the corpus is built: a song that holds a reserved byte is refused, or the byte is replaced, before any index is built, because wherever song boundaries are found from separators, a stray one inside a song moves them. And at query time, separately: a fragment that holds a reserved byte finds nothing, because even in a clean corpus it could only match across the boundary between two songs.

Fix the code, the box, or the design?

Exercise 37

You give an AI the trie’s design box and ask for the code. Its remove walks to the word and clears the mark that says a word ends there, and does nothing else. Insert tea and ten into an empty trie, then remove both. get finds neither word, keys() returns nothing, and the count of words is 0. The trie still has 5 nodes. Which of the three is it, and why?

Answer: fix the code. Every lookup is right, so the promise holds, but invariant 3 breaks: the branches t, e, a and t, e, n lead to no stored word. The box already asks for what you wanted, and the code does not keep it. On the way back up, remove must cut every node left with no word and no children; then the trie is back to 1 node, the root.

Then: Suppose the box had stopped at invariant 2 and said nothing about memory. Which would it be then? Write the line you would add to the box, and a test you would keep from the AI that checks it.

Answer to the follow-up: Fix the box. That code keeps a box without invariant 3; the leftover nodes are what the box failed to forbid. Add 3. Every branch leads to a stored word. The test to keep: insert some words, remove some or all of them, and check that the trie has exactly as many nodes as a trie built fresh from the words that remain; with every word removed, that is one node.

Exercise 38

The same AI’s trie, its remove now mended, holds 2,000 web addresses of a shop, such as https://shop.example.com/products/aaliwuqonsmb/reviews, about 54 letters each. Nothing has been removed, every check of the box’s invariants passes, and every lookup is right. Yet the trie has 36,601 nodes, about 18 per address, and a colleague says the leak is back. Which of the three is it, and why?

Answer: change the design. Nothing is broken. The box’s cost says memory up to a node per letter stored, and addresses that share their start and then never branch again spend a node on every letter of their tail. The promise and the invariants hold; the cost no longer fits a dictionary of long words.

Then: Name the design you would switch to, and say what you would measure to check it.

Answer to the follow-up: The Patricia tree, whose goal is the trie’s job when the words are long: it squeezes every chain into one branch. Its promise is the trie’s, so the same tests of get, insert and remove still apply. Measure the nodes: on these addresses it has 2,649, at most two per address.

Exercise 39

An AI builds the FM-index from its design boxes for a reading app. Asked where i occurs in mississippi$, locate returns [10, 7, 4, 1]; asked for ssi, it returns [5, 2]. The app jumps to the first position in the list, so a search for i takes the reader to position 10, the last i in the text. Which of the three is it, and why?

Answer: fix the box. Every start position is there, each once. The box promises them in no particular order, and the code keeps it: they come out in the order of the sorted suffixes. The app wanted them in text order, and the box never asked for it.

Then: Rewrite the line of the box that has to change, say what the change costs, and name a test you would keep from the AI.

Answer to the follow-up: Promise: every start position, each exactly once, in increasing order. The cost: sorting the z positions found, about z \log_2 z more steps per question, and the index needs no more memory. The test: on texts that the AI never saw, compare locate with a plain scan as lists, not as sets; for i the scan gives [1, 4, 7, 10].

Derive it

Exercise 40

Write remove(key) for the Patricia tree, as code or as precise steps, so that the invariant holds again after every removal. Your answer must say what happens to a node left with no word and no children, to one left with a single child and no word, and why the root is treated differently from every other node.

Removal: clear the word’s mark; if the node now has no word and no children, delete it from its parent; then, at the parent (and at the node itself if it still has a single child and no word), merge a node that has no word and exactly one child with that child, joining the labels. Never merge the root, which has no branch above it into which to merge. A word that is not stored changes nothing: the walk falls off the tree, stops partway along a label, or ends at a node with no mark, and removal returns there.

Node counts after each removal, equal to a fresh build each time: after removing romulus: 12; after removing rubicon: 10; after removing rubicundus: 8

Geometry and high-dimensional search

The keys to the exercises, under the numbers the chapter gives them.

Run it and report the state

Exercise 1

Build the range tree over the keys 84, 71, 69, 42, 20, 46, 86, 30, 54, 36, 75, 40. Sort the keys and hang them in the leaves. Every inner node splits the keys below it in half, the left half taking the extra key when the count is odd, and holds the largest key of its left half. Give the key of every inner node, level by level from the root, and the tree’s depth.

  • inner keys by level: [[46], [36, 71], [30, 42, 69, 84], [20, 40, 54, 75]]
  • depth: 4

Exercise 2

In the tree of Exercise 1, query the range [65, 86]. At a node, go left when 86 is smaller than its key and right when its key is smaller than 65. The first node where neither holds is the split node. Which node is it, and which nodes does the walk pass on the way? Then follow 65 down the left side and 86 down the right side: which nodes does each path visit, which whole subtrees does each report, and which keys come out?

  • walk to the split node: 46 right
  • split node: 71
  • left path: 69 left, 54 right, leaf 69 (inside)
  • whole subtrees off the left path: [[71]]
  • right path: 84 right, leaf 86 (inside)
  • whole subtrees off the right path: [[75, 84]]
  • reported: [69, 71, 75, 84, 86]

Exercise 3

Build the k-d tree over the points a (8, 10), b (19, 8), c (4, 15), d (15, 5), e (7, 17), f (3, 1), g (13, 7), h (18, 9), i (20, 16), j (17, 6). Cut on x at the root, then on y, taking turns. At each node the left side takes the first half of its points along the axis (the extra point when the count is odd), and the cut is the coordinate of the last of them. A leaf holds one point. Draw the tree: the cut at every node, and the point in every leaf. How deep is it?

  • tree:

    x ≤ 13
      y ≤ 10
        x ≤ 8
          y ≤ 1
            point f
            point a
          point g
        x ≤ 4
          point c
          point e
      y ≤ 8
        x ≤ 17
          y ≤ 5
            point d
            point j
          point b
        x ≤ 18
          point h
          point i
  • depth: 4

Exercise 4

In the k-d tree of Exercise 3, find every point with 12 ≤ x ≤ 19 and 3 ≤ y ≤ 12. Keep the region that each node covers, bounded by the cuts above it and running on without end where no cut bounds it (not the smallest box around its points): report a region whole when it lies inside the rectangle, skip a side that the rectangle does not reach, and open the rest. Which regions are reported whole, which are skipped, which leaves do you check one point at a time, and which points come out?

  • reported whole: {j}
  • skipped: {a, f}, {c}
  • leaves checked: g in, e out, d in, b in, h in, i out
  • found: {b, d, g, h, j}

Exercise 5

In the k-d tree of Exercise 3, find the point nearest to (9, 11) by best-first search, in squared distances.

  • Every waiting region carries a bound: the sum of the squared distances from the query to the region along each axis.
  • Always open the waiting region with the smallest bound. Opening a node queues its far side first, then its near side, which keeps the parent’s bound, and equal bounds come out in the order they went in.
  • Stop when the smallest bound waiting is larger than the best distance found.

In what order are the regions opened, which points are measured, which regions are skipped, and why?

A region whose bound is larger than the best distance found cannot hold a nearer point, because the bound is the least distance anything in it can have.

Each cut crossed sets the offset along its axis, and the regions below keep it: {a, f} lies past the cut y ≤ 10, which is 1 from the query along y, and past the cut x ≤ 8, which is 1 from the query along x, so its bound is 1² + 1² = 2.

  • opened, with bounds:
    • {a, b, c, d, e, f, g, h, i, j} at 0
    • {a, c, e, f, g} at 0
    • {c, e} at 0
    • {e} at 0
    • {a, f, g} at 1
    • {g} at 1
    • {a, f} at 2
    • {a} at 2
  • measured: e 40, g 32, a 2
  • nearest: a at 2
  • skipped, with bounds: {b, d, h, i, j} at 16, {c} at 25, {f} at 101

Exercise 6

Run Andrew’s monotone chain on the points a (9, 7), b (0, 10), c (3, 4), d (12, 9), e (7, 11), f (4, 5), g (5, 2), h (1, 8). Sort them by x, build the lower chain left to right and the upper chain right to left, and keep dropping the last kept point while it, the one before it and the new point do not make a strict left turn. Which points are dropped, and when? What is the hull, counterclockwise from the leftmost point?

  • lower chain drops:
    • h when c arrives
    • f when g arrives
    • e when a arrives
    • a when d arrives
  • upper chain drops:
    • a when e arrives
    • g when f arrives
    • f when c arrives
    • c when h arrives
    • h when b arrives
  • lower chain: b, c, g, d
  • upper chain: d, e, b
  • hull: b, c, g, d, e
  • never on the hull: {a, f, h}

Then: The turn test is written >= 0 instead of > 0. Which point is now kept that the promise says must be left out, and why?

Answer to the follow-up: h (1, 8): it lies on the straight stretch of the fence between its two neighbors on the hull, so the turn there is 0, and >= 0 keeps it. The promise leaves out points on a straight stretch.

Exercise 7

Walking from a to b, is c on the left, on the right, or on the line? Give the sign of the orientation test, once for a (1, 9), b (0, 4), c (3, 0), and once for a (7, 1), b (6, 2), c (0, 8).

  • first: +1, left
  • second: 0, on the line

Exercise 8

A box runs from -2 to 2 along every axis. In each of its corners sits a ball of radius 1, centered at the point whose every coordinate is 1 or -1, so it touches the box’s walls at that corner and the balls in the neighboring corners. A ball at the center of the box is made as large as it can be without overlapping any corner ball. What is its radius when every point has 2 numbers, 10 numbers, and 100 numbers? From how many numbers on does the center ball reach outside the box, though every corner ball stays inside it?

  • radius at 2 numbers: 0.414
  • radius at 10 numbers: 2.162
  • radius at 100 numbers: 9
  • the rule: the radius is the square root of the number of numbers, less 1: the distance from the center to a corner ball’s center, less that ball’s radius
  • outside the box from: 10 numbers (at 9 it touches the walls)

Exercise 9

A table’s cuts are lines through the origin, given by the directions (2, 2), (-1, -3), (1, -1). A point’s bit for a cut is 1 when the dot product of the point with the direction is zero or more, and 0 when it is negative. Its key is its three bits in the order of the cuts. Hash the points a (-4, -3), b (3, 4), c (0, -5), d (4, -3), e (3, -4), f (-3, 4), g (0, 5), h (-5, 0). What is each point’s key, and which points share a bucket?

  • keys:
    • a: 010
    • b: 100
    • c: 011
    • d: 111
    • e: 011
    • f: 100
    • g: 100
    • h: 010
  • buckets:
    • 111: {d}
    • 100: {b, f, g}
    • 011: {c, e}
    • 010: {a, h}

Exercise 10

Add a second table to the points of Exercise 9, with the cuts (3, 1), (2, -1), (3, 3). The query is (-3, -4). What is its key in each table, which points share a bucket with it in some table, and which point is the answer after measuring each of them exactly? What would the answer have been with the first table alone?

  • query keys: ['011', '000']
  • candidates: {a, c, e, h}
  • measured: a 2, c 10, e 36, h 20
  • answer: a at 2
  • first table alone: candidates {c, e}, answer c at 10

Exercise 11

An LSH index uses keys of K = 4 cuts and L = 8 tables. With what probability does a point at 60° from the query share the query’s key in one given table, and with what probability does it become a candidate? Answer the same for a point at right angles to the query.

  • one table, 60°: 0.1975
  • a candidate, 60°: 0.8280
  • one table, 90°: 0.0625
  • a candidate, 90°: 0.4033

Then: Choose K and L so that a point at 45° becomes a candidate with probability at least 0.99, and one at 90° becomes a candidate with probability at most 0.05, with as few tables as you can. Try key lengths from 4 up, and for each find the fewest tables that let the 45° point in. Keep four decimal places.

Answer to the follow-up: K = 12 and L = 144: a point at 45° becomes a candidate with probability 0.9903, and one at 90° becomes a candidate with probability 0.0345. No fewer tables meet both bounds, whatever the key length: a key long enough to keep the far point out needs this many tables to let the near one in. K = 11 just misses: 107 tables let the near point in, but the far one then gets in with probability 0.0509.

Exercise 12

The point a (9, 8) picks at most 3 neighbors from the candidates b (6, 0), c (0, 12), d (12, 9), e (11, 2). Take them nearest first, in squared distances, and skip a candidate when a neighbor already picked is strictly nearer to it than a is. Which are picked, in order, and which is skipped, because of which neighbor?

  • candidates, nearest first: d 10, e 40, b 73, c 97
  • picked: d, e, c
  • skipped: b: 29 from e, 73 from a

Exercise 13

A flat graph index holds the points a (14, 17), b (4, 19), c (5, 9), d (13, 10), e (1, 11), f (8, 1), g (15, 8), h (16, 16), i (9, 7), j (11, 6), with the links a: b, d, h; b: a, c, e; c: e, i; d: g, i, h, j; e: c, b; f: c, g; g: d, f; h: a, d; i: c, d, j; j: i, d. Walk greedily from a toward the query (12, 0): at each point, measure every neighbor and step to the nearest one if it is nearer than where you stand. Stop when none is nearer. Which points does the walk visit, with their squared distances, and where does it stop? Is that the nearest point?

  • walk: a 293, d 101, j 37
  • stops at: j
  • nearest point: f at 17

Then: Walk again from a, but keep the 3 nearest points seen so far: each time, take the nearest kept point you have not yet expanded, measure its neighbors you have not measured, and keep the 3 nearest of all you have seen. Stop when the nearest point not yet expanded is farther than the worst of the 3 kept. Which kept point is nearest to the query?

Answer to the follow-up: Expanded a, d, j, i, g, f, in that order; kept f 17, j 37, i 58. The nearest kept point is f, the true nearest.

Exercise 14

A flat graph index with M = 2, so a list may hold four, holds the points a (11, 7), b (14, 12), c (15, 0), d (4, 1), e (8, 5), f (0, 17), g (13, 9), h (6, 11), with the links a: g, e, c; b: a, g, h; c: a; d: a, e; e: a, d, f, h; f: e; g: a, b; h: e, b. Insert i (9, 3): the beam finds all eight points as candidates. Pick by the rule of Exercise 12, in squared distances: which two does i pick, in order? Which lists get i as a link back, which of them grows past four, and what does its owner keep when it picks again?

  • candidates, nearest first:
    • e 5
    • a 20
    • d 29
    • c 45
    • g 52
    • h 73
    • b 106
    • f 277
  • picked: e, d
  • skipped: a: 13 from e, 20 from i
  • links back: e, d
  • over four: e: i 5, a 13, d 32, h 40, f 208
  • re-pick keeps: i, a, h
  • re-pick skips: d: 29 from i, 32 from e; f: 72 from h, 208 from e
  • their lists afterwards: e: i, a, h; d: a, e, i

Exercise 15

The graph index’s table in What it costs gives, for each beam width ef, recall@10 and queries a second on GloVe: ef 10: 0.467, 12,168; ef 40: 0.699, 4,712; ef 160: 0.849, 1,413; ef 640: 0.936, 416; ef 1,280: 0.964, 222; ef 2,560: 0.983, 118. Mia’s service needs recall@10 of at least 0.9 and at least 300 queries a second. Which beam width from the table do you ship, and why not the others? LSH answers 17 queries a second at recall 0.976, and the chapter says that at that recall the graph answers more than eight times as many. Is that a figure from the table? If not, where does it come from?

  • ship: ef 640: recall 0.936 at 416 queries a second
  • too little recall: ef 10, ef 40 and ef 160
  • too slow: ef 1,280 and ef 2,560
  • the table: every figure in it is measured
  • more than eight times: read, not measured: recall 0.976 lies 63% of the way from ef 1,280 (0.964, 222) to ef 2,560 (0.983, 118), so on a log scale of speed the graph reads as about 150 queries a second, 8.8 times LSH’s 17

Then: Read the speed at exactly recall 0.9 between the two measured beam widths around it, on a log scale of speed, the same way. What do you get, and what would you run before you promised it?

Answer to the follow-up: About 690 queries a second, with a beam somewhere between ef 160 and ef 640. That figure is read, not measured, and a beam read to land near 0.9 can land on either side of it, so run that beam on the same queries, and measure its recall and speed before promising either.

Which promise broke

Exercise 16

A range tree over 3, 9, 11, 14: the root has key 8; its left child has key 3 over the leaves 3 and 9; its right child has key 12 over the leaves 11 and 14.

  • verdict: broken: invariant 1, every inner key separates its two sides
  • detail: 9 sits on the left of the root’s 8; the root’s key becomes 9, the largest key on its left
  • broken: 1

Exercise 17

A k-d tree over a (2, 7), b (5, 1), c (9, 4), d (11, 8), e (14, 3): the root cuts at x ≤ 2, with a alone on its left; its right side cuts at y ≤ 3, then b, e below and c, d above are each cut on x.

  • verdict: broken: invariant 2, every cut splits the points under it in the tree in half
  • detail: the root’s cut leaves 1 point on the left and 4 on the right; cut at the lower median, x ≤ 9, so a, b, c go left and d, e go right
  • broken: 2

Exercise 18

An LSH table over the points of Exercise 9, with its cuts, has the buckets 111: {d}; 100: {b, f}; 011: {c, e}; 010: {a, g, h}.

  • verdict: broken: invariant 1, every stored point sits in the bucket its key names
  • detail: g’s key is 100, but it sits in bucket 010
  • broken: 1

Exercise 19

The point a (0, 0) picks at most 3 neighbors from b (3, 1), c (5, 2), d (1, 4), e (-4, 2), and picks b, d, e.

  • verdict: broken: invariant 2, skip any candidate closer to one already picked than to the point
  • detail: d is 13 from b but 17 from a; the picks are b, e
  • broken: 2

Exercise 20

The one-table index of Exercise 9 answers the query (-3, -4) with c, at squared distance 10. The nearest stored point is a, at 2.

  • verdict: correct: the promise is the nearest of the points that share a bucket, measured exactly
  • detail: a shares no bucket with the query, so it is no candidate. That is recall, which the box measures and does not promise
  • broken: none

Exercise 21

A flat graph index built with at most 4 links per point gives d the links g, i, h, j, a.

  • verdict: broken: invariant 1, every point has at most a fixed number of neighbors
  • detail: d has 5; re-pick its list with the picking rule, keeping at most 4
  • broken: 1

You supply the input

Exercise 22

Over the keys of Exercise 1, give a query [lo, hi] with lo < hi, both between the smallest and the largest key, for which the split node is a leaf: the walk from the root reaches a leaf without stopping on the way.

  • an example: [21, 29]

Then: Say what every such query has in common, and why.

Answer to the follow-up:

  • every case: the range holds no stored key, except possibly the largest: every other key is held by an inner node, the largest key on that node’s left side (invariant 1), and a walk that reaches it stops there, since it lies inside the range. The walk does reach it, because keys in the range never send it away from them

Exercise 23

With only the first table of Exercise 9 (cuts (2, 2), (-1, -3), (1, -1)), find a point with integer coordinates, as close to the query (-5, -3) as you can, that does not share the query’s bucket. How close can it be? You’re done when you can show no integer point outside the bucket is closer.

  • closest squared distance: 2
  • an example: (-4, -4)
  • why none is closer: the query’s key is 010; the only integer points at squared distance 1, (-4, -3), (-6, -3), (-5, -2) and (-5, -4), all have key 010 too, and integer points lie at integer squared distances, so 2 is the least; (-4, -4) has key 011, because its dot product with (1, -1) is 0, which puts it on the 1 side of that cut

Then: Say exactly when two points share a bucket.

Answer to the follow-up:

  • the rule: two points share a bucket exactly when no cut separates them: for every direction, both dot products are negative, or both are zero or more

Exercise 24

Place four candidates around a point at the origin, at different distances from it, so that picking at most 3 neighbors keeps only one.

  • an example: (1, 0), (1, 1), (1, 2), (1, 3)

Then: Say what every such set of candidates has in common.

Answer to the follow-up:

  • every case: the nearest candidate is picked, and every other one is strictly nearer to it than to the point

Which idea do you reach for

Exercise 25

A game world holds a million objects that barely move, and every frame the game asks which of them lie inside the area that the camera sees. The world can be prepared once, before the game starts.

  • (a) random directions
  • (b) navigable graph
  • → (c) spatial partition
  • (d) check every candidate

Answer: (c) Cut the world into regions once, and each region into smaller ones: a frame opens only the regions that meet the view, takes a region wholly inside it whole, and skips the rest.

Exercise 26

A delivery planner tries routes one at a time. Halfway through building a route, its cost so far is already higher than the cheapest complete route found, and the planner still finishes it.

  • → (a) bound and prune
  • (b) random directions
  • (c) navigable graph
  • (d) collide on purpose

Answer: (a) A partial route that already costs more than the best complete one can never win, so drop it and everything that would extend it.

Exercise 27

A file archive keeps folders inside folders, and each folder is labeled with the earliest date of anything inside it. You want the oldest file that matches a search, and opening a folder is slow.

  • (a) check every candidate
  • → (b) best-first
  • (c) which side
  • (d) random directions

Answer: (b) Always open the waiting folder whose label is earliest: its label is a bound on everything inside, and once a match is older than every label still waiting, you are done.

Exercise 28

A drawing app must decide, exactly and for every click, whether the click landed inside a triangular button, even when the click is a hair from an edge.

  • (a) best-first
  • (b) navigable graph
  • → (c) which side
  • (d) bound and prune

Answer: (c) The click is inside when it lies on the same side of all three edges: three signs of one determinant each, computed exactly.

Exercise 29

Every customer is described by ten thousand numbers. You need the distances between them only roughly, but computing on ten thousand numbers is far too slow.

  • → (a) random directions
  • (b) bound and prune
  • (c) check every candidate
  • (d) which side

Answer: (a) Multiply by a random matrix to a few hundred numbers: every distance survives within a small factor, with high probability.

Exercise 30

A photo service wants to find near-duplicates among a billion photos, each already turned into a list of numbers, without comparing every photo with every other.

  • (a) best-first
  • → (b) collide on purpose
  • (c) which side
  • (d) spatial partition

Answer: (b) Hash so that similar photos tend to land in the same bucket, and compare only photos that share one.

Exercise 31

Airport security cannot hand-search every passenger. A walk-through scanner is fast but raises false alarms, and a hand search is slow but certain.

  • (a) random directions
  • (b) navigable graph
  • → (c) check every candidate
  • (d) bound and prune

Answer: (c) Everyone passes the fast scanner. Only those it flags get the slow, exact search, so a false alarm costs a little time and never a wrong verdict.

Exercise 32

A music app links every song to a handful of songs that sound like it. Given a new song, it must find similar ones quickly among millions, with no other index.

  • → (a) navigable graph
  • (b) which side
  • (c) best-first
  • (d) collide on purpose

Answer: (a) Start anywhere and keep hopping to the linked song most like the new one, keeping a short list of the best heard so far.

Exercise 33

Without looking back, write each structure of this chapter as what it is made of: the range tree, the k-d tree, the convex hull, LSH, the graph index and the graph index with short codes. Write each as a sum of ideas from this list: spatial partition, a few whole pieces, bound and prune, best-first, which side, keep an invariant, random directions, collide on purpose, check every candidate, navigable graph, keep it in layers. Where one structure is built on another, the whole structure counts as one part. Then draw it as a map: a dot for each structure and each idea, and a line from each structure to every idea it uses. Which ideas have lines to two structures or more, and what does each one do in each? Three of the ideas did other jobs in earlier chapters. Which, and where?

Answer: Range tree = spatial partition + a few whole pieces. k-d tree = spatial partition + bound and prune + best-first. Convex hull = which side + keep an invariant. LSH = which side + random directions + collide on purpose + check every candidate. Graph index = navigable graph + best-first + keep it in layers. Graph index with short codes = graph index + random directions + check every candidate.

Shared: spatial partition (the range tree halves the line, the k-d tree cuts the map by turns); best-first (the k-d tree’s queue of regions, the graph’s beam of points); which side (the hull’s left turn, and LSH’s bit, the side of a cut through the origin); random directions (LSH’s cuts, and the rotation before a phone’s short codes keep their signs); check every candidate (LSH’s shared bucket, and the points that the short codes rank, each measured exactly).

Earlier chapters: keep an invariant is binary search’s loop invariant, in the contracts chapter and again in the search chapter; check every candidate is Rabin–Karp’s match, checked against the text, in the strings chapter; keep it in layers is the LSM-tree’s runs, and the skip list’s levels, in the search chapter.

The tests pass. What did they miss?

Exercise 34

A team ships an LSH index for finding similar products. Its tests pass: for a thousand queries, the index’s answer is the true nearest product every time. In production, shoppers search with photos of products that the shop does not sell, and the answers are often far from the best. What requirement did the tests miss?

Answer: The test queries were most likely products already in the index, or very near one. A stored point shares every bucket with itself, so it is always a candidate and always the answer. A shopper’s photo of something the shop does not sell has its nearest product at a wider angle, and by the box’s formula that product shares a bucket in no table far more often. The requirement nobody tested is recall on queries that the index has never seen, drawn like real ones.

Then: Write the requirement as a sentence that a test could check.

Answer to the follow-up: For example: on queries that are not stored points, drawn like real queries, the answer is the true nearest at least 95% of the time, measured against the scan.

Exercise 35

A graph index over restaurant reviews passes its tests: on a million points spread evenly, its recall@10 is 0.99. After launch, the reviews turn out to fall into tight clusters, one per city, and searches for a dish in one city often return a dish from another. What requirement did the tests miss?

Answer: Recall on data shaped like the real data. The box measures recall and does not promise it, so a figure measured on points spread evenly holds for points spread evenly. On clustered data, few links cross between clusters, so a walk that starts in the wrong one stops there.

Then: Write the test: on what data, against which reference, and at what beam width.

Answer to the follow-up: Test on data shaped like production, clusters included, or a sample of production itself, and measure recall against the scan at the chosen beam width.

Fix the code, the box, or the design?

Exercise 36

You give an AI the LSH design box and ask for the code. On the two tables of Exercise 10, asked for the point nearest to (-3, -4), its index answers c, at squared distance 10, though a, at 2, shares a bucket with the query too. Its tests had passed. Which of the three is it, and why?

Answer: fix the code. c is what an index answers if it stops at the first table, whose bucket holds c and e, or if it takes the first point in a bucket without measuring. Either way it breaks the box. The promise is the nearest of the candidates, measured exactly, and invariant 2 says so. The promise’s probability counts all L tables, so a point that shares the query’s bucket in any one of them is a candidate. a shares the second table’s bucket and is nearer. Gather the candidates from every table, measure them all, and return the nearest.

Then: Suppose the box had stopped at invariant 1. Which would it be then? Write the line you would add, and a test you would keep from the AI that checks it.

Answer to the follow-up: Still fix the code. The promise above the invariants says the nearest of the candidates, measured exactly, and c is not, so the code breaks the box even without invariant 2. It would be the box only if the promise had said less, for instance a point that shares a bucket with the query. Then add 2. A shared bucket only makes a point a candidate, and every candidate is measured exactly before one is reported. The test to keep: on the two tables of Exercise 10, the query (-3, -4) gets a; and for random queries, the answer is the nearest of every stored point whose key equals the query’s in at least one table, worked out from the cuts by a plain scan, not from the index’s own candidate list.

Exercise 37

The same AI’s k-d tree holds 2,000 points, every check of the box’s invariants passes, and every answer equals the scan’s. On points given by 2 numbers, a search measures about 4 points. Then the points are described by 32 numbers each, and a search measures about 2,000 of the 2,000. A colleague says the pruning is broken. Which of the three is it, and why?

Answer: change the design. Nothing is broken. Every answer is right, so the promise holds, and the pruning skips every region it can skip. The box assumes the data’s real dimension is low. In 32 dimensions almost every region lies about as close as the best point found, so the search opens nearly all of them. It is slower and still right. The assumption no longer fits.

Then: Name the design you would switch to, and say what you would measure to check it.

Answer to the follow-up: At 2,000 points the scan is exact and fast. At millions, use the graph index, which gives up the guarantee for speed. On GloVe, LSH at recall 0.976 measured 39% of the words and ran slower than the scan. Measure recall against the scan, and time per query beside the scan’s, at a few beam widths.

Exercise 38

An AI builds a map app’s rectangle search on the k-d tree of Exercise 3. Asked for the places with 12 ≤ x ≤ 19 and 3 ≤ y ≤ 12, it returns b, d, g, h, j. The app lists them in that order as running west to east, and b is not the westernmost. Which of the three is it, and why?

Answer: fix the box. Every point inside the rectangle is there, each once, and nothing else. The box’s promise holds, and it says nothing about order. The app wanted them west to east, and the box never asked for it.

Then: Rewrite the line of the box that has to change, say what the change costs, and name a test you would keep from the AI.

Answer to the follow-up: Promise: the same answers as the scan, the nearest stored point or the k nearest. Also every stored point inside a rectangle, each once, in increasing x, ties by y. The cost: sorting the k points found, about k log k more steps per query, and no more memory. The test: compare with a scan sorted by x, as lists, not as sets; here g, d, j, h, b.

Derive it

Exercise 39

Write query(lo, hi) for the 2D range tree, as code or as precise steps: every stored point with lo ≤ (x, y) ≤ hi on both axes, where lo = (x_lo, y_lo) and hi = (x_hi, y_hi), each once. Your answer must say what happens at the split node, what you do with a whole subtree that hangs off either path, and what you do with the leaf where a path ends.

Answer: Every whole subtree that the walk on x would report gets a one-dimensional query on y, on that subtree’s own tree.

Query: if lo > hi on either axis, return nothing. Otherwise walk from the root to the split node on x, as the 1D query does. Follow lo’s x down the left side and hi’s x down the right side. Every whole subtree that hangs between the two paths lies inside the strip on x, so search its associated tree for [lo’s y, hi’s y] and report what it returns. Check the leaf where each path ends, a split node that is a leaf, and a hanging subtree that is a single leaf, against both coordinates, without a search. Each point lies in one hanging subtree or one end leaf at most, so it is reported once.

Answers, with the number of associated trees searched (a hanging single leaf is checked, not searched): 14 ≤ x ≤ 25, 17 ≤ y ≤ 26: {c, i}, 1 search, plus the leaf g checked; 16 ≤ x ≤ 28, 1 ≤ y ≤ 13: {f, g}, 1 search, plus the leaves b and i checked; 12 ≤ x ≤ 22, 18 ≤ y ≤ 28: {c, i, l}, 1 search.

A rectangle with lo > hi, such as 25 ≤ x ≤ 14, returns nothing: no inner key lies between the two ends, so even without the first step the walk ends on a leaf, and the leaf fails the check.

Stretch: Show that a query costs O(log² n + k), and that the whole tree takes O(n log n) memory.

Answer to the follow-up: The two walks on x take about log₂ n steps each, and each step hands at most one whole subtree to a search on y, so a query runs at most about 2 log₂ n searches on y. Each is the 1D query: two walks of about log₂ n steps, plus one step for each point it reports, and each point is reported once: O(log² n + k) in all. Each point sits in the associated tree of every inner node above it, one per level, so the trees hold about n log₂ n points, at about two nodes per point: O(n log n) memory.

Graph structure and decomposition

The keys to the exercises, under the numbers the chapter gives them.

Run it and report the state

Exercise 1

Run Kahn’s method on the graph of the figure with Exercise 1. An arrow from x to y means x must be placed before y. Count the arrows into every vertex, queue the vertices with none, from a upward, and keep the queue first in, first out: take the front vertex, place it, lower the count of every vertex to which its arrows lead, in alphabetical order, and queue a vertex when its count reaches 0. Which vertices are ready at the start, which vertices wait in the queue after each placement, and what is the order?

  • ready at the start: a, e
  • queue after each placement:
    • a placed: e, d
    • e placed: d
    • d placed: b, f
    • b placed: f
    • f placed: c, h
    • c placed: h
    • h placed: g
    • g placed: empty
  • order: a, e, d, b, f, c, h, g

Exercise 2

Run Kahn’s method, as in Exercise 1, on the graph of the figure with Exercise 2. Which vertices does it place, in what order, and which vertices are stuck?

  • placed: d, g, f
  • stuck: {a, b, c, e, h}

Exercise 3

Run the depth-first walk on the graph of Exercise 1. Start from a, then the next vertex not yet entered in alphabetical order, and take each vertex’s arrows in alphabetical order of where they lead. A vertex finishes when every arrow out of it has been followed. In what order do the vertices finish, and what order does reversing it give?

  • finishing order: g, c, b, h, f, d, a, e
  • order: e, a, d, f, h, b, c, g

Exercise 4

Run the depth-first walk on the graph of the figure with Exercise 4. Start from a, then the next vertex not yet entered in alphabetical order, and take each vertex’s arrows in alphabetical order of where they lead. Stop at the first arrow that leads to a vertex still on the walk’s path. Which vertices are on the path then, from the start, which arrow is it, and which cycle does it name?

  • path: a, f, d, c
  • arrow: c→f
  • cycle: f, d, c, f

Exercise 5

Walk the graph of the figure with Exercise 5 depth first, to the end this time: an arrow to a vertex on the path does not stop the walk. Start from a, then the next vertex not yet entered in alphabetical order, and take each vertex’s arrows in alphabetical order of where they lead. Keep a clock that starts at 0 and ticks by one each time the walk enters a vertex or leaves it for good, and write down each vertex’s two times. Then sort the arrows into four kinds. A tree arrow is one by which the walk enters a new vertex. A back arrow leads to a vertex still on the path. A forward arrow leads to a vertex already left that was entered after the arrow’s own start, so it lies below it in the walk. A cross arrow leads to a vertex already left that was entered before the arrow’s start. Give each vertex’s times and each kind’s arrows, in the order in which the walk looks along them.

  • entered: a 1, b 3, c 5, d 6, e 7, f 11, g 8
  • left: a 2, b 4, c 14, d 13, e 10, f 12, g 9
  • tree: c→d, d→e, e→g, d→f
  • back: g→c, f→c, f→d
  • forward: c→f
  • cross: d→a, g→a, f→b

Exercise 6

The links of the figure with Exercise 6 go both ways, and no two vertices share more than one link, so a vertex’s neighbors and its links are the same count. Delete any vertex with fewer than k neighbors left; deleting it lowers each neighbor’s count by one; repeat until every vertex left has at least k neighbors. What is left is the k-core (Batagelj and Zaveršnik). Which vertices form the 2-core, and which vertices form the 3-core?

  • 2-core: {a, c, d, e, g, i, j}
  • 3-core: {c, d, i, j}

Then: Kahn’s method keeps a queue of the vertices ready to place. What would you keep so that each deletion finds the next vertex to delete without looking at every vertex again?

Answer to the follow-up: A count of neighbors left per vertex, as Kahn keeps a count of waits, and a queue of the vertices whose count is below k. Deleting a vertex lowers each neighbor’s count, and a neighbor joins the queue when its count drops below k, once. Each vertex and each link is looked at a constant number of times. Whatever the order, the vertices left are the same: a vertex with fewer than k neighbors stays short as others go, so it is deleted in every order.

Exercise 7

Run Algorithm T on the graph of the figure with Exercise 7. Start from a, then the next vertex not yet entered in alphabetical order, and take each vertex’s arrows in alphabetical order of where they lead. Number vertices from 1 as the walk enters them; a vertex’s climb-back number starts as its own number. Looking along an arrow to a vertex met but not out, or coming back over an arrow, a vertex takes the other end’s climb-back number if it is smaller; a vertex whose group is out is passed by. Stop when done: once every vertex is entered and the current vertex climbs back as far as the root it started from, everything not yet out comes out as one group. Give each vertex’s entry number, its climb-back number when its group comes out, the groups in the order they come out, and the groups numbered from 0 so that every arrow between two groups goes from a smaller number to a larger one.

  • entry numbers: a 1, b 6, c 2, d 7, e 4, f 3, g 8, h 5
  • climb-back numbers as each group comes out: a 1, b 6, c 1, d 7, e 1, f 1, g 6, h 5
  • groups in the order they come out: {h}, {a, c, e, f}, {d}, {b, g}
  • groups, numbered: 0 {b, g}, 1 {d}, 2 {a, c, e, f}, 3 {h}

Exercise 8

Walk the graph of Exercise 7 again, recursively and to the end, with no early stop. Start from a, then the next vertex not yet entered in alphabetical order, and take each vertex’s arrows in alphabetical order of where they lead. Run it twice, with two rules for an arrow from a vertex to one met but not out. The classical rule: the vertex takes that vertex’s entry number if it is smaller. Algorithm T’s rule: it takes that vertex’s climb-back number if it is smaller. In both, coming back from a vertex it entered, a vertex takes that vertex’s climb-back number if it is smaller, and a vertex leads a group when it finishes with its climb-back number equal to its own. What is each vertex’s climb-back number when it finishes, under each rule?

  • classical rule: a 1, b 6, c 1, d 7, e 2, f 2, g 6, h 5
  • Algorithm T’s rule: a 1, b 6, c 1, d 7, e 1, f 1, g 6, h 5

Then: Where the two tables differ, why do the two walks still find the same groups?

Answer to the follow-up: A vertex leads exactly when nothing below it in the walk has an arrow to a vertex met but not out, entered before it. Under both rules a vertex’s number drops below its own entry number exactly then. The classical rule passes entry numbers, which are never smaller than the climb-back numbers that T passes, so its numbers stay higher; but when T’s number drops below a vertex’s own entry number, some vertex below it has an arrow to an open vertex entered earlier, and that arrow’s entry number reaches the vertex under the classical rule too. The leaders are the same, so the groups are the same; only the numbers in between differ.

Exercise 9

Shrink each group of Exercise 7 to one vertex, keeping the numbers it gave them, and keep one arrow from group c to a different group d whenever some arrow of the graph leads from a vertex of c to a vertex of d. Which arrows does the graph of groups have?

  • arrows: 0→1, 0→2, 1→2, 2→3

Exercise 10

In the graph of Exercise 7, read an arrow as “can pass a message to”. a has heard news 1 and d has heard news 2; nobody else has heard anything, and nobody forgets. Settle the groups of Exercise 7 in their numbered order, and inside a group pass news along its arrows until a whole round changes nothing. What has each vertex heard at the end?

  • heard: a {1, 2}, b {}, c {1, 2}, d {2}, e {1, 2}, f {1, 2}, g {}, h {1, 2}

Exercise 11

Find true or false for x1, x2 and x3 that makes every clause hold: (¬x2 or x3), (x2 or x1), (¬x2 or ¬x3), (¬x2 or x1), (¬x3 or ¬x1). Draw the six literals x1, ¬x1, x2, ¬x2, x3, ¬x3 as vertices, in that order, and give each clause (p or q) its two arrows, ¬p → q and ¬q → p. Find the groups with Algorithm T, starting from x1 and taking each literal’s arrows in the order above, and number them so every arrow between groups goes from a smaller number to a larger one. Then set xᵢ true exactly when its group’s number is larger than the number of ¬xᵢ’s group. What are the groups, and the answer?

  • groups, numbered: 0 {¬x1, x2, x3}, 1 {x1, ¬x2, ¬x3}
  • answer: x1 true, x2 false, x3 false

Then: Add one clause that leaves no answer at all, and say how the groups show it.

Answer to the follow-up: For example (¬x1 or x2): then x1 and ¬x1 fall into one group, so each forces the other, and no answer exists.

Exercise 12

Run the block walk on the graph of the figure with Exercise 12. Start from a, then the next vertex not yet entered in alphabetical order, and take each vertex’s links in alphabetical order of the vertex at the other end. Number vertices from 1 as the walk enters them. Skip the link by which a vertex was entered. A link to a vertex entered earlier goes on the link stack and passes that vertex’s entry number if it is smaller; a link to a new vertex goes on the stack and the walk goes down it. When a vertex finishes, the vertex above it takes its climb-back number if smaller; if that number is no earlier than the upper vertex’s own, pop the stack down to the link between them: one block. Give each vertex’s entry number and its climb-back number when it finishes, the blocks in the order they come off the stack, the bridges and the cut vertices.

  • entry numbers: a 1, b 4, c 2, d 5, e 9, f 7, g 8, h 3, i 6
  • climb-back numbers: a 1, b 4, c 1, d 1, e 9, f 6, g 6, h 1, i 1
  • blocks, in order: {b, h}, {e, g}, {f, g, i}, {a, c, d, h, i}
  • bridges: b–h, e–g
  • cut vertices: g, h, i

Exercise 13

Draw the block-cut forest of the graph of Exercise 12: a node for each block, a node for each cut vertex, and a line from each cut vertex to every block that holds it. Which vertices, each failing alone, cut b off from e?

  • blocks: {b, h}, {e, g}, {f, g, i}, {a, c, d, h, i}
  • forest lines: g to {e, g}, {f, g, i}; h to {b, h}, {a, c, d, h, i}; i to {f, g, i}, {a, c, d, h, i}
  • separators: g, h, i

Exercise 14

In the graph of the figure with Exercise 14, f and g are joined by two links. Run the block walk of Exercise 12: it skips only the very link by which a vertex was entered, so the other copy counts as a link back. Which links are bridges, and which vertices are cut vertices?

  • bridges: b–e, d–f
  • cut vertices: b, f, g

Then: Now skip every link back to the vertex from which a vertex was entered. What does the walk report, and which answer is right?

Answer to the follow-up: It also reports f–g as a bridge: both copies lead back to the vertex above, so both are skipped and nothing climbs back. The first answer is right. Cut one copy and the other still joins the two vertices, so neither copy is a bridge.

Exercise 15

Eight items a to h start alone, each of rank 0. A union looks up its first item, then its second; if the two roots are the same it merges nothing and answers no. Otherwise the root of lower rank goes under the other, and on equal ranks the second root goes under the first, whose rank rises by one. Every lookup points each item it walked straight at the root. Run union(g, a), union(f, b), union(f, e), union(a, g), union(f, b), union(g, h), union(g, b), find(b), union(g, e), union(d, b). What does each step answer, how many groups are there after it, and where does every item point at the end, with which ranks?

  • steps:
    • union(g, a) yes, 7 groups
    • union(f, b) yes, 6 groups
    • union(f, e) yes, 5 groups
    • union(a, g) no, 5 groups
    • union(f, b) no, 5 groups
    • union(g, h) yes, 4 groups
    • union(g, b) yes, 3 groups
    • find(b) g, 3 groups
    • union(g, e) no, 3 groups
    • union(d, b) yes, 2 groups
  • links at the end: a→g, b→g, c→c, d→g, e→g, f→g, g→g, h→g
  • ranks at the end: a 0, b 0, c 0, d 0, e 0, f 1, g 2, h 0

Exercise 16

Seven items a to g start alone, in a union-find that can take merges back. It never shortens a path, and unions follow the rules of Exercise 15. Every union call writes one entry in a log, an empty one when it merges nothing, and an undo takes back the last entry. Run union(g, d), union(g, f), union(d, a), union(a, d), union(f, g), undo(), undo(), union(a, d), joined(g, a). What does each step answer, how many groups are there after it, and where does every item point at the end?

  • steps:
    • union(g, d) yes, 6 groups
    • union(g, f) yes, 5 groups
    • union(d, a) yes, 4 groups
    • union(a, d) no, 4 groups
    • union(f, g) no, 4 groups
    • undo() yes, 4 groups
    • undo() yes, 4 groups
    • union(a, d) no, 4 groups
    • joined(g, a) yes, 4 groups
  • links at the end: a→g, b→b, c→c, d→g, e→e, f→g, g→g

Which promise broke

Exercise 17

Kahn’s method on the graph of Exercise 1 returns the order a, e, b, d, f, c, h, g.

  • verdict: broken: invariant 1, every vertex placed so far comes after everything it waits for
  • detail: the arrow d→b points backward; place d before b
  • broken: 1

Exercise 18

A program groups the vertices of Exercise 7 as {b, g}, {d}, {c, e, f}, {h}, {a}, and says each group’s vertices reach each other.

  • verdict: broken: the promise, two vertices share a group exactly when each reaches the other
  • detail: a and the rest of its old group reach each other, so they belong together; a checker finds it at the check “strongly connected”
  • broken: promise

Exercise 19

On the graph of Exercise 12, a program reports f–g as a bridge.

  • verdict: broken: the promise, a link is reported exactly when removing it alone leaves more pieces
  • detail: delete f–g and count the pieces: still 1, as before; the link lies on a cycle
  • broken: promise

Exercise 20

A union-find has received the links of the figure with Exercise 20, one union each, and answers that a and b are not joined.

  • verdict: broken: the promise, two items give the same lookup answer exactly when they are in one group
  • detail: search the links received so far: a – e – g – b joins them
  • broken: promise

Exercise 21

A union-find over a to h stores the links a→a, b→a, c→b, d→a, e→e, f→e, g→g, h→a, the ranks a 2, b 1, c 0, d 0, e 1, f 0, g 0, h 0, and a count of 3 groups.

  • verdict: correct: every item’s links lead up to a root, ranks rise toward the root, a root of rank r has at least 2^r items, and there are 3 roots
  • detail: c sits two links below a: a lookup would shorten that, and nothing requires it before one
  • broken: none

You supply the input

Exercise 22

Add one arrow to the graph of Exercise 7 so that every vertex reaches every other: the whole graph becomes one group. Give one that works.

  • an example: h→b

Then: Say which arrows work, all of them, and why.

Answer to the follow-up:

  • every case: any arrow from a vertex of the last group, {h}, to a vertex of the first, {b, g}: the graph of groups has one group nothing leads into and one nothing leaves, every group lies on a path from the first to the last, and the new arrow closes that path into a cycle

Exercise 23

Two weak checkers judge a grouping of the graph of Exercise 7. The first checks that every vertex is in exactly one group and each group is strongly connected, then trusts the graph of groups that the answer supplies and checks only that it has no cycle. The second checks that every vertex is in one group and that the graph of groups, built from the arrows, has no cycle, and skips the check that each group is strongly connected. For each, find a wrong grouping it accepts.

  • accepted by the first: the groups {b}, {d}, {a, c, e, f}, {h}, {g}, with an empty graph of groups
  • accepted by the second: the groups {b, d, g}, {a, c, e, f}, {h}

Then: Say what every wrong grouping each one accepts has in common.

Answer to the follow-up:

  • every case: the first accepts any split of a knot into pieces that are each strongly connected, with a supplied graph of groups that hides the arrows between them; the second accepts any merge of groups that leaves the graph of groups built from the arrows without a cycle, such as two groups where one reaches the other only one way

Exercise 24

Add one link to the graph of Exercise 12, between two vertices not yet linked, so that no bridge is left.

  • an example: b–e

Then: Say which links work, all of them, and why.

Answer to the follow-up:

  • every case: b–e: with every bridge gone, the pieces left form a path joined by the bridges, and only a link between the two end pieces puts every bridge on a cycle

Exercise 25

Eight items a to h start alone, with the union rules of Exercise 15. Give a sequence of unions after which some item sits three links below its root.

  • an example: union(a, b), union(c, d), union(e, f), union(g, h), union(a, c), union(e, g), union(a, e)

Then: Say what every such sequence has in common.

Answer to the follow-up:

  • every case: no item sits deeper than its root’s rank, and a root of rank r has at least 2^r items, so depth 3 needs a root of rank 3 over all eight: every merge joins two trees of equal rank, pairs, then fours, then one tree; and the lookups that the unions make leave at least one path of three links unshortened

Which idea do you reach for

Exercise 26

A kitchen cooks a banquet of forty dishes. Some dishes need a sauce or a stock that another dish produces, and one cook can work on one dish at a time. In what order should the cook start them?

  • (a) contraction
  • → (b) topological order
  • (c) monotone fixed point
  • (d) rewrite on read

Answer: (b) Start any dish whose ingredients are all ready; finishing it may make others ready. Every dish then comes after everything it needs.

Exercise 27

A power company wants every substation whose failure alone would black out some neighborhood, on a grid of a million substations, in one pass over the grid.

  • (a) merge smaller into larger
  • (b) topological order
  • → (c) DFS timestamps and low-link
  • (d) rewrite on read

Answer: (c) One depth-first walk numbers the substations and keeps how far back each part below can reach. A part that cannot climb above a substation hangs on it alone.

Exercise 28

A delivery planner works on a city where, inside each neighborhood, every street leads round to every other. It wants to plan between neighborhoods only, treating each one as a single stop, and still know which neighborhood can be reached from which.

  • → (a) contraction
  • (b) monotone fixed point
  • (c) rewrite on read
  • (d) merge smaller into larger

Answer: (a) Shrink each neighborhood to one stop, keeping an arrow between two stops when a street joins them. What it keeps is named: who can reach whom.

Exercise 29

A security tool works out, for each variable of a program, every untrusted input whose data could flow into it. Data flows round loops, and a variable’s list of inputs only grows.

  • (a) topological order
  • → (b) monotone fixed point
  • (c) DFS timestamps and low-link
  • (d) contraction

Answer: (b) Pass the lists along the flows again and again until a whole round changes nothing. Lists only grow and there are finitely many inputs, so it stops.

Exercise 30

A chain of shops merges with other chains again and again. Each merge relabels every shop of one chain with the other chain’s name, and relabeling a shop costs a letter to its staff. How do you keep the total number of letters small?

  • (a) monotone fixed point
  • (b) topological order
  • → (c) merge smaller into larger
  • (d) contraction

Answer: (c) Relabel the smaller chain. A shop relabeled lands in a chain at least twice as large, so no shop gets more than log₂ n letters.

Exercise 31

A file system lets a shortcut point to another shortcut, which points to another, and only the last points to the file. The same shortcuts are opened all day, and following a long chain is slow.

  • → (a) rewrite on read
  • (b) contraction
  • (c) DFS timestamps and low-link
  • (d) monotone fixed point

Answer: (a) After following a chain once, point every shortcut on it straight at the file. The next opening takes one step.

The tests pass. What did they miss?

Exercise 32

A university’s course planner orders courses so that every course comes after its prerequisites. Its tests pass: on a thousand random catalogues it returns every course once with every prerequisite earlier. After launch, two departments each list the other’s course as a prerequisite, and the planner prints a list of courses with no warning; students plan around the courses it left out without knowing they are missing. What requirement did the tests miss?

Answer: Every test catalogue was drawn without a cycle, so only the first half of the promise was ever run. The promise has a second branch: when no order exists, say so and name the courses that could not be placed. The tests never asked for it.

Then: Write the requirement as a sentence that a test could check.

Answer to the follow-up: On a catalogue with a cycle of prerequisites, the planner returns no order; it returns the courses it could not place, each of which still waits on one of them, and the test builds such a catalogue on purpose.

Exercise 33

A build tool draws an arrow from each module to every module that imports it, groups modules that import each other in circles, and then builds the groups by number, group 0 first. The grouping’s tests pass: on random graphs, two modules share a group exactly when each reaches the other, checked against a plain search. In use, builds fail because a group is built before a group it imports. What requirement did the tests miss?

Answer: The numbering. The tests compared only who shares a group, a check that ignores the numbers, so a grouping numbered in the order in which the groups came out, sinks first, passed. The build needs the groups numbered in the order of the graph of groups.

Then: Write the test.

Answer to the follow-up: For every arrow between two different groups, the group it leaves has a smaller number than the group it enters; compared on the numbers, as well as on who shares a group.

Exercise 34

An AI writes a union-find for a photo app that groups pictures of the same scene. Its tests pass: on fifty items and random unions, every answer to “joined?” matches a plain search over the links. Its union always hangs the first root under the second, and its lookup never shortens a path. In production, pictures arrive one by one, and each arrival calls union(the picture before, the new one). After a hundred thousand pictures, a single question takes a noticeable pause. What requirement did the tests miss?

Answer: The cost. The box promises that one lookup walks at most log₂ n links, which needs the balance rule. The tests checked only the answers, and on fifty items a chain of fifty is fast. Each union hangs the whole tree under the new item, which builds a chain a hundred thousand links long, and a lookup walks all of it.

Then: Write the test that would have caught it.

Answer to the follow-up: After any sequence of unions on n items, no item sits more than log₂ n links below its root; run it on the order that production uses, union(the item before, the new one), on a large n, so a chain shows.

Fill in the contract

Exercise 35

A spreadsheet holds a hundred thousand cells, and a cell’s formula may read other cells. When someone edits a cell, every cell that depends on it, directly or through others, must show its new value before the next keystroke, and no cell may be computed from a value that is about to change. Someone sometimes writes a formula that reads itself through other cells. Work out the parts of a contract for this workload, in the order in which the contracts chapter works them out, one or two sentences each.

Answer, one line per question. Grade on the parts kept apart, not on the wording:

  1. Goal: after each edit, recompute exactly the cells that depend on the edited one, each after everything it reads, and report formulas that read themselves.
  2. Floor: every cell that depends on the edit must be visited, and every formula link among them looked at once; the scarce resource is time before the next keystroke.
  3. Promise and invariants: every affected cell that can be computed is computed once, after every cell it reads; cells caught in a circle, and cells waiting behind one, are named and left uncomputed. What must remain true: a cell is computed only when nothing it reads is still waiting.
  4. Idea: topological order over the cells that the edit can reach: count, for each, how many cells it reads are still waiting, and compute the ones at zero.
  5. Cost: one look at each affected cell and each formula link among them; it refuses to say anything about cells that the edit cannot reach, and gives no values inside a circle or behind one.
  6. Assumes: formulas do not change while a recomputation runs, and a formula reads only the cells it names. If a formula reads cells chosen at run time, the links are not known in advance, and the order can be wrong.

Then: Which part of your contract tells the spreadsheet what to show when formulas read each other in a circle, and why does the order alone not settle it?

Answer to the follow-up: The promise: cells in a circle get no order, since each waits on another, so the contract has to say what they show. An order exists only when there is no circle, and the spreadsheet must decide, and say, what a circle shows instead: an error in those cells, for example. Repeating until nothing changes would be legal only if values only grow and can grow only finitely often, which formulas do not promise.

Fix the code, the box, or the design?

Exercise 36

You give an AI the union-find design box and ask for the code. Its union finds both roots and links them by rank, but never asks whether the roots are the same. After union(a, b), union(b, a) and union(a, b) on four items, the root a has rank 3 and 2 items in its tree, and the group count says 1. Every lookup still answers correctly. Which of the three is it, and why?

Answer: fix the code. The box promises that merging two items already together merges nothing, and its invariant 2 says a root of rank r has at least 2^r items: rank 3 with 2 items breaks it, and the count is wrong too. Answers stay right for now, but the depth bound that rank was keeping is gone. Return before linking when the two roots are the same.

Then: Name a test you would keep from the AI that catches it.

Answer to the follow-up: Union two items already joined, and check that every root, every rank and the count stay as they were. The union’s two lookups may still shorten paths. And after any sequence of operations, every root of rank r has at least 2^r items, and the count equals the number of roots.

Exercise 37

An AI writes a course planner from the topological order box. On the graph of Exercise 1 it lists a, e, d, b, f, c, h, g. Every arrow points forward. The registrar complains that whenever several courses could come next, the list should take them alphabetically, and here it does not. Which of the three is it, and why?

Answer: fix the box. The promise holds: every course once, every arrow forward. The box allows any such order, and the registrar wanted one particular order for which the box never asked.

Then: Rewrite the line of the box that has to change, say what the change costs, and give the answer that the registrar expects.

Answer to the follow-up: Promise: every vertex exactly once, with every arrow pointing forward, and of all such orders, the one that comes first alphabetically. Keep the ready vertices in a heap instead of a queue: about log₂ n more steps per vertex. Here: a, d, b, e, f, c, h, g.

Exercise 38

A social app keeps a union-find of its users, one union per friendship, and answers “are these two connected?”. On the links of Exercise 20, a and e unfriend each other. The app still says they are connected, though no chain of friendships joins them any more. Which of the three is it, and why?

Answer: change the design. The union-find keeps its promise for the links it received. Its box assumes groups only merge and never split, and an unfriending is a split: that assumption no longer fits the job.

Then: Name a design that fits, and say what it costs.

Answer to the follow-up: Rebuild the union-find from the current friendships when one ends, which costs a pass over all of them per removal; or, when removals are known in advance, run time backwards so each removal becomes a merge; or a dynamic connectivity structure, which handles both at a cost of a few log factors per change.

Exercise 39

An AI writes 2-SAT from the strong components box. On the clauses of Exercise 11, it answers x1 false, x2 true, x3 true, and (¬x2 or ¬x3) is false under it. Its tests checked only whether it said “no answer” at the right times. Which of the three is it, and why?

Answer: fix the code. The grouping is right, but the code sets xᵢ true when its group comes before ¬xᵢ’s group in the order of the groups, the opposite of the rule. An answer must make every clause true. Set xᵢ true exactly when its group comes after ¬xᵢ’s group.

Then: Name the test you would keep from the AI.

Answer to the follow-up: Whenever it gives an answer, every clause holds under it; and it says “no answer” exactly when a search through all assignments finds none.

Derive it

Exercise 40

Write a procedure, as code or as precise steps, that splits the vertices of a connected network into its largest pieces that no single link failure can split, and joins those pieces into a tree, one line per bridge. Your answer must say how a piece is found, why two vertices in one piece stay joined after any one link fails, and why the pieces with the bridges form a tree.

Find the bridges with the block walk. Delete them, and search what is left (or union the ends of every other link): each group found is a piece. Two vertices in one piece are joined by links that are no bridges, and each such link lies on a cycle, so losing any one link leaves another way round. Each bridge joins two pieces, and the pieces with the bridges form a tree: a cycle among them would put a bridge on a cycle.

Answers: pieces 0 {a}, 1 {b, c, e, g, h, i}, 2 {d}, 3 {f}, 4 {j}; tree lines 0–1, 2–1, 3–1, 1–4, one for each of the bridges a–e, d–e, f–g, i–j.

Stretch: Show that your procedure takes one look per vertex and per link, and that the pieces really are the largest: a link inside a piece lies on a cycle.

Answer to the follow-up: The block walk is one look per vertex and link, and the search that follows is one look per vertex and link too; together, linear. A link that is no bridge lies on a cycle (removing it leaves its ends joined), so its two ends belong together; and two vertices joined only through a bridge come apart when it fails, so no larger piece survives every single failure.

Paths and trees

The keys to the exercises, under the numbers the chapter gives them.

Run it and report the state

Exercise 1

Run breadth-first search from a on the graph of the figure with Exercise 1. Every link can be taken both ways and counts one. Take each place’s links in alphabetical order of the place at the other end. The moment a place is found, give it its count and note the place that found it. In what order do the places come off the queue? How many links is each place from a, and what is each place’s previous vertex?

  • off the queue: a, b, d, e, f, h, c, i, g
  • links from a: a 0, b 1, c 3, d 1, e 2, f 2, g 4, h 3, i 3
  • previous vertices: b from a, c from f, d from a, e from b, f from b, g from h, h from e, i from f

Exercise 2

Run Dijkstra’s algorithm from a on the graph of the figure with Exercise 2, as the chapter’s code does. The number on an arrow is its cost, and a street drawn with two arrows has a cost each way. Try each settled place’s arrows in alphabetical order of where they lead. The queue hands out the smallest cost first. On a tie, the letter that comes first goes first. When a known cost drops, a new entry goes in. An offer equal to the known cost changes nothing. The old entry stays, and it is skipped when it comes off. In what order are the places settled, and at what cost? Which entries come off old and are skipped? What is each place’s previous vertex? Which cheapest path to i do the previous vertices give?

  • settled: a 0, d 4, b 8, c 9, g 10, e 15, f 16, h 16, i 17
  • old entries skipped: f 17
  • previous vertices: b from a, c from b, d from a, e from c, f from e, g from d, h from e, i from f
  • cheapest path to i: a, b, c, e, f, i

Exercise 3

The bread is sold at three counters: the Bakery, a kiosk at the Station and the School’s canteen. A customer who calls gets the loaf from the counter whose rider reaches the customer quickest by bike, in the minutes of Figure 6.3. Say what you would change in Dijkstra’s algorithm. Give every place’s time and its counter. Finally, say whether the box’s Assumes still holds.

  • the change: the start: all three counters, each at 0, instead of one place. Each counter’s known cost is set to 0 minutes, with no previous vertex, and each goes into the queue as an entry at 0. Every other place starts with no known cost. Nothing else changes
  • times: Bakery 0, Square 4, Market 5, School 0, Hilltop 6, Station 0
  • unit: every time is in minutes, as in the figure
  • counters: Square from the Bakery, Market from the Station, Hilltop from the School; each counter from itself
  • Assumes: still holds: the arrows are the town’s own minutes, and none costs less than 0

Then: Now do the same another way. Add one new place, with an arrow costing 0 to each counter, and run Dijkstra’s algorithm unchanged from it. Which way changes the search, and which changes the map?

Answer to the follow-up: The same times, Bakery 0, Square 4, Market 5, School 0, Hilltop 6, Station 0: the new place settles first at 0. Each counter then settles at 0 through its new arrow, and from there the search runs as before. Following the previous vertices back stops at the new place, one step past the counter. Starting with all three in the queue changes the search. The new place changes the map, and the search stays as the box prints it, since an arrow of 0 is not negative.

Exercise 4

Run Bellman–Ford from a on the graph of the figure with Exercise 4, in place, as the chapter’s code does. Each round goes through the places in alphabetical order and tries each place’s arrows in alphabetical order of where they lead. Pass over a place that has no cost yet. A cost lowered early in a round is used later in the same round. Give the list after each round, until a round lowers nothing. How many rounds run, counting that last one? What is the cheapest path to f?

  • after each round:
    • round 1: a 0, b 8, c none, d 2, e 9, f 8, g 4, h 4, i 6
    • round 2: a 0, b 8, c 11, d 2, e 9, f 8, g 4, h 4, i 6
    • round 3: a 0, b 8, c 11, d 2, e 9, f 8, g 4, h 4, i 6
  • rounds: 3
  • cheapest path to f: a, d, h, i, f

Then: Row 1 of the table holds the cheapest cost with at most one arrow. A place is ahead of row 1 when the list after round 1 gives it a cost where row 1 has none, or a lower cost than row 1. Which places are ahead after round 1, and why is that safe?

Answer to the follow-up: b 8 (row 1: none), e 9 (row 1: none), f 8 (row 1: none), g 4 (row 1: none), h 4 (row 1: none), i 6 (row 1: none). Each comes from an arrow out of a place whose cost was lowered earlier in the same round. So it is the cost of a real path with more than one arrow. A cost on the list is always the cost of some path, so it never drops below the cheapest. Running ahead only reaches the cheapest sooner.

Exercise 5

The graph of the figure with Exercise 5 has a negative cycle that a reaches. Run Bellman–Ford from a in place, as in Exercise 4, for six rounds, one per place. Which place does the sixth round lower last? From it, step back through the previous vertices six times: where do you land? Then keep stepping back until that place comes back. Which cycle is it? Write it reversed, so that each place is followed by the end of its arrow. What do its arrows total?

  • after round 6: a −6, b −6, c −8, d −4, e −3, f 1
  • lowered last: f
  • after six steps back: d
  • cycle: d, b, a, d
  • total: −2

Exercise 6

A kitchen starts four dishes, a to d, at integer minutes x_a, \dots, x_d, counted from a reference time, so a start may be negative. Each rule says one dish starts at most some minutes after another: x_b - x_a \le 5, x_c - x_b \le 2, x_a - x_c \le -4, x_d - x_c \le 3 and x_d - x_a \le 6. Make a place for each dish, and one more place, s. Draw an arrow costing 0 from s to every dish. For each rule x_j - x_i \le c, draw an arrow from i to j costing c. Run Bellman–Ford from s and give each dish’s cost. Show that these costs, taken as start times, keep every rule. Then add the rule x_c - x_a \le 3 and say why no start times can keep all the rules.

  • start times: a −4, b 0, c 0, d 0
  • every rule holds: x_b - x_a = 4 \le 5, x_c - x_b = 0 \le 2, x_a - x_c = -4 \le -4, x_d - x_c = 0 \le 3, x_d - x_a = 4 \le 6
  • cycle with the added rule: c, a, c
  • the same cycle from another dish: a, c, a
  • its total: −1
  • why no times work: go round the cycle and add up the rules on it. The start times cancel, so the left sides add up to 0. The right sides add up to −1. So the rules together say 0 \le -1, which is false

Exercise 7

A bank quotes: 1 euro buys 1.10 dollars, 1 dollar buys 0.90 euros, 1 dollar buys 150 yen and 1 yen buys 0.0062 euros. Make a place per currency and an arrow per quote. An arrow costs 1,000 times -\ln of its rate, rounded to an integer. Say why, before the rounding, a loop of trades that gains money is a negative cycle. Can the rounding change that? Then find such a loop with Bellman–Ford from the euro, and check that it really gains.

  • arrow costs: euro→dollar −95, dollar→euro 105, dollar→yen −5011, yen→euro 5083
  • gaining round: euro, dollar, yen, euro
  • the same round from another currency: dollar, yen, euro, dollar; yen, euro, dollar, yen
  • its total: −23
  • one unit becomes: 1.023
  • why a gain is a negative cycle: a loop gains when the product of its rates is above 1. Then the sum of the logarithms of its rates is above 0. Each arrow costs -1{,}000 times its logarithm, so before rounding the loop’s arrows add up to less than 0. The steps also hold in reverse, so a loop whose unrounded costs add up to less than 0 gains
  • what the rounding changes: the match is no longer exact. Each arrow moves by at most 0.5, so a loop that gains very little can round to a total of 0: a rate of 1.0004 and a rate of 1 back both cost 0, yet the loop gains. Here the 3 arrows move the total by at most 1.5, far less than the 23 below 0, so the loop really gains

Exercise 8

A box holds 9 kilograms, and four orders wait: order 1 weighs 3 kilograms with a tip of 10, order 2 weighs 2 kilograms with a tip of 8, order 3 weighs 5 kilograms with a tip of 11 and order 4 weighs 2 kilograms with a tip of 4. Fill the knapsack’s layers one order at a time, as the chapter’s code does. From each state that some pick reaches, skip the order, or take it if it fits. At each weight, keep the larger gain. Then step back from the best state. If states tie, start from the one with the least weight. At each layer, take the order when taking it gives at least as much as skipping it. Give each layer as its weights and gains. Then give the best tips and the pick.

  • layers:
    • after order 1: 0 kg 0, 3 kg 10
    • after order 2: 0 kg 0, 2 kg 8, 3 kg 10, 5 kg 18
    • after order 3: 0 kg 0, 2 kg 8, 3 kg 10, 5 kg 18, 7 kg 19, 8 kg 21
    • after order 4: 0 kg 0, 2 kg 8, 3 kg 10, 4 kg 12, 5 kg 18, 7 kg 22, 8 kg 21, 9 kg 23
  • best tips: 23
  • pick: orders 2, 3 and 4

Then: The box now holds one kilogram more. What is the best pick now, and its tips?

Answer to the follow-up: Orders 1, 2 and 3, 29 in tips. One more kilogram adds one row, for 10 kilograms, to the DP table, and the steps back start from a new best state.

Exercise 9

Turn the word lane into plant in as few edits as possible. Each edit inserts, deletes or changes one letter. As a graph, a state is a pair (i, j): i letters of lane used so far and j letters of plant used so far. The grid of the figure with Exercise 9 has every state, with lane across the top and plant down the side. It has no arrows yet. Draw the three kinds of arrow out of a state. Across uses the next letter of lane alone and deletes it. Down uses the next letter of plant alone and inserts it. The diagonal uses one letter of each. What does each kind cost, and which arrows cost 0? Then give every state the cheapest cost of a path to it from (0, 0). Go a row at a time. Row j holds the states with j letters of plant used. How many edits does it take? There is only one cheapest path. Which edits does it make, and which letters does it keep?

  • arrows: across 1, down 1, the diagonal 1 where its two letters differ and 0 where they are the same
  • free arrows: into (1, 2) for l, into (2, 3) for a, into (3, 4) for n
  • rows:
    • row 0: 0, 1, 2, 3, 4
    • row 1: 1, 1, 2, 3, 4
    • row 2: 2, 1, 2, 3, 4
    • row 3: 3, 2, 1, 2, 3
    • row 4: 4, 3, 2, 1, 2
    • row 5: 5, 4, 3, 2, 2
  • fewest edits: 2
  • edits: insert p, change e to t
  • kept: l, a, n

Then: git diff compares two files line by line, with inserts and deletes only and no change. Search this grid of letters the same way, with inserts and deletes only. How many edits does it take?

Answer to the follow-up: 3. Without the diagonal that changes a letter, only the free diagonals keep a letter. Every other letter of the two words is deleted or inserted on its own. That makes 4 + 5 letters less twice the 3 kept, l, a and n.

Exercise 10

Build the knapsack’s graph the other way around. A box holds 9 kilograms, and four orders wait: order 1 weighs 2 kilograms with a tip of 1, order 2 weighs 5 kilograms with a tip of 1, order 3 weighs 6 kilograms with a tip of 2 and order 4 weighs 3 kilograms with a tip of 3. Make a state a pair: how many orders are decided, and the total of the tips of the orders taken so far. From each state two arrows leave. One skips the next order and adds no weight. The other takes it, gains its tip and adds its weight, whether it fits or not. Fill the layers one order at a time, as in Exercise 8. This time, label each state with the lightest weight that a path into it carries. Give each layer as its tip totals, each with its lightest weight. Then read the last layer. What are the most tips whose lightest weight fits in the box? Which orders give them?

  • layers:
    • after order 1: 0 tips at 0 kg, 1 tip at 2 kg
    • after order 2: 0 tips at 0 kg, 1 tip at 2 kg, 2 tips at 7 kg
    • after order 3: 0 tips at 0 kg, 1 tip at 2 kg, 2 tips at 6 kg, 3 tips at 8 kg, 4 tips at 13 kg
    • after order 4: 0 tips at 0 kg, 1 tip at 2 kg, 2 tips at 6 kg, 3 tips at 3 kg, 4 tips at 5 kg, 5 tips at 9 kg, 6 tips at 11 kg, 7 tips at 16 kg
  • best tips: 5
  • pick: orders 3 and 4

Then: How many states can a layer of this graph hold? For this box, how many can a layer of the graph of Exercise 8 hold? Which of the two graphs grows with the box’s size?

Answer to the follow-up: Up to 8 here, one for every tips total from 0 to 7, against 10, one for every weight from 0 to 9 kilograms. The graph of Exercise 8 grows with the box’s size. This one grows with the total of the tips. So it is the smaller one when the tips are small integers and the weights are large, as with a box weighed in grams. The approximation chapter comes back to this version of the graph.

Exercise 11

The graph of the figure with Exercise 11 has no cycle, and some arrows cost less than 0. Put it in Kahn’s order. Count the arrows into every place, and queue the places with none, in alphabetical order. Then, while the queue has a place, take the front place. Lower the count of each place at the end of its arrows, in alphabetical order, and queue a place when its count reaches 0. Now take the places in Kahn’s order, starting with a at cost 0. Pass over a place that no arrow has reached. For every other place, try each arrow out of it once. Give Kahn’s order, every place’s cost from a, and each previous vertex.

  • order: b, c, h, a, i, e, d, f, g
  • costs: a 0, b none, c none, d 1, e 3, f 3, g −3, h none, i none
  • previous vertices: d from e, e from a, f from e, g from d

Exercise 12

On the graph of Exercise 2, work out the cost still to go to e from every place. This is Bellman’s equation read from the goal. Set r(e) = 0. Then r(u) = \min_{u \to v} \big( \text{cost}(u \to v) + r(v) \big), as in equation (6.12). Next, start at a. At every place, take the arrow whose cost plus r at its end is smallest. On a tie, take the letter that comes first. Give r for every place, with none where e cannot be reached, and give the path.

  • cost to go: a 15, b 7, c 6, d 11, e 0, f 4, g 15, h 9, i none
  • path: a, b, c, e

Exercise 13

The graph of the figure with Exercise 13 is a grid of junctions. Each block can be ridden both ways, in the minutes it shows. No block takes less than 2 minutes. Run A* from f to j. The estimate is twice the number of blocks still to go, counted along the grid. Each entry’s priority is the known cost plus the estimate. The smallest priority comes off first. On a tie, the letter that comes first goes first. The search stops when j is settled. Which places are settled, in order, with their priorities? What does the path cost, and which path is it? With the same tie rule, how many places does Dijkstra’s algorithm settle, up to and including j?

  • settled: f 8, g 11, h 12, i 13, k 13, l 13, m 13, n 13, o 13, j 13
  • cost: 13
  • path: f, k, l, m, n, o, j
  • **settled by A*:** 10
  • settled by Dijkstra: 14

Exercise 14

On the graph of the figure with Exercise 14, the number under each letter is an estimate of the cost still to go to f. Say whether each estimate is a lower bound on the cost still to go. Then say along which arrows the estimate drops by more than the arrow costs. Next, run A* from a to f, as in Exercise 13, settling each place once. What cost does it give f, and by which path? What is the cheapest cost, and by which path?

  • lower bounds: yes, every one
  • drops too far along: e→b, e→c
  • A* gives: 16 by a, b, c, f
  • cheapest: 13 by a, d, e, c, f

Exercise 15

A courier firm can send a van to the next town by three routes. Route A takes 20 minutes and has no toll. Route B takes 16 minutes and has a toll of 2 euros. Route C takes 10 minutes and has a toll of 3 euros. The firm pays at most 2 euros of toll a trip. Within that limit, it wants the quickest route. A planner turns the toll into minutes instead. At a price of p minutes for every euro, it picks the route with the smallest total of its minutes plus p times its toll. For every price of 0 or more, which route does it pick? Which route is quickest within the 2 euros? Is there a price that picks it?

  • picked at each price: C for every price below 10/3, A and C tied at 10/3, A for every price above 10/3
  • quickest within the toll: B, 16 minutes
  • a price that picks B: none: B scores no more than A only at a price of 2 or less, and no more than C only at 6 or more

Then: Suppose each road of a map has minutes and a toll. What must a state remember, so that a cheapest-path search finds the quickest route within the toll limit? Why can a price not do the same here?

Answer to the follow-up: The toll paid so far. A state is a place and the euros of toll paid to reach it. An arrow that would take the toll past 2 euros is left out. The quickest path to any state of the goal is the answer. The state keeps each route’s toll as it is, where a price adds it into the minutes. Drawn as points, with toll across and minutes up, the routes put B above the straight line from A to C, which at 2 euros gives 40/3 minutes. A price picks only a route that some straight line touches from below, with every other point on or above it. No such line touches B.

Exercise 16

Run Kruskal’s algorithm on the graph of the figure with Exercise 16. Take the links shortest first. Equal lengths go in alphabetical order of their ends, by the earlier end and then by the later one. Keep a link whose ends are not yet joined. Skip a link whose ends are joined already. Stop when one group is left. Which links does it look at, in order, and is each kept or skipped? Which links does it never look at, and what do the kept links total?

  • looked at: d–h kept, a–e kept, c–d kept, c–g kept, f–k kept, g–h skipped, e–f kept, f–i kept, f–j kept, g–k kept, a–b kept, h–l kept
  • never looked at: b–f, b–g, d–g, i–j
  • total: 29

Then: Equal lengths now go the other way, latest letters first. Which links does the tree hold, and what does it total?

Answer to the follow-up: a–b, a–e, c–g, d–h, e–f, f–i, f–j, f–k, g–h, g–k, h–l: the same total, 29. g–h takes the place of c–d, a link of the same length. Ties allow more than one cheapest tree. That is why the box’s invariant 1 says “some minimum such set”.

Exercise 17

Run Prim’s algorithm on the graph of Exercise 16, starting at a. Keep taking the shortest link from a place already joined to a place not yet joined. Equal lengths go in alphabetical order of their ends, as in Exercise 16. In what order are the links added?

  • added: a–e, e–f, f–k, f–i, f–j, g–k, c–g, c–d, d–h, a–b, h–l

Then: Now give each place a priority equal to its cost from a so far plus the link, as Dijkstra’s algorithm does. Which links does the tree from a hold? How much longer is it than the cheapest tree?

Answer to the follow-up: a–b, a–e, b–g, c–g, d–h, e–f, f–i, f–j, f–k, g–h, h–l, 31 in all, 2 more than the 29 of the cheapest tree. Each place gets its cheapest path from a. That is a different promise from joining everyone for the least.

Which promise broke

Exercise 18

A program computes the cheapest costs from a on the graph of Exercise 2 and returns a 0, b 8, c 9, d 4, e 15, f 17, g 10, h 16, i 18.

  • verdict: broken: the promise, every place that can be reached gets the cost of its cheapest path. Invariant 1, a settled place’s cost is its cheapest, names the same fault inside the method and is right too
  • detail: the arrow e→f gives f 15 + 1 = 16, less than the 17 returned. These are the costs of the paths with the fewest arrows
  • broken: promise

Exercise 19

Bellman–Ford, run from a on the graph of Exercise 4, reports the cycle d, g, h, d as a negative cycle.

  • verdict: broken: the promise, the answer is such a cycle only when the start reaches a negative cycle
  • detail: its arrows total 6, which is not negative. This graph has no negative cycle, so the answer must be the cheapest costs
  • broken: promise

Exercise 20

On the orders of Exercise 8, a program packs orders 1, 2 and 4, for 22 in tips. It says no selection gains more.

  • verdict: broken: the promise, the best selection of orders
  • detail: orders 2, 3 and 4 fit, 9 kilograms, and gain 23. The program took the best tips per kilogram first
  • broken: promise

Exercise 21

On the graph of Exercise 16, a program returns the links a–b, a–e, c–d, d–h, e–f, f–i, f–j, f–k, g–h, g–k, h–l, 29 in all, as a minimum spanning tree.

  • verdict: correct: the links join every place, close no cycle, and no other such set has a smaller total
  • detail: it is not the tree that Kruskal’s algorithm keeps with ties in alphabetical order: g–h takes the place of c–g, of the same length. But the promise asks for no tree in particular, since equal lengths allow more than one cheapest tree
  • broken: none

You supply the input

Exercise 22

Add one arrow to the graph of Exercise 2, out of i and costing −3. It must lead to another place, one to which i has no arrow yet. Choose it so that Dijkstra’s algorithm, run from a as in Exercise 2, gives some place a wrong cost while no cycle is negative. Give one that works.

  • an example: i→h

Then: Name all the arrows that work, and say why the others do not work.

Answer to the follow-up:

  • every case: i→h: through the new arrow, some place costs less than the cost at which it was settled. That place is the arrow’s end. The lower cost comes too late: i is settled last, at 17, so the code skips every arrow out of i. i→a, i→b, i→c, i→d, i→g do no harm. Through the new arrow, each end would cost 17 − 3 = 14, but each already costs less. i→e, i→f close a negative cycle, since a path back to i costs less than 3

Exercise 23

Bellman–Ford on the graph of Exercise 4 takes the places in alphabetical order, and it needs several rounds. Give another order in which to take the places, so that the first round already gives every place its cheapest cost. Each place’s arrows are still tried in alphabetical order of where they lead.

  • an example: a, d, b, e, g, h, c, i, f

Then: Say what every such order has in common.

Answer to the follow-up:

  • every case: every place that is some place’s previous vertex comes after its own previous vertex. Here d comes after a. b and h come after d. i comes after h. So the arrows of every cheapest path are tried in order, from a out, in the first round. The other places, here c, e, f and g, can stand anywhere. Each gets its cost when its previous vertex is taken. The second round then lowers nothing

Exercise 24

On the graph of Exercise 14, forget its estimates. Give a new estimate, one integer per place. It must keep the box’s invariant, and with it A* from a to f must settle only the places of the cheapest path.

  • an example: a 13, b 10, c 5, d 10, e 9, f 0

Then: Say what every such estimate has in common.

Answer to the follow-up:

  • every case: it keeps the invariant. Every place off the path that an arrow from the path reaches gets a priority above 13, the cheapest cost to f. That priority is the place’s cost through the path plus its estimate. Here b costs 6 through the path, so its estimate must be at least 8. The estimate 0 fails: it is Dijkstra’s algorithm, and it settles b before f. The cost still to go does it here, because the cheapest path, a, d, e, c, f, is the only one

Exercise 25

On the graph of Exercise 16, Kruskal’s algorithm leaves out b–f. Give b–f a new length, an integer of at least 1, so that Kruskal’s algorithm keeps it. Use the tie rule of Exercise 16.

  • an example: 1

Then: Name all the lengths that work, and say why.

Answer to the follow-up:

  • every case: every length from 1 to 3. The tree’s path between its ends has a–b as its longest link, of length 4. A shorter link is looked at before a–b. It finds its ends in two groups, and it is the cheapest link across the cut that a–b crosses

Which idea do you reach for

Exercise 26

A museum app tells a visitor at the entrance the walking time to every room. Corridors take different times, none negative. The app should show each room’s time as soon as it is certain, the nearest rooms first.

  • (a) reduction
  • → (b) best-first search
  • (c) greedy exchange
  • (d) monotone fixed point

Answer: (b) Always settle the room with the smallest known time, then try the corridors out of it. No corridor costs less than 0, so no time found later beats the smallest. Each room’s time is final the moment it is settled.

Exercise 27

A sawmill cuts a 12-meter log into pieces for sale. Its price list gives a price for a piece of each length from 1 to 12 meters, and a cut loses no wood. Which cuts bring the most money?

  • (a) greedy exchange
  • (b) make the state remember it
  • → (c) dynamic programming
  • (d) best-first search

Answer: (c) The best for 12 meters is the best, over the first piece, of its price plus the best for what is left. Work out the best for every shorter length once, shortest first, and keep it.

Exercise 28

A price site keeps the lowest price found so far for every product, in cents. A bundle’s price is built from the stored prices of the products in it. Every night the site goes through all the shops again, and the shops’ offers do not change during the night. A price it finds can only lower what is stored. When can it stop for the night?

  • → (a) monotone fixed point
  • (b) dynamic programming
  • (c) best-first search
  • (d) greedy exchange

Answer: (a) Prices only drop, and each is the price of a real offer. A price in cents cannot drop below 0, so the passes cannot keep lowering it forever. Once a whole pass over the shops lowers nothing, the next pass would find the same, since the offers stay as they are for the night. So the stored prices are the answer. The stop needs both: offers fixed while the passes run, and prices that can drop only so many times.

Exercise 29

A film festival has one screen and forty films, each with a start time, an end time and a rating. It wants screenings that never overlap, with the largest total rating.

  • (a) greedy exchange
  • → (b) reduction
  • (c) best-first search
  • (d) make the state remember it

Answer: (b) Turn it into a question about paths. Make a state for each moment when a film starts or ends. Draw a free arrow from each moment to the next, and an arrow from a film’s start to its end that gains its rating. Every arrow goes forward in time, so there is no cycle, and the longest path is the best program.

Exercise 30

A rail pass lets a traveler take at most three night trains and any number of day trains. A planner wants the cheapest trip between two cities that keeps to the pass.

  • → (a) make the state remember it
  • (b) reduction
  • (c) monotone fixed point
  • (d) greedy exchange

Answer: (a) Two visits to one city, one with a night train left and one with none, lead to different trips. Make a state a city and the night trains taken so far, which gives four copies of every city. The cheapest path in that graph keeps to the pass.

Exercise 31

A puzzle app solves a sliding-tile puzzle in the fewest moves. A move slides one tile one square. From any position, the app can quickly add up how many squares each tile is from its home square. The app should look at as few positions as it can and still find the fewest moves.

  • (a) greedy exchange
  • (b) monotone fixed point
  • → (c) bound and prune
  • (d) reduction

Answer: (c) A move brings at most one tile one square closer to home, so it lowers the sum by at most 1. The sum is therefore never more than the number of moves still needed. It is a lower bound on the rest. Take a position and add its moves so far to its sum. If this total already reaches the length of the best solution found so far, the position cannot lead to a shorter solution. So the search drops it without looking further.

Exercise 32

A biologist has 500 samples and the distance between every two samples. The biologist wants them in 5 groups, so that the two closest samples in different groups are as far apart as possible.

  • (a) dynamic programming
  • → (b) greedy exchange
  • (c) best-first search
  • (d) monotone fixed point

Answer: (b) Join the two closest samples in different groups, again and again, until 5 groups are left. This is Kruskal’s order, stopped early. The closest pair across groups is then the next link it would take. An exchange shows that no other grouping keeps its closest pair farther apart.

The tests pass. What did they miss?

Exercise 33

A delivery app finds the quickest time from its depot to every address with Dijkstra’s algorithm. Its tests pass: on a thousand random maps, each in one piece, every time matches a slow search that tries every path. After launch, a bridge closes. The addresses beyond it show a time of 0 minutes, and drivers are sent there first. What requirement did the tests miss?

Answer: The promise for places that no path reaches. Every test map was in one piece, so every place was reached, and that part of the promise never ran. The box promises that such a place is reported as unreachable. Grade on this missed requirement. How the code came to print 0 is not asked; a missing cost printed as 0 is one likely way.

Then: Write the requirement as a sentence that a test could check.

Answer to the follow-up: A place that no path reaches is reported as unreachable, with no time and no previous vertex. The test builds a map in two pieces on purpose and checks every place of the far piece.

Exercise 34

A currency desk finds the cheapest chain of exchanges from euros to every currency by Bellman–Ford. Each exchange is an arrow whose cost comes from -\ln of its rate, as in Exercise 7. Its tests pass: on random rate tables, every cost matches a slow search. Each test table is made from one price per currency, less a fee on each exchange. One morning the rates allow a loop of exchanges that euros can reach and that ends with more money than at its start. The desk prints its costs as on any other day. What requirement did the tests miss?

Answer: The second branch of the promise. On a test table, every loop of exchanges pays its fees and gains nothing, so no test table held a negative cycle. So every test took the branch that returns costs. The box promises that when the start reaches such a cycle, the answer is the cycle. The loop must be one that euros reach: for a loop they cannot reach, printing the costs is right, and an answer that says so is right too. Grade on this missed requirement, not on a guess at the code. Stopping after the last useful round without the round that checks is one way to miss it.

Then: Write the test.

Answer to the follow-up: On a table with a negative loop that euros reach, the answer is such a loop. Each currency in it is followed by the end of its arrow, and the arrows total less than 0. The test builds such a table on purpose. It also builds a table with a negative loop that euros cannot reach. There the costs must still come back.

Exercise 35

A warehouse packs a van with the knapsack as a longest path. Its tests pass: on random orders, the best value always matches a slow search through every selection. In use, the loaders find that the orders it lists weigh more than the van takes. What requirement did the tests miss?

Answer: The selection. The promise is the best selection, and a selection is the orders, not only their total. The tests compared only the best value, which the layers get right on their own. The orders come from stepping back through the layers, and no test looked at them. Grade on this missed requirement. The stem does not say which slip in stepping back made the list too heavy, so an answer need not name one.

Then: Write the test that would have caught it.

Answer to the follow-up: Every order returned is one of the orders given, no order is returned twice, the orders fit in the van, and their values add up to the value returned. Check this on every test, beside the value. The second check matters: with order 1 of 1 kilogram worth 1, order 2 of 2 kilograms worth 2, and a van that takes 2 kilograms, the list “order 1, order 1” fits and adds up to the best value, 2, yet it takes one order twice.

Exercise 36

A council plans which roads to clear after a storm with Kruskal’s algorithm, joining every village for the least work. Its tests pass: on random connected maps, the total always matches a slow search through every spanning tree. After a landslide splits the valley in two, the program stops with an error. It has read past the end of its list of roads. What requirement did the tests miss?

Answer: A map in more than one piece. The code kept taking roads until it had one fewer than the villages. A map in two pieces never allows that, so the code ran past the last road. The promise is to join every two places that the graph joins. On such a map that is a spanning forest, and every test map was in one piece.

Then: Write the requirement as a sentence that a test could check.

Answer to the follow-up: On a map in several pieces, the links kept join every two places that the map joins, they close no cycle, and their total is the least: on small maps, it equals the sum, over the pieces, of the cheapest spanning tree of each piece found by a slow search. That gives one cheapest tree per piece. The test builds a map in two pieces on purpose.

Fill in the contract

Exercise 37

A strategy game moves units over a map of a million tiles. Each tile takes some seconds to cross, never a negative number. Roads make some tiles quicker. When a player clicks, the unit must start moving within two milliseconds, along the quickest way to the target. Players notice a unit that takes a needlessly slow way. Buildings go up during play and can block tiles. Work out the parts of a contract for this workload, in the order that the contracts chapter uses. Give one or two sentences for each part.

Answer, one line per question. Grade on the parts kept apart, not on the wording:

  1. Goal: for each click, the quickest way from the unit’s tile to the target tile, found fast enough that the unit starts moving within two milliseconds.
  2. Floor: the search must at least look at the tiles of the way it returns. The scarce resource is time per click, and a search that settles every tile of the map does not fit in that time.
  3. Promise and invariants: the way returned is the quickest on the map as it stood at the click, or “no way” when there is none. What must remain true: the estimate is never negative, is 0 at the target, and along any step drops by no more than the step takes.
  4. Idea: A*. The estimate is the fewest moves to the target on a map with no obstacles, times the seconds of the quickest tile on the map.
  5. Cost: each tile is settled at most once, so it is never worse than Dijkstra’s algorithm. How many tiles are settled depends on how much the estimate knows. A long way round a lake settles many tiles, and then the search can take longer than two milliseconds. So A* alone cannot promise the two milliseconds on such a way, and the contract must say how the requirement is met. Any of these is right: work done before play, such as distances to a few landmark tiles or a coarse map of regions, kept up to date as buildings go up; an explicit bound, such as a first stretch of the way within two milliseconds while the search finishes; or a requirement agreed again with the game’s designers. A contract that names A* alone and still promises two milliseconds on every map does not meet the requirement.
  6. Assumes: the map does not change during one search, and no tile is quicker than the quickest tile the estimate uses. When a building blocks a tile, the way belongs to a map that no longer exists, and the game asks again from where the unit stands.

Then: Suppose a building blocks the way while a unit is on it. Which part of your contract says what happens then? Why does the method alone not settle it?

Answer to the follow-up: The Assumes. The promise is about the map at the click, so a building put up later breaks no promise. The contract has to say what the game does then. Asking again from the unit’s tile, on the map as it is now, is enough, because a quickest way from there is all the unit needs. The search cannot know that the map will change.

Fix the code, the box, or the design?

Exercise 38

An AI writes A* from its box for a courier firm. The estimate is 0 at every place, so the code is Dijkstra’s algorithm to one goal. Asked for the cheapest path from a to g on the graph of Exercise 2, it stops as soon as g is settled. To plan the next order, the dispatcher reads the cost of f off that answer, 17. But the cheapest path to f costs 16. Which of the three is it, and why?

Answer: fix the box. The code keeps its box. A*’s promise is the cheapest path for the goal. Only the goal’s cost and the costs of the places settled before it are final. The dispatcher wanted the cheapest cost of every place, which that box never promised.

Then: Rewrite the line of the box that has to change. Say what the change costs, and give the cost that the dispatcher expects.

Answer to the follow-up: Promise: every place that can be reached gets the cost of its cheapest path. That is Dijkstra’s box. The search no longer stops at the goal. It settles every place it can reach and tries the arrows out of all of them, not only out of those settled before the goal. A narrower line also works: the goal and every place that the next order needs. The search then stops once the last of them is settled. Here: f costs 16.

Exercise 39

A shipping firm packs containers with the knapsack as a longest path, as the chapter builds it. For years it has weighed everything in kilograms. A new customer weighs in grams: 30 parcels and a container that takes 20 tonnes, so the container holds 20,000,000 grams. The code follows the chapter’s Python, and it is still correct. But a single packing now runs for minutes and fills gigabytes of memory. Which of the three is it, and why?

Answer: change the design. The method keeps its promise, the best selection. Its cost grows with the orders times the container’s size. Here that is 31 layers of 20,000,001 states, 620,000,031 states in all, each with up to two arrows. The chapter’s Python keeps every layer for stepping back, so at 8 bytes a slot the table alone takes about 5 gigabytes. The design assumed weights in kilograms, which keep the container’s size small, and that no longer fits the job.

Then: Name a design that fits, and say what it costs.

Answer to the follow-up: If the values are small integers, turn the table round, as in Exercise 10. Keep, for each total value, the least weight that reaches it. Then the states are the parcels times the total value, and the grams no longer matter. If the values are large, scale them first. Choose an error \varepsilon, say 1/10. Leave out any parcel that does not fit on its own. Take as the unit \varepsilon times the largest value, divided by 30. Divide every value by the unit, round down, and run the turned-round table on these values. Each is at most 30/\varepsilon = 300, so the table has at most 31 × 9,001 = 279,031 states, against 620,000,031. The weights stay exact, so the pick fits. Each value loses less than one unit, so a pick loses less than 30 units. That is \varepsilon times the largest value, and so at most \varepsilon times the best, since the parcel with the largest value fits on its own. The pick is worth at least 1 - \varepsilon times the best. A smaller \varepsilon costs more states, in time and in memory alike. Rounding the weights instead promises nothing. Parcels of 10,000,500 and 9,999,500 grams fill the container exactly, but rounded up to kilograms they need 20,001 kilograms and no longer fit together. Rounded down, a pick can overfill the container. For only 30 parcels there is also an exact design, whatever the unit of weight: meet in the middle. List the 32,768 picks of each half with their weights and values. Sort one list by weight, keeping the best value up to each weight. For each pick of the other list, look up the best partner that still fits. That is 65,536 picks, a sort and a lookup per pick, in memory for 65,536 picks.

Exercise 40

An AI writes Kruskal’s algorithm from the box, but it keeps one mark per place instead of union-find. A link is kept unless both its ends are marked already, and keeping a link marks its ends. On the graph of Exercise 16 it keeps 9 links, 23 in all. Which of the three is it, and why?

Answer: fix the code. The box’s invariant 2 says two places are in one group exactly when the kept links join them. A mark says only that a place touches some kept link. It does not say which group the place is in. So a link between two marked places in different groups is skipped, and the answer leaves the graph in 3 pieces. Ask union-find whether the two ends are joined.

Then: Name a test you would keep from the AI.

Answer to the follow-up: The links kept join every two places that the graph joins, and they close no cycle. A search over the kept links checks the joining. On small graphs, their total also equals that of a slow search through every spanning tree.

Derive it

Exercise 41

A courier has one voucher, which makes one street of a trip free. No street costs less than 0. Write a procedure, as code or as precise steps, that finds the cheapest trip from one place to another. The voucher may be used at most once. Your answer must say what a state of your graph is. It must say which arrows leave each state, and what they cost. It must also say why the cheapest path in your graph is the cheapest trip with the voucher, and why Dijkstra’s algorithm may run on that graph.

A state is a place together with whether the voucher is used, so there are two states per place. From (u, unused), each arrow u→v leads to (v, unused) at its cost and to (v, used) at 0. From (u, used), each arrow leads to (v, used) at its cost. No arrow leads back to unused, so a path uses at most one free arrow. Every trip with the voucher used at most once is one such path, of the same cost. No arrow costs less than 0, so the box’s Assumes holds, and Dijkstra’s algorithm from (start, unused) is right. The answer is the cheaper of the goal’s two states.

Answers: the trip a, d, h, i costs 7, with the voucher on a→d. The cheapest trip without it, a, b, c, e, h, i, costs 14, and it costs 8 with its costliest arrow made free.

Grade the construction by its costs and its reasons, not by its shape. An equivalent graph is right too: one with an extra goal state, one that leaves out the states no trip reaches, or the two copies of each place kept implicitly in code. The hint’s count fits only the graph with two copies of each place, so it is not a check.

Stretch: Extend it to k vouchers. How does the work then grow with k and the arrows?

Answer to the follow-up: Make k + 1 copies of every place, one per number of vouchers used. For every arrow of the map, each copy but the last has a free arrow to the next copy. For n places and m arrows, that makes (k + 1) n states and (2k + 1) m arrows. The work grows with k + 1 times the arrows, times a logarithm.

Flow, cuts, matching

The keys to the exercises, under the numbers the chapter gives them.

Run it and report the state

Exercise 1

A flow network has the source s, the sink t and seven arrows, with these capacities: s \to a 5, s \to b 3, a \to b 4, a \to c 3, b \to d 3, c \to t 5 and d \to t 4. Two additions each saturate their bottleneck, first along s \to a \to b \to d \to t and then along s \to a \to c \to t. How much does each send? Draw the residual graph after them. Give every arrow with residual capacity, reverse arrows included, and its residual capacity.

  • sent: 3, then 2
  • residual capacity: a→s 5, s→b 3, a→b 1, b→a 3, a→c 1, c→a 2, d→b 3, c→t 3, t→c 2, d→t 1, t→d 3

Exercise 2

Go on from the flow of Exercise 1. Add along one augmenting path with the fewest arrows at a time, until none is left. Each search tries a vertex’s arrows in the order of the list. It tries each reverse arrow where its own arrow stands in the list. Give each path and what it adds. Which path takes a unit back, and along which reverse arrow? What is the final amount? Which vertices does the last search reach, and which cut do they give?

  • paths: s→b→a→c→t adds 1
  • taken back along: b→a
  • amount: 6
  • last search reaches: s, a, b
  • cut: a→c 3, b→d 3

Exercise 3

A flow network has the source s, the sink t and eight arrows, with these capacities: s \to a 5, s \to b 4, a \to b 2, a \to c 2, b \to d 4, c \to b 2, c \to t 4 and d \to t 2. Run the loop with fewest arrows first from no flow. Each search tries a vertex’s arrows in the order of the list. It tries each reverse arrow where its own arrow stands in the list. Give each augmenting path and what it adds. Which vertices does the last search reach? Give the arrows of that cut and its capacity. Which arrow comes back into the source’s side, and why does it not count?

  • paths: s→a→c→t adds 2, s→b→d→t adds 2
  • amount: 4
  • last search reaches: s, a, b, d
  • cut: a→c 2, d→t 2
  • capacity: 4
  • comes back: c→b
  • why it does not count: the cut’s capacity counts only the arrows from the source’s side to the sink’s side. An arrow coming back can only return flow to the source’s side, which lowers the amount, so it adds nothing to what can cross

Exercise 4

A residual graph has the source s, the sink t and twelve arrows with residual capacity: s \to a, s \to b, a \to b, a \to c, b \to a, b \to d, c \to a, c \to b, c \to e, d \to e, e \to c and e \to t. Draw its layers, and say which arrows a round of Dinic’s rule keeps. For each arrow it drops, say why.

  • layers: 0: s; 1: a, b; 2: c, d; 3: e; 4: t
  • kept: s→a, s→b, a→c, b→d, c→e, d→e, e→t
  • dropped: a→b (same layer), b→a (same layer), c→a (goes back toward the source), c→b (goes back toward the source), e→c (goes back toward the source)

Exercise 5

A flow network has the source s, the sink t and ten arrows, with these capacities: s \to a 4, s \to b 3, a \to b 2, a \to c 2, b \to d 4, c \to a 1, c \to t 3, d \to b 1, d \to c 2 and d \to t 2. Run the loop with Dinic’s rule from no flow. Each search and each walk tries a vertex’s arrows in the order of the list. They try each reverse arrow where its own arrow stands in the list. For each round, give the sink’s layer and the paths the walk sends, in order, with what each adds. How many rounds send something, and what is the final amount?

  • rounds: layer 3: s→a→c→t adds 2, s→b→d→t adds 2; layer 4: s→b→d→c→t adds 1
  • rounds that send: 2
  • amount: 5

Exercise 6

Five people, P1 to P5, and five objects, V to Z, have these acceptable pairs: P1 accepts V or W; P2 accepts V; P3 accepts W, X or Y; P4 accepts V or W; P5 accepts Y or Z. Build the matching network, find a largest matching, and give a cover with as many members as the matching has pairs. Say why no matching has more pairs. Any largest matching is accepted.

  • network: an arrow of capacity 1 from the source to each person, one from each person to each object that person accepts, and one from each object to the sink
  • pairs: P1–V, P3–X, P4–W, P5–Y
  • size: 4
  • accepted: any largest matching: the table has 12 of them, each with 4 pairs. The cover is the only one with 4 members
  • cover: P3, P5, V, W
  • why no more: every pair of a matching is incident to a member of the cover, and no member is incident to two pairs of one matching, so no matching has more pairs than the cover has members
  • supplementary, not graded: someone always stays unmatched, and the blocked group shows why: P1, P2 and P4 accept only V and W, two objects for three people

Exercise 7

Five people, P1 to P5, and five objects, V to Z, have these acceptable pairs: P1 accepts V or X; P2 accepts W or X; P3 accepts X; P4 accepts W, Y or Z; P5 accepts V or W. Find a largest matching. Someone stays unmatched: give the blocked group that the last search reaches, and the objects that its people accept. Any largest matching is accepted.

  • pairs: P1–V, P2–W, P3–X, P4–Y
  • size: 4
  • accepted: any largest matching: the table has 10 of them, and from every one the last search reaches the same blocked group
  • blocked group: P1, P2, P3, P5
  • they accept: V, W, X

Exercise 8

The quiet rooms with other wishes. This one is for after Matching as a flow. Change the friends’ wishes. Room 4 is full of boxes, so nobody can take it. Anita accepts room 1 or room 3, and Daniel accepts only room 1. Tomás accepts room 1 or room 2. Juan accepts only room 3. Start from Tomás in room 1 and Anita in room 3, and run the loop with fewest arrows first. Then start again from the same two pairs, but take the friends without a room one at a time, Juan first, and look for an augmenting path through each of them. Each time, say who is left out and how many pairs the run ends with. Last, overlay the two answers, and show that the pairs that are in only one of them form an alternating path.

  • fewest arrows first: adds along s→Daniel→room 1→Tomás→room 2→t; Anita room 3, Daniel room 1 and Tomás room 2; Juan left out; 3 pairs
  • Juan first: adds along s→Juan→room 3→Anita→room 1→Tomás→room 2→t; Anita room 1, Tomás room 2 and Juan room 3; Daniel left out; 3 pairs
  • overlay: Daniel–room 1–Anita–room 3–Juan

Exercise 9

A flow network has the source s and the sink t, and its arrows, each with (capacity, cost), are s \to a (2, 1), s \to b (2, 3), a \to b (2, 1), a \to c (1, 6), b \to d (2, 2), c \to d (1, 1), c \to t (2, 1) and d \to t (2, 3). The cheapest path rule is asked for 3 units. Its first step has sent 2 units along s \to a \to b \to d \to t, and the heights after it are s 0, a 1, b 2, c 7, d 4, t 7. Give the changed cost of every arrow with residual capacity, reverse arrows included. Then take the next step. The search settles the vertex with the smallest cost first. On a tie, it settles the vertex that comes earlier in the order s, a, b, c, d, t. It stops when the sink is settled. Give the path, what it sends, the heights after it, and the total cost.

  • changed costs: a→s 0, s→b 1, b→a 0, a→c 0, d→b 0, c→d 4, c→t 1, t→d 0
  • path: s→b→a→c→t
  • sends: 1
  • heights: s 0, a 2, b 3, c 8, d 6, t 9
  • total cost: 23

Exercise 10

A flow network has the source s and the sink t, and its arrows, each with (capacity, cost), are s \to a (2, 2), s \to b (1, 1), a \to b (2, 1), a \to c (2, 1), b \to c (1, 1), b \to d (2, 4), c \to t (2, 1), d \to c (1, 1) and d \to t (1, 5). Run the cheapest path rule for 3 units, from every height at zero. The search settles the vertex with the smallest cost first. On a tie, it settles the vertex that comes earlier in the order s, a, b, c, d, t. It stops when the sink is settled. For each step, give the path, what it sends and the heights after it. Which step uses a reverse arrow, and what does it refund? What does the flow cost?

  • steps: s→b→c→t sends 1, heights s 0, a 2, b 1, c 2, d 3, t 3; s→a→c→t sends 1, heights s 0, a 2, b 2, c 3, d 4, t 4; s→a→c→b→d→t sends 1, heights s 0, a 2, b 2, c 3, d 6, t 11
  • reverse arrow: c→b refunds 1
  • total cost: 18

Exercise 11

A flow network has the source s and the sink t, and its arrows, each with (capacity, cost), are s \to a (1, 4), s \to b (2, 1), a \to b (3, 4), a \to c (1, 4), b \to c (3, 2), b \to t (1, 1) and c \to t (2, 3). Asked for 3 units, a program returns the flow s \to a 1, s \to b 2, a \to c 1, b \to c 1, b \to t 1, c \to t 2; all other arrows carry zero. It costs 19. As its certificate the program gives the heights s 0, a 4, b 6, c 8, t 11. For every arrow, give its changed cost and say whether it fits the arrow’s load. Then a second program returns another flow of 3 units on the same network, at a cost of 21: s \to a 1, s \to b 2, a \to b 1, b \to c 2, b \to t 1, c \to t 2; all other arrows carry zero. Show that no heights can pass it, by finding a cycle of arrows with room whose cost is below zero.

  • changed costs: s→a 0 (full, fits); s→b −5 (full, fits); a→b 2 (empty, fits); a→c 0 (full, fits); b→c 0 (partly loaded, fits); b→t −4 (full, fits); c→t 0 (full, fits)
  • cycle: a→c→b→a, cost −2: one unit around it gives the first program’s flow, of cost 19

Exercise 12

A flow network has the source s and the sink t, and its arrows, each with (capacity, cost), are s \to a (2, 1), s \to c (1, 5), a \to b (3, 2), a \to c (3, 3), b \to t (3, 2) and c \to t (1, 0). Send 3 units as cheaply as possible with the cheapest path rule. In each round, search the residual graph with the Bellman–Ford algorithm instead of Dijkstra’s algorithm, and use no heights. For each round, give the path, its cost and the amount it adds. Then give the final flow’s cost. Last, run Bellman–Ford once more on the final residual graph, from a new vertex with an arrow of cost 0 to every vertex. Show that the costs it finds, used as heights, pass the height check. Every arrow with residual capacity must have a changed cost of at least zero.

  • rounds: s→a→c→t costs 4, adds 1; s→a→b→t costs 5, adds 1; s→c→a→b→t costs 6, adds 1
  • ties: none: each round has only one cheapest path
  • refund: round 3 takes c→a, which refunds 3
  • flow cost: 15
  • heights: s −6, a −4, b −2, c −1, t 0
  • height check: a→s 1, c→s 0, a→b 0, b→a 0, a→c 0, b→t 0, t→b 0, t→c 1; every arrow with residual capacity is at zero or more

Which promise broke

Exercise 13

A flow network has the source s, the sink t and these capacities: s \to a 2, s \to b 3, a \to b 3, a \to c 1, c \to b 3, b \to t 3 and c \to t 3. A program returns the flow s \to a 1, s \to b 3, a \to c 1, b \to t 3, c \to t 1; all other arrows carry zero. It sends 4 units in all, and as its certificate the program gives the side s, a and b. Its own checker then adds up every arrow between the two sides, gets 7, and reports that the flow cannot be shown to be the largest. Judge that report: is it correct?

  • verdict: the report is wrong; the flow and its side are a correct answer
  • detail: a cut’s capacity counts only the arrows from the source’s side to the sink’s side. The arrow that comes back, c→b, does not count. The cut’s capacity is 4, equal to the flow, so the flow is the largest and the side proves it

Exercise 14

On the flow network s \to a 1, s \to b 6, a \to b 5, a \to c 4, b \to d 2, c \to d 3, c \to t 1 and d \to t 2, with source s and sink t, a program returns the flow s \to a 1, s \to b 2, a \to c 1, b \to d 2, c \to t 1, d \to t 2; all other arrows carry zero. It sends 3 units in all. As its certificate it gives the side s, a, b, c and d, whose cut is c \to t 1 and d \to t 2. The last search of the loop reaches only s and b.

  • verdict: correct: the side holds the source and not the sink, and its cut has capacity 3, equal to the flow
  • detail: it is not the side the last search reaches. But any cut whose capacity equals the flow amount proves the flow the largest, since no flow exceeds any cut

Exercise 15

On the flow network s \to a 2, s \to b 2, a \to b 2, a \to c 2, b \to d 2, c \to t 2 and d \to t 2, with source s and sink t, a program sends 2 units along s \to a \to b \to d \to t. It finds no path from s to t along the network’s arrows that are not yet full, and it reports a maximum flow of 2 units.

  • verdict: broken: the third promise, report none only when no augmenting path is left
  • detail: the program looked only at the arrows forward. The reverse arrow b→a gives the augmenting path s→b→a→c→t, and the largest amount is 4
  • also accepted: the Max flow design box’s Promise, a cut whose capacity equals the flow. The forward search reaches s and b, and that side’s cut has capacity 4, not 2

Exercise 16

Five people, P1 to P5, and five objects, V to Z, have these acceptable pairs: P1 accepts X; P2 accepts Y; P3 accepts W, X or Z; P4 accepts Y; P5 accepts Y or Z. A program returns the matching P1–X, P2–Y, P3–Z and calls it largest. Beside it, it gives the cover P1, P3, P5, Y, which has a member incident to every acceptable pair.

  • verdict: broken: the promise, a cover with as many members as the matching has pairs
  • detail: the cover has 4 members and the matching 3 pairs, so the cover proves only that no matching has more than 4. One exists: P1–X, P2–Y, P3–W, P5–Z

Exercise 17

A flow network has the source s and the sink t, and its arrows, each with (capacity, cost), are s \to a (1, 1), s \to b (1, 4), a \to b (1, 1), a \to t (1, 4) and b \to t (1, 1). Asked for one unit, a program sends it along s \to a \to t, at a cost of 5, and calls it the cheapest. As evidence it gives the heights s 0, a 1, b 2, t 3.

  • verdict: broken: the promise, every arrow with residual capacity has a changed cost of at least zero
  • detail: the reverse arrow t→a has the changed cost −2. Sending one unit around the cycle it closes gives the flow along s→a→b→t, which costs 3
  • also accepted: read on the arrows themselves: a→t is full, and its changed cost is 2, above zero, so the heights do not fit its load

Exercise 18

Four people and four objects have these costs: P1’s costs for W, X, Y and Z are 1, 7, 8 and 3; P2’s costs for W, X, Y and Z are 1, 9, 2 and 1; P3’s costs for W, X, Y and Z are 1, 4, 4 and 1; P4’s costs for W, X, Y and Z are 8, 6, 8 and 4. A program returns the assignment P1–W, P2–Y, P3–X, P4–Z, which costs 11, and calls it the cheapest. As evidence it gives the labels P1 3, P2 2, P3 3, P4 6 for the people and W −2, X 0, Y 0, Z −2 for the objects.

  • verdict: broken: the promise, every chosen pair is tight
  • detail: the labels fit every pair, but on the chosen pair P3–X they add up to 3, less than its cost 4. The labels total 10, so no assignment costs less than that, and P1–W, P2–Y, P3–Z, P4–X costs 10
  • also accepted: the labels total 10, and the assignment costs 11. A certificate whose total differs from the cost fails the third step of the label check, the same failure

You supply the input

Exercise 19

Give a family of flow networks, one for every positive integer U, each with largest capacity U, on which a path rule that ignores the number of arrows can need at least U additions. Then say why fewest arrows first needs only a few additions on every network of your family.

  • what every family needs: its networks keep the same size while U grows, and some choice of augmenting paths adds only a bounded amount each time, so the additions grow with U. Any family with that property is accepted. The usual one: two ways from the source to the sink, each of capacity U, joined by a middle arrow of capacity 1. A path through the middle arrow, forward or back, adds only 1, so the paths can alternate U times on each side
  • an example: s→a U, s→b U, a→b 1, a→t U, b→t U; adding along the path with the most arrows takes 6 additions for U = 3, 10 additions for U = 5, 16 additions for U = 8
  • fewest arrows: 2 additions for every U: each path through the middle arrow has 3 arrows, so the two paths of 2 arrows go first and fill the network. In general the bound n m on additions does not grow with the capacities

Exercise 20

Give a flow network with two minimum cuts, and an arrow of one of them whose widening buys nothing. Say what every such case has in common.

  • every case: the widened arrow lies in one minimum cut, and another minimum cut leaves it out. That cut keeps its capacity, so the maximum flow stays
  • an example: s→a 3, a→b 4, b→t 3: the cuts at s→a and at b→t both have capacity 3. Widening s→a to 4 leaves the maximum flow at 3

Exercise 21

Give a table of costs on which cheapest first, which again and again takes the cheapest pair that is still possible, costs more than the assignment. Say what every such table has in common.

  • every case: the cheapest pair takes a person and an object that a cheaper whole needs elsewhere: the pairs left to the others cost more than cheapest first saved
  • an example: two people and two objects, with costs 1 and 2 for the first person and 2 and 9 for the second: cheapest first takes the 1, then must take the 9, 10 in all; the assignment takes both 2s, 4

Which idea do you reach for

Exercise 22

Five workers and five jobs. A table gives the hours that each worker needs for each job. Every job needs exactly one worker, and every worker takes exactly one job. The firm wants the fewest hours in all.

Answer: assignment. The workers are the people and the jobs are the objects, and a pair’s cost is its hours. The table is square and every pair is possible, so the assignment answers it, and its labels prove that no other plan takes fewer hours. If the table said only which worker can do which job, and the firm wanted as many jobs done as possible, a matching would answer it instead.

Exercise 23

Workshop seats. A summer school has 60 students and 5 workshops. Each workshop has a number of seats, from 8 to 15, and each student names the workshops they would accept. Each student takes at most one workshop. The school wants as many students placed as possible.

Answer: matching. Give each workshop one copy per seat, and let a student accept every copy of each workshop they would accept. A maximum matching of students with copies places as many students as possible. A maximum flow on the matching network of students and workshops, with each workshop’s arrow to the sink carrying its number of seats as capacity, gives the same answer and is accepted too.

Exercise 24

Project selection: which products to keep, when a product’s benefit needs all of its parts. A firm can make six products. Each product brings a known profit, but only if every tool it needs is bought, and each tool has a price. One tool can serve several products. Which products and tools should the firm choose, to make the most money?

Answer: minimum cut. Draw an arrow from the source to each product, with its profit as capacity, and an arrow from each tool to the sink, with its price. From each product, draw an arrow to every tool it needs, with a capacity larger than all the profits together. A minimum cut never cuts such an arrow, so a product on the source’s side brings its tools with it. The cut pays the profit of every product left out and the price of every tool bought. So the best choice is the source’s side of a minimum cut, and the most money is the total profit less the cut’s capacity.

Exercise 25

Disjoint paths: routes that share no arrow. A data center joins its machines with one-way cables. How many paths from machine A to machine B share no cable, so that one broken cable stops at most one of them?

Answer: maximum flow. Make every cable an arrow of capacity 1, with A as the source and B as the sink. With integer flows, every arrow carries 0 or 1, and the flow splits into paths that share no arrow. So the largest amount is the number of such paths. Its minimum cut is the fewest cables whose loss cuts B off from A, the question of what survives a failure.

Exercise 26

Elimination: whether a team can still finish first. In a league, every game has one winner, who gets one point. There are no draws, and a loss gives no points. Some games are still to be played. Team X has its points so far, and it can win every game it has left. Can X still finish with at least as many points as every other team?

Answer: maximum flow. Let X win all its games, so it ends with W points. Draw an arrow from the source to a vertex for each game left between two other teams, with capacity 1. From that vertex, draw an arrow to each of its two teams, and from each team an arrow to the sink, with W less that team’s points as capacity. A unit through a game is its win. If some team already has more than W points, X is out. Otherwise X can still finish first exactly when the maximum flow fills every arrow out of the source.

Exercise 27

Pumping stations with limits of their own. Water runs from a reservoir to a district through pipes, each with a capacity. Each pumping station on the way can also pass only so much water an hour, whatever its pipes allow. How much water can reach the district?

Answer: maximum flow. Split each station into two vertices, one where its pipes come in and one where its pipes leave. Join them by one arrow whose capacity is the station’s own. Then a station’s limit is an arrow’s capacity, and the maximum flow from the reservoir to the district is the answer.

Exercise 28

The fewest vehicles that cover all trips. A bus company has 30 trips for tomorrow, each with a start time and place and an end time and place. A bus that ends a trip can take another trip if it reaches that trip’s start in time. How few buses cover every trip?

Answer: matching. Make every trip a person and, again, an object. Trip i accepts trip j when one bus can drive j right after i. A matching links trips into chains, and each chain is one bus’s day. Every pair saves one bus, so the fewest buses are the trips less the pairs of a maximum matching.

Exercise 29

Bread for the shops. Three bakeries bake 40, 25 and 35 loaves each morning, and five shops need 20, 15, 30, 10 and 20 loaves. Each road from a bakery to a shop can carry only so many loaves a morning, and each loaf on it costs a known amount to drive. Loaves that no shop needs stay at the bakery. How should the bread go, so that every shop gets what it needs at the least cost? And what does your method give back when the roads cannot carry it all?

Answer: min-cost flow. Draw an arrow from a source to each bakery, with its loaves as capacity and cost 0, an arrow for each road from a bakery to a shop, with the road’s limit as capacity and its cost per loaf, and an arrow from each shop to a sink, with the loaves it needs as capacity and cost 0. Ask the cheapest path rule for 95 units, what the shops need in all. Its heights prove that no plan delivers the 95 loaves for less. If the search misses the sink before 95 units are sent, the vertices it still reaches give a cut whose capacity is the amount sent: the bread that the roads can carry at most, and the roads and shops that hold it back. This is the frontier entry on shipping goods: a source feeds every supply and a sink drains every demand.

Exercise 30

Airline scheduling. An airline must fly 12 given flights tomorrow, each at a fixed time between two airports. A plane can fly one flight and then a later one, if it can reach that flight’s start in time. To get there it may fly empty, through other airports, and a table gives the flying time between every two airports. A plane may also stay on the ground all day. Can 4 planes fly them all?

Answer: matching. First find which flight can follow which. A plane that lands from flight i can take flight j when the fastest empty route from i’s airport to j’s start, a shortest path over the table’s times, lands before j leaves. Then make every flight a person and, again, an object, and let flight i accept flight j when j can follow i. A matching links flights into chains, and each chain is one plane’s day, so the fewest planes are the 12 flights less the pairs of a maximum matching. Four planes fly every flight exactly when that number is at most 4, since a spare plane stays on the ground. Unlike the buses, the pairs come from the shortest empty routes, not from direct drives alone. A flow in which every flight’s arrow must carry one unit gives the same answer and is accepted too.

Exercise 31

Exam scheduling. A school has 8 exams, 4 time slots and 3 rooms. Each exam is supervised by its own teacher, and some teachers have more than one exam. An exam can be held only in the slots when its teacher is free, and each room holds one exam in a slot. Can every exam get a slot and a room? Build the flow network first. Then check it against every requirement in the setting: which one does your network leave out, and how would you change the network to keep it?

Answer: maximum flow. The exams are the people and the slots are the objects, and an exam accepts the slots when its teacher is free. Each slot can take 3 exams, one per room, so its arrow to the sink has capacity 3, as for a host with several beds. Every exam gets a slot exactly when the maximum flow is 8, and any room is then fine, since a slot takes no more exams than rooms. The requirement this network leaves out: one teacher cannot run two exams at once. Nothing stops two exams of one teacher from taking the same slot in two rooms. To keep it, put a vertex for each teacher and slot between that teacher’s exams and the slot: each of the teacher’s exams that may use the slot has an arrow of capacity 1 to it, and it has one arrow of capacity 1 to the slot. Then each teacher has at most one exam in a slot, and every exam gets a slot and a room exactly when the maximum flow is 8. A small case shows the difference: one teacher with two exams, free only in one slot. The first network sends 2, so it places both exams in that slot; the changed network sends 1, and one exam finds no slot.

Exercise 32

The one-way postman. A street sweeper must drive along every one-way street of a district at least once, and come back to its depot. From the depot it can reach every street, and from every street it can get back to the depot. Each street has a driving time. Which streets should it drive again, for the least time in all?

Answer: min-cost flow. A round trip leaves every vertex as often as it enters. So a vertex with more streets in than out must be left more often: it supplies the difference. A vertex with more streets out than in demands the difference. Every street is an arrow with no limit, and its cost is its driving time. Add a source with an arrow to every supplier and a sink with an arrow from every demander, each with that amount as capacity and cost 0. The cheapest flow of the total supply says how often to repeat each street. Then every vertex has as many arrows coming in as going out, and, since every street can be reached from the depot and leads back to it, one round trip drives every street and every repeat.

The tests pass. What did they miss?

Exercise 33

A food bank places volunteer drivers on delivery routes with code that an AI wrote from the Matching design box. Its tests pass: on a thousand random tables, the number of pairs always matches a slow search that tries every set of pairs. One week two drivers are left without a route, and the manager asks why no better placement exists. The program has no answer to give. What requirement did the tests miss?

Answer: The certificate. The tests compared only the number of pairs, which the code got right. The box promises a cover as large as the matching, and a blocked group when someone stays unmatched. The code returned the pairs and dropped the rest, so nobody can check the answer, and the manager gets no reason.

Then: Write the test.

Answer to the follow-up: On every table, the answer holds a cover beside the pairs. The test checks that every acceptable pair is incident to a member of the cover, which has as many members as there are pairs. When someone stays unmatched, it also checks that the blocked group’s people accept fewer routes between them than there are of them.

Exercise 34

A team writes capacity scaling as a path rule for the loop. Its tests pass: on many random flow networks with every capacity 1, the amount always matches a slow search over every cut. On a network with capacities up to 1000, the loop stops below the largest amount. What requirement did the tests miss?

Answer: The third promise: a round may report that no augmenting path is left only when none is left. With every capacity 1, every threshold is 1, so nothing in the way the threshold falls is ever exercised, and no test of that kind could see a round that gives up too early. Grade the requirement and the test; the stem does not show the code, so an answer need not guess the exact defect.

Then: Write the test.

Answer to the follow-up: Flow networks whose capacities differ, with the largest well above 1. On each, the test checks the answer’s cut: its capacity must equal the amount, and the residual capacity must not reach the sink. A small one that catches a round giving up early: s \to t 8, s \to a 1 and a \to t 1, from s to t. The amount must be 9; a round that stops when the first threshold, 8, has no path left returns 8, with the path through a still open.

Fix the code, the box, or the design?

Exercise 35

A clinic gives four night shifts to four nurses, Ana, Ben, Chen and Dita. Each nurse rates each shift by how hard it is for them, from 1 to 10: Ana’s ratings for shift 1, shift 2, shift 3 and shift 4 are 8, 1, 4 and 5; Ben’s ratings for shift 1, shift 2, shift 3 and shift 4 are 5, 10, 1 and 1; Chen’s ratings for shift 1, shift 2, shift 3 and shift 4 are 10, 6, 9 and 5; Dita’s ratings for shift 1, shift 2, shift 3 and shift 4 are 7, 8, 9 and 1. Code that an AI wrote from the Assignment design box returns the cheapest assignment, 13 in all, with labels that pass the label check. In it, Chen gets the shift rated 10, and the nurses reject the plan. They say that what matters to them first is the hardest shift that any one of them gets, and only then the total. Another plan gives no one a shift rated above 6, at 16 in all. Which of the three is it, and why?

Answer: change the design. The code keeps its box: the labels prove that no assignment costs less than 13. The box asks for the least total, and the nurses want the hardest shift as easy as possible first. That objective is not a total, so no fix to the code makes the least total fair. Also accepted, as a fix to the box: a clearly stated cap, no nurse gets a shift rated above a stated limit, with the least total among the plans under it. The box’s assignment then needs the pairs above the cap forbidden: give each a cost that no plan of allowed pairs reaches, here 41, above 4 times the largest rating, or check with a matching on the allowed pairs that everyone fits. A cap left unstated, or a forbidden pair kept at its rating, is not accepted.

Then: Name a design that fits, and say what it costs.

Answer to the follow-up: Ask for the least worst shift first. Try each limit in turn, from the smallest rating up. Forbid every pair rated above it, with the cost 41, and run the assignment; the limit fits when the cheapest plan costs less than 41. The smallest limit that fits is 6 here, and its cheapest plan costs 16. It costs one assignment per limit tried; a matching per limit to find the limit, and one assignment at the end, does the same.

Fill in the contract

Exercise 36

A conference has 300 papers and 120 reviewers. Each paper needs 3 reviewers, and each reviewer takes at most 8 papers. Every pair of a reviewer and a paper has a score for how well the reviewer knows the topic, and a reviewer may not review a paper from their own institution. Work out the parts of a contract for this workload, in the order that the contracts chapter uses.

Answer, one line per question. Grade on the parts kept apart, not on the wording:

  1. Goal: give every paper 3 different reviewers, no reviewer more than 8 papers and no paper from their own institution, with the largest total score, and show that no such plan scores more.
  2. Floor: every allowed pair must be read once, since any score could change the best plan: up to 36,000 pairs. The plan itself has 900 placements.
  3. Promise and invariants: a plan that keeps every count and every conflict, and beside it the evidence that no plan scores more. If no plan keeps the counts, the most placements possible and a cut that proves it, such as papers whose allowed reviewers have too few seats between them. What must remain true: the flow on every arrow is an integer, so each placement is a whole reviewer.
  4. Idea: min-cost flow. The source has an arrow of capacity 8 to every reviewer, every allowed pair is an arrow of capacity 1, and every paper has an arrow of capacity 3 to the sink. Capacity 1 on each pair keeps a reviewer from taking the same paper twice, which copies of a paper alone would allow. A pair’s cost is the largest score less its own score, so no cost is below zero. Ask for 900 units.
  5. Cost: one cheapest-path search per step, each over the 36,000 arrows, and at most 900 steps, one per unit.
  6. Assumes: the scores add up, so the best plan is the one with the largest total; the caps and the conflicts are known before the run.

Then: Suppose that all allowed pairs have one common score, the same for every reviewer and every paper. What does your contract then promise, and which part tells you?

Answer to the follow-up: Every plan that keeps the counts then has the same total score, so the promise is only a plan that keeps the counts and the conflicts. The Goal tells you: its total adds nothing, and the task is a flow with capacities, the hosts with several beds, with no costs.

Derive it

Exercise 37

Derive the method, and say why it is right. Then run it on the flow network with the source s, the sink t and these capacities: s \to a 1, s \to b 5, a \to b 2, a \to c 1, b \to d 1, c \to b 4, c \to d 4, c \to t 1 and d \to t 2. For which arrows does widening by one unit raise the maximum flow?

  • method: Find a maximum flow. Search the residual capacity from the source, and search it backward from the sink. An arrow helps exactly when it is full, its start is reached from the source and its end reaches the sink. Widening such an arrow by one gives it room, and the room joins the two searches into an augmenting path. If its start is not reached, the last search’s cut leaves it out and keeps its capacity. If its end does not reach the sink, the cut of the vertices that cannot reach the sink leaves it out. Either way a minimum cut stays, and so does the maximum flow
  • maximum flow: 2
  • arrows that help: b→d 1

Stretch: List every minimum cut of this network, each by the vertices on the source’s side.

Answer to the follow-up: {s, b}; {s, a, b}

Exercise 38

Enough runs of Karger. This one is for after The cut without a source. One run of Karger’s contraction finds a given global minimum cut with probability at least 2/(n(n-1)), where n is the number of vertices. How many independent runs make the chance of missing it smaller than one in a hundred? Why does the answer still carry no certificate?

  • runs: with p = 2/(n(n−1)), k runs all miss with chance at most (1 − p)^k, which is at most e^(−pk). That is below 1/100 once k ≥ ln(100)/p = ln(100) n(n−1)/2, about 2.3 n(n−1) runs
  • examples: n = 6: 67 runs, and the bound gives 70; n = 10: 205 runs, and the bound gives 208; n = 100: 22794 runs, and the bound gives 22796
  • no certificate: a run returns a cut and nothing that bounds every other cut. A smaller cut that no run met leaves no trace, so many runs raise the confidence but never prove the cut smallest. One maximum flow between two vertices proves only the smallest cut that separates those two. A global certificate needs more pairs: fix one vertex, and find a maximum flow from it to each of the other n − 1 vertices. Every cut separates the fixed vertex from some other one, so the smallest of those flows, with its cut, proves the global minimum