University Computer Science — Year 1 · Bachelor Year 1
23Dynamic Programming
Type catlaogue into a search box and it offers catalogue. To do that, the program needs a measure of how far one word is from another: the fewest letters to insert, delete or change. Trying every sequence of edits is hopeless, yet the answer comes in a table of a few hundred cells, filled in a fraction of a millisecond. The table is the method of this chapter: when a problem’s optimal solutions are made of optimal solutions of smaller problems, and the same smaller problems come back again and again, solve each one once and write the answer down.
You already know
Recurrences and their costs were studied in Chapter 13; divide and conquer (Definition 21.1) cuts a problem into independent subproblems. The second book computed Fibonacci numbers and a longest common subsequence with a table.
23.1 Optimal substructure and overlapping subproblems
Definition 23.1 (Dynamic programming, optimal substructure, overlapping subproblems)
A problem has optimal substructure when an optimal solution of an instance is made of optimal solutions of smaller instances, its subproblems. It has overlapping subproblems when a recursive solution meets the same subproblems many times. Dynamic programming solves such a problem by computing the answer of each subproblem once, from the answers of smaller ones, and storing it.
Optimal substructure is proved by cut and paste: if the part of an optimal solution that solves a subproblem were not optimal for it, cutting it out and pasting in a better one would improve the whole, a contradiction. Divide and conquer has optimal substructure too, but its subproblems do not overlap; the Fibonacci recursion shows what overlap costs.
Definition 23.2 (Memoisation, bottom-up evaluation)
Memoisation keeps the recursive program and stores each result in a table, the memo, read before computing. Bottom-up evaluation fills the table in an order where every entry is computed after the entries it needs, without recursion.
def fib_naive(n):
global calls
calls += 1
return n if n < 2 else fib_naive(n - 1) + fib_naive(n - 2)
def fib_memo(n, memo=None):
global calls
calls += 1
if memo is None:
memo = {}
if n < 2:
return n
if n not in memo: # each subproblem is solved once, then read from the table
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
def fib_table(n):
"""Bottom-up: the table filled in increasing order, two cells kept."""
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
$ python fib_memo.py
n F(n) naive calls memoised calls
5 5 15 9
10 55 177 19
15 610 1973 29
20 6765 21891 39
25 75025 242785 49
The naive recursion makes calls, exponential in ; the memoised one , since each value is computed once and read once more. The bottom-up version needs neither the calls nor the table, only the last two values. The name of the method goes back to Bellman’s book Dynamic Programming of 1957, where “programming” means planning, as in a programme of events.
23.2 The recurrence first, the table second
Method 23.3 (Designing a dynamic programme)
- Choose the subproblems, usually prefixes, intervals or prefixes with a budget, and give each a name with indices.
- Write the recurrence that gives a subproblem’s answer from smaller ones, and prove it, by cut and paste.
- Fix an order of evaluation in which every entry comes after those it reads.
- Read the answer in the table.
- Rebuild a solution, not just its value, by walking back through the choices that gave each entry.
Definition 23.4 (Edit distance, alignment)
The edit distance of two words is the smallest number of single-letter insertions, deletions and substitutions that turn into . An alignment of and writes them one above the other with gaps (written -), so that no column holds two gaps; its cost is the number of columns whose two entries differ.
An alignment is a sequence of edits read column by column: a letter over a gap is a deletion, a gap over a letter an insertion, two different letters a substitution. So is the smallest cost of an alignment (Exercise 23.9).
Proposition 23.5 (The edit-distance recurrence)
Let be the edit distance of the prefixes and . Then , , and for
where is 1 if holds and 0 otherwise.
Proof. An alignment of with the empty word has columns, each a letter over a gap; likewise for . Otherwise, the last column of an optimal alignment is over a gap, a gap over , or over . Removing it leaves an alignment of with , of with , or of with , and that alignment is optimal for its prefixes: a cheaper one, with the last column put back, would beat the optimal alignment (cut and paste). So is one of the three expressions, and it is at most each of them, since each is the cost of some alignment. ∎
def table(a, b):
"""d[i][j]: the edit distance of a[:i] and b[:j]."""
d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(len(a) + 1):
d[i][0] = i # delete the i letters
for j in range(len(b) + 1):
d[0][j] = j # insert the j letters
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
d[i][j] = min(d[i - 1][j] + 1, # delete a[i-1]
d[i][j - 1] + 1, # insert b[j-1]
d[i - 1][j - 1] + (a[i - 1] != b[j - 1])) # keep or change
return d
def alignment(a, b, d):
"""Walk back from the corner, following a choice that gives each cell its value."""
i, j, top, bottom = len(a), len(b), [], []
while i > 0 or j > 0:
if i > 0 and j > 0 and d[i][j] == d[i - 1][j - 1] + (a[i - 1] != b[j - 1]):
top.append(a[i - 1])
bottom.append(b[j - 1])
i, j = i - 1, j - 1
elif i > 0 and d[i][j] == d[i - 1][j] + 1:
top.append(a[i - 1])
bottom.append("-")
i -= 1
else:
top.append("-")
bottom.append(b[j - 1])
j -= 1
return "".join(reversed(top)), "".join(reversed(bottom))
$ python edit_distance.py
r a i n s
0 1 2 3 4 5
t 1 1 2 3 4 5
r 2 1 2 3 4 5
a 3 2 1 2 3 4
i 4 3 2 1 2 3
n 5 4 3 2 1 2
train -> rains: distance 2
train-
-rains
* *
catlaogue -> catalogue: distance 2
catlaogue
catalogue
**
train and rains, and two alignments; stars mark the edited columns.train- over -rains.The table has cells, each computed in constant time: . The walk back takes at most steps. Where several neighbours give a cell its value, the program prefers the diagonal; another preference may give another alignment of the same cost.
Definition 23.6 (Longest common subsequence)
A longest common subsequence of two words is a word of largest length that can be obtained from each by deleting letters.
With insertions and deletions only, an alignment keeps exactly the letters of a common subsequence, and the distance is , with the length of a longest common subsequence (Exercise 23.12): the table of the second book is the same method with another recurrence. The distance with substitutions was introduced by Levenshtein in 1965, for codes that correct lost and added bits.
23.3 Matrix-chain order
Definition 23.7 (Matrix-chain problem)
Multiplying a matrix by a matrix takes products of numbers. The matrix-chain problem asks, for matrices of sizes , for the order of the products that computes with the fewest products of numbers.
The product is the same in every order, by associativity; the cost is not. Trying every order is out of the question: their number is a Catalan number, which grows like .
$ python catalan.py
2 matrices: 1 orders; Catalan C(1) = 1
3 matrices: 2 orders; Catalan C(2) = 2
5 matrices: 14 orders; Catalan C(4) = 14
10 matrices: 4862 orders; Catalan C(9) = 4862
20 matrices: 1767263190 orders; Catalan C(19) = 1767263190
Let be the cheapest cost of . The last product splits the chain at some , , and both parts must be computed optimally (cut and paste), so
An entry reads entries for shorter chains: the table is filled by increasing length. There are entries, each a minimum over at most splits: in all.
def chain_order(dims):
"""Matrix i is dims[i] x dims[i+1]. Returns (cost table, split table)."""
n = len(dims) - 1
cost = [[0] * n for _ in range(n)]
split = [[0] * n for _ in range(n)]
for length in range(2, n + 1): # by diagonals: shorter chains first
for i in range(n - length + 1):
j = i + length - 1
cost[i][j] = None
for k in range(i, j): # (A_i ... A_k)(A_k+1 ... A_j)
c = cost[i][k] + cost[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1]
if cost[i][j] is None or c < cost[i][j]:
cost[i][j], split[i][j] = c, k
return cost, split
def parenthesise(split, i, j):
if i == j:
return f"A{i + 1}"
k = split[i][j]
return f"({parenthesise(split, i, k)} {parenthesise(split, k + 1, j)})"
$ python chain.py
cost table (row i, column j: A_i ... A_j)
0 4000 3000 6500 3800
0 2000 3500 3400
0 12000 2800
0 1200
0
best order: (A1 ((A2 A3) (A4 A5))) with 3800 products
left to right: 20400 products
The program numbers matrices from 0: its dims[i] is , and its matrix is the book’s . The best order costs 3800 products, the left-to-right order 20 400: the order matters by a factor of five on five matrices.
23.4 Knapsack and longest increasing subsequence
Definition 23.8 (0/1 knapsack, pseudo-polynomial algorithm)
The 0/1 knapsack problem asks, for items of integer weights and values and a capacity , for a set of items of total weight at most and largest total value. An algorithm is pseudo-polynomial if its cost is polynomial in the numbers of the input, but not in the number of digits needed to write them.
Let be the best value of the first items within capacity . Item is left out, or, if it fits, taken with the best of the first items in the remaining capacity:
def knapsack(items, capacity):
"""best[i][c]: the best value of the first i items within capacity c."""
best = [[0] * (capacity + 1) for _ in range(len(items) + 1)]
for i, (w, v) in enumerate(items, start=1):
for c in range(capacity + 1):
best[i][c] = best[i - 1][c] # without item i
if w <= c:
best[i][c] = max(best[i][c], best[i - 1][c - w] + v) # with it
return best
def chosen(items, best, capacity):
"""Walk back: item i was taken where the value changed from row i - 1."""
take, c = [], capacity
for i in range(len(items), 0, -1):
if best[i][c] != best[i - 1][c]:
take.append(i - 1)
c -= items[i - 1][0]
return sorted(take)
$ python knapsack.py
capacity: 0 1 2 3 4 5 6 7 8
none 0 0 0 0 0 0 0 0 0
+(3, 25) 0 0 0 25 25 25 25 25 25
+(4, 40) 0 0 0 25 40 40 40 65 65
+(2, 15) 0 0 15 25 40 40 55 65 65
+(5, 50) 0 0 15 25 40 50 55 65 75
+(1, 8) 0 8 15 25 40 50 58 65 75
take items [0, 3] value 75
40 random items, capacity 737: best 1406, 30258 cells
The cost is . That looks polynomial, but is written with about bits: doubling the number of bits of the capacity squares the work. With 40 items the table has 30 258 cells where the tree of Chapter 20 has leaves; with capacities of a hundred billion it would be the tree’s turn. Counting subsets with a given total is the same table with sums of counts instead of maxima of values: the reading lists of Chapters 20 and 21, now for all 80 books.
def count(values, target):
"""ways[t]: the number of subsets of the values seen so far with total t."""
ways = [1] + [0] * target
for v in values:
for t in range(target, v - 1, -1): # downwards: each value used at most once
ways[t] += ways[t - v]
return ways[target]
$ python subset_sum_dp.py
first 16 books: 9 lists of 1000 pages, 16016 cell updates at most
first 24 books: 31 lists of 1000 pages, 24024 cell updates at most
first 40 books: 459 lists of 1000 pages, 40040 cell updates at most
first 80 books: 165521 lists of 1000 pages, 80080 cell updates at most
The loop over totals goes downwards so that ways[t - v] still counts the subsets without ; Exercise 23.5 shows what going upwards does.
Definition 23.9 (Longest increasing subsequence)
A longest increasing subsequence of a sequence is a subsequence, its terms taken in their order but not necessarily adjacent, that is strictly increasing and of largest length.
With the length of the longest increasing subsequence ending at term , (the maximum of an empty set being 0): . A different invariant gives .
def lis_table(a):
"""length[i]: the longest strictly increasing subsequence ending at a[i]."""
length, before = [1] * len(a), [None] * len(a)
for i in range(len(a)):
for j in range(i):
if a[j] < a[i] and length[j] + 1 > length[i]:
length[i], before[i] = length[j] + 1, j
if not a:
return []
i = max(range(len(a)), key=lambda k: length[k])
out = []
while i is not None: # rebuild by following the predecessors
out.append(a[i])
i = before[i]
return out[::-1]
def lis_patience(a):
"""The length: tops[k] is the smallest last key of an increasing subsequence of
length k + 1 seen so far; each key goes on the leftmost pile whose top is >= it."""
tops = []
for x in a:
k = bisect_left(tops, x)
if k == len(tops):
tops.append(x) # a new pile on the right
else:
tops[k] = x
return len(tops)
Proposition 23.10 (Patience piles)
After reading the first terms of , tops[k] is the smallest last term of an increasing subsequence of length among them, and tops is increasing. So its length at the end is the length of a longest increasing subsequence.
Proof. True before any term. Suppose it holds and the term is read. Every increasing subsequence ending at extends one whose last term is less than ; the longest such has length , where is the number of tops less than , which bisect_left returns. So ends an increasing subsequence of length and no longer one. If is the length of tops, is larger than all tops and is appended: a new, longer subsequence. Otherwise and replaces it, the new smallest last term for length ; the other entries do not change, since ends no subsequence of another length that would improve them. In both cases tops stays increasing, as . ∎
$ python lis.py
[5, 2, 8, 6, 3, 6, 9, 7, 4, 10] -> [2, 3, 6, 9, 10] length 5
years of the 80 books in catalogue order: longest increasing subsequence 15, patience 15
[1950, 1957, 1961, 1966, 1973, 1980, 1993, 1994, 1995, 1999, 2001, 2003, 2009, 2016, 2022]
23.5 Saving space
A row of the edit-distance table reads only the row above it: two rows suffice for the distance.
def distance(a, b):
previous = list(range(len(b) + 1)) # row 0 of the table
for i in range(1, len(a) + 1):
current = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
current[j] = min(previous[j] + 1, current[j - 1] + 1,
previous[j - 1] + (a[i - 1] != b[j - 1]))
previous = current # row i - 1 is no longer needed
return previous[-1]
$ python edit_two_rows.py
distance 7 (full table: 7)
cells kept: full table 1258, two rows 68
The price is the alignment: the walk back needs the whole table. Hirschberg showed in 1975 how to recover it in linear space anyway, by divide and conquer: compute the middle row of the table from the top with two rows, the same from the bottom on the reversed words, find where an optimal alignment crosses the middle row, and recurse on the two halves. The time stays , about twice as much.
23.6 Exercises
Exercise 23.1 ★
Fill the edit-distance table of loan and lane, and give an optimal alignment.
Solution
Solution of Exercise 23.1.
Rows for the prefixes of loan, columns for those of lane:
| l | a | n | e | ||
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | |
| l | 1 | 0 | 1 | 2 | 3 |
| o | 2 | 1 | 1 | 2 | 3 |
| a | 3 | 2 | 1 | 2 | 3 |
| n | 4 | 3 | 2 | 1 | 2 |
The distance is 2: loan- over l-ane, deleting o and inserting e.
Exercise 23.2 ★
How many calls do fib_naive(6) and fib_memo(6) make?
Solution
Solution of Exercise 23.2.
fib_naive(6) makes calls, fib_memo(6) makes : one call for each from 6 down to 2 that computes, plus one call for each value read back or below 2.
Exercise 23.3 ★
Add a sixth item of weight 3 and value 30 to the knapsack of Output 23.5: compute the new row, and the items taken.
Solution
Solution of Exercise 23.3.
From the last row , the new entry for capacity is the larger of the old one and 30 plus the old one at : . The best value is 80, with the items of weights 5 and 3 (values 50 and 30).
Exercise 23.4 ★
Find the length of a longest increasing subsequence of with the piles, and one such subsequence.
Solution
Solution of Exercise 23.4.
Tops after each term: ; ; ; ; ; ; ; ; ; ; . Four piles: length 4, for instance or .
Exercise 23.5 ★★
The one-row knapsack below goes through the capacities upwards or downwards. Explain the two results.
def one_row(items, capacity, downwards):
best = [0] * (capacity + 1)
for w, v in items:
order = range(capacity, w - 1, -1) if downwards else range(w, capacity + 1)
for c in order:
best[c] = max(best[c], best[c - w] + v)
return best[capacity]
downwards: 65 upwards: 80
Solution
Solution of Exercise 23.5.
Downwards, best[c - w] has not yet been updated for the current item: it is the best value without it, and each item is used at most once, which gives 65. Upwards, best[c - w] may already contain the current item, which is then taken again: 80 is twice the item . That is the right method for a knapsack with unlimited copies of each item, the wrong one here.
Exercise 23.6 ★★
This memo is keyed on the identity of the list of values, which the recursion shortens and restores. Explain the wrong counts and repair the key.
def ways(values, target):
"""Subsets of values with the given total; values is shortened and restored."""
key = (id(values), target)
if key in memo:
return memo[key]
if not values:
result = int(target == 0)
else:
v = values.pop() # decide the last value, then put it back
result = ways(values, target) + ways(values, target - v)
values.append(v)
memo[key] = result
return result
total 10: memoised 2, all 32 subsets 2
total 13: memoised 0, all 32 subsets 2
total 17: memoised 0, all 32 subsets 2
Solution
Solution of Exercise 23.6.
The recursion always passes the same list object, shortened, so id(values) is the same at every depth: the result for a prefix of three values is stored under the same key as the result for five, and read back in place of it. For the total 10 the confusion happens to give the right count; for 13 and 17 it does not. The subproblem is a prefix and a total, so the key should say which prefix: (len(values), target), or (tuple(values), target), which costs a copy.
Exercise 23.7 ★★
Talks now have weights. Find a set of compatible talks of largest total weight in ; the greedy rule of Theorem 22.4 no longer works.
Solution
Solution of Exercise 23.7.
def best_weight(talks):
"""talks: (start, end, weight). best[i]: the best of the first i talks by end."""
talks = sorted(talks, key=lambda t: t[1])
ends = [t[1] for t in talks]
best = [0] * (len(talks) + 1)
for i, (s, _, w) in enumerate(talks, start=1):
p = bisect_right(ends, s, 0, i - 1) # talks ending at or before s
best[i] = max(best[i - 1], best[p] + w) # without talk i, or with it
return best[-1]
Sort the talks by finishing time; let be the best weight using the first , and the number of talks among the first that finish by the start of talk . An optimal set either leaves talk out, or takes it together with an optimal set of the talks compatible with it: . Sorting and the binary searches cost . A heavy talk overlapping two light compatible ones defeats the earliest-finish rule.
Exercise 23.8 ★★
In how many ways can one climb stairs with steps of sizes taken from a given set, the order of the steps counting?
Solution
Solution of Exercise 23.8.
def climbs(n, steps):
ways = [1] + [0] * n # ways[k]: ordered sequences of steps summing to k
for k in range(1, n + 1):
ways[k] = sum(ways[k - s] for s in steps if s <= k)
return ways[n]
The last step of a climb to has some size , and before it comes any climb to : with , in . With steps 1 and 2, is the Fibonacci number : 89 for .
Exercise 23.9 ★★
Show that the edit distance equals the smallest cost of an alignment.
Solution
Solution of Exercise 23.9.
An alignment of cost is read as edits, column by column, so is at most the smallest cost. Conversely, take edits turning into . Edits never reorder letters: the letters of that survive, perhaps changed, end at positions of in the same order. Write each over its final letter, the deleted letters of over gaps and the other letters of under gaps. A column of two different letters needs at least one substitution of that letter, a column with a gap at least one deletion or insertion, all different edits: the alignment costs at most .
Exercise 23.10 ★★★
Show another way that the number of patience piles is the length of a longest increasing subsequence: each pile never increases from bottom to top, and each key placed on pile has a smaller key on pile placed before it.
Solution
Solution of Exercise 23.10.
A key goes on a pile only if its top is not smaller, so each pile never increases from bottom to top; the keys of one pile came in that order, so an increasing subsequence takes at most one key from each pile, and its length is at most the number of piles. When a key goes on pile , the top of pile is less than and came before it; remember . From any key on the last pile, following these remembered keys back to pile 0 gives keys that increase and come in order, one per pile: an increasing subsequence as long as the number of piles.
Exercise 23.11 ★★★
Compute the length of a longest subsequence of a word that is a palindrome, in , and test it.
Solution
Solution of Exercise 23.11.
def longest_palindrome(s):
n = len(s)
if n == 0:
return 0
best = [[0] * n for _ in range(n)] # best[i][j]: for s[i..j]
for i in range(n - 1, -1, -1):
best[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
best[i][j] = best[i + 1][j - 1] + 2 if j > i + 1 else 2
else:
best[i][j] = max(best[i + 1][j], best[i][j - 1])
return best[0][n - 1]
For : if the end letters are equal, a best palindrome may use both around a best one of ; otherwise it does without one of them. Cells are filled for decreasing and increasing, so each reads cells already computed: . The test compares with all subsequences of random words of up to 10 letters.
Exercise 23.12 ★★★
With insertions and deletions only, show that the distance of and is , where , are their lengths and the length of a longest common subsequence.
Solution
Solution of Exercise 23.12.
Without substitutions, every column of an alignment of finite cost holds two equal letters, or a letter and a gap. The columns of equal letters spell a common subsequence of some length ; the other letters of and of face gaps. So the cost is , smallest when is the length of a longest common subsequence, and by Exercise 23.9 the distance is .
23.7 Problem: A spelling checker for the catalogue
Problem 23.1
Weekend problem — A spelling checker for the catalogue
Eight misspelt queries are matched against the 80 titles of the catalogue, in lower case. The program computes edit distances with two rows, and avoids most of them with the triangle inequality: four titles serve as pivots, whose distances to every title are computed once.
def nearest_pruned(query, books, pivots, to_pivot):
"""to_pivot[t][k] = distance(t, pivots[k]), computed once for the catalogue.
By the triangle inequality, |d(q, p) - d(p, t)| <= d(q, t) for every pivot p."""
computed = len(pivots)
dq = [distance(query, p) for p in pivots]
bound = {t: max(abs(x - y) for x, y in zip(dq, to_pivot[t])) for t in books}
best = (float("inf"), None)
for t in sorted(books, key=lambda t: bound[t]): # most promising first
if bound[t] >= best[0]:
break # every remaining title is at least as far as the best found
best = min(best, (distance(query, t), t))
computed += 1
return best, computed
$ python spell.py
'the clokwork harbor' -> 'the clockwork harbour' distance 2, 5 distances computed
'a map of the lighthose' -> 'a map of the lighthouse' distance 1, 5 distances computed
'notes on the libary' -> 'notes on the library' distance 1, 5 distances computed
'the silent comit' -> 'the silent comet' distance 1, 5 distances computed
'beyond the rivr' -> 'beyond the river' distance 1, 7 distances computed
'under the gardn' -> 'under the garden' distance 1, 5 distances computed
'seven machnie' -> 'seven machine' distance 2, 6 distances computed
'the hiden kingdom' -> 'the hidden kingdom' distance 1, 7 distances computed
pruned: 45 distances for 8 queries; brute force: 640
Part I — The recurrence and its table.
- Why is the distance of
the silent comitandthe silent cometequal to 1? - How many cells has the table of a query of 19 characters against a title of 21?
- In which order are the cells filled, and why is every cell read after it is computed?
- What is the cost of one distance computation for words of lengths and ?
- How many distances does a brute-force search compute per query?
- Why is ?
Part II — Alignments.
- Give an optimal alignment of
the clokwork harborwiththe clockwork harbour. - Give two optimal alignments of
catlaogueandcatalogue. - Why does the walk back always find a neighbour that gives the cell its value?
- What is the cost of the walk back?
- Why does the two-row version lose the alignment?
- Describe how the alignment can still be found in linear space.
Part III — Time and space.
- Read the cells kept by the full table and by two rows in Output 23.8.
- How many cells does each version keep for two words of 1000 letters?
- Does saving space change the time?
- How many distances are computed once, for the pivots?
- How many distances do the eight queries compute, against brute force?
- From how many queries on does the computation for the pivots pay off, at this rate?
Part IV — A metric, and pruning.
- Show that exactly when .
- Show that .
- Prove the triangle inequality .
- Deduce that for any query , pivot and title .
- Why can the loop stop at the first title whose bound is at least the best distance found?
- State the named result, edit distance is a metric, with the saving it brings on the catalogue.
Solution
Solution of Problem 23.1.
1. One substitution, i into e, turns one into the other, and the words differ, so the distance is not 0.
2. .
3. Row by row, each from left to right: a cell reads its left, upper and upper-left neighbours, all filled before it.
4. , a constant amount of work per cell.
5. 80, one per title.
6. Turning letters into none takes deletions, and no operation removes more than one letter.
7. the clo-kwork harbo-r over the clockwork harbour: two insertions.
8. catlaogue over catalogue (two substitutions), and cat-laogue over catal-ogue (an insertion and a deletion).
9. A cell’s value is the smallest of three expressions, so it equals at least one of them.
10. : each step lowers by at least 1.
11. The walk back reads cells of every row, and only the last two rows are kept.
12. Compute the middle row from the top and the same row from the bottom, on the reversed words, each with two rows; the column where their sum is smallest is where an optimal alignment crosses the middle; recurse on the two halves (Hirschberg’s method).
13. 1258 cells against 68.
14. against .
15. No: both versions compute every cell once, .
16. .
17. 45 against 640.
18. A query saves about distances, so the 320 pay off from the fifth query on.
19. No edit is needed exactly when the words are equal.
20. Each edit can be undone by one edit, an insertion by a deletion and a substitution by a substitution: the reversed sequence turns into in as many steps.
21. Following edits from to , then edits from to , turns into ; the smallest number of edits is at most that.
22. gives , and gives ; for several pivots, the largest of these bounds.
23. The titles come by increasing bound, and each bound is at most the true distance: once a bound reaches the best distance found, every remaining title is at least that far. (A title at an equal distance may be skipped: the program returns one nearest title.)
24. Edit distance is a metric: it is zero exactly on equal words, symmetric, and satisfies the triangle inequality (questions 19–21). On the catalogue, the bound it gives lets the eight queries compute 45 distances instead of 640, after 320 computed once for the pivots.