Sub topic 7
Recovering the Edit Script with Traceback
The previous chapter filled the dynamic programming table and read the distance from its bottom-right cell. A number like "3" tells you how far apart kitten and sitting are. It does not tell you which edits to make. Spell checkers that highlight changed letters, diff tools, and sequence aligners all need the edits themselves. This chapter shows how to recover them by walking back through the table you already built.
This chapter assumes you can read Python and have worked through the table-filling chapter. You should know that dp[i][j] is the distance between the first i characters of a and the first j characters of b.
What the Table Remembers
Each cell was computed as the minimum of three candidates:
| Move into `(i, j)` from | Meaning | Cost added |
|---|---|---|
| `(i-1, j-1)` | keep `a[i-1]` if it equals `b[j-1]`, otherwise substitute | 0 or 1 |
| `(i-1, j)` | delete `a[i-1]` | 1 |
| `(i, j-1)` | insert `b[j-1]` | 1 |
The table stores only the winning value, not which candidate won. You can still work that out afterwards. A neighbor "produced" the current cell if the neighbor's value plus the move's cost equals the current value. Starting at (m, n), you repeatedly step to such a neighbor until you reach (0, 0). The moves you collect, read in reverse, form an optimal edit script: a list of operations that turns a into b at minimum cost.
At least one valid predecessor always exists, because the cell's value came from one of them. The border cells are covered too. In row 0 only insertions are possible, and dp[0][j] = dp[0][j-1] + 1 holds. In column 0 only deletions are possible, and dp[i][0] = dp[i-1][0] + 1 holds.
The Reference Implementation
This version builds the table and then walks back with a fixed preference: diagonal first, then deletion, then insertion.
def edit_script(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)
ops = []
i, j = m, n
while i > 0 or j > 0:
if i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + (a[i - 1] != b[j - 1]):
op = "keep" if a[i - 1] == b[j - 1] else "sub"
ops.append((op, a[i - 1], b[j - 1]))
i, j = i - 1, j - 1
elif i > 0 and dp[i][j] == dp[i - 1][j] + 1:
ops.append(("del", a[i - 1], ""))
i -= 1
else:
ops.append(("ins", "", b[j - 1]))
j -= 1
ops.reverse()
return dp[m][n], ops
distance, ops = edit_script("kitten", "sitting")
assert distance == 3
for op in ops:
print(op)Running it prints:
('sub', 'k', 's')
('keep', 'i', 'i')
('keep', 't', 't')
('keep', 't', 't')
('sub', 'e', 'i')
('keep', 'n', 'n')
('ins', '', 'g')The else branch never checks its condition. That is safe because if neither the diagonal nor the upward move fits, the leftward move must. The guards i > 0 and j > 0 stop the walk from leaving the table along the borders.
Tracing `kitten` to `sitting` by Hand
Here is the full table, with rows for kitten and columns for sitting:
| Row | ε | s | i | t | t | i | n | g |
|---|---|---|---|---|---|---|---|---|
| ε | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| k | 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| i | 2 | 2 | 1 | 2 | 3 | 4 | 5 | 6 |
| t | 3 | 3 | 2 | 1 | 2 | 3 | 4 | 5 |
| t | 4 | 4 | 3 | 2 | 1 | 2 | 3 | 4 |
| e | 5 | 5 | 4 | 3 | 2 | 2 | 3 | 4 |
| n | 6 | 6 | 5 | 4 | 3 | 3 | 2 | 3 |
- At
(6, 7)the value is 3. Diagonal:n ≠ g, so the candidate is 3 + 1 = 4, which does not fit. Up: 4 + 1 = 5, which does not fit. Left: 2 + 1 = 3, which fits. Record an insertion ofg. - At
(6, 6)the value is 2. Sincen = n, the diagonal candidate is 2 + 0 = 2, which fits. Record keep. - At
(5, 5)the value is 2. Sincee ≠ i, the diagonal candidate is 1 + 1 = 2, which fits. Record a substitution. - Cells
(4, 4),(3, 3)and(2, 2)are matches along the diagonal. Record keep three times. - At
(1, 1),k ≠ sand the diagonal candidate is 0 + 1 = 1. Record a substitution and arrive at(0, 0).
Displaying the Result as an Alignment
An edit script is often easier to read as a three-line alignment, with a gap character standing in for the missing side of an insertion or deletion.
def render(ops):
top = "".join(x or "-" for _, x, _ in ops)
bottom = "".join(y or "-" for _, _, y in ops)
marks = "".join("|" if op == "keep" else " " for op, _, _ in ops)
return f"{top}\n{marks}\n{bottom}"
ops = [("sub", "k", "s"), ("keep", "i", "i"), ("keep", "t", "t"),
("keep", "t", "t"), ("sub", "e", "i"), ("keep", "n", "n"),
("ins", "", "g")]
print(render(ops))kitten-
||| |
sittingTies: Many Optimal Scripts
Several neighbors can fit at the same cell. Each choice leads to a different script with the same total cost. The order in which you test the moves is your tie-breaking policy, and it decides which optimal script you get. This version makes the order a parameter and checks its own output:
def build_table(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)
return dp
def traceback(a, b, dp, order=("diag", "del", "ins")):
ops = []
i, j = len(a), len(b)
while i > 0 or j > 0:
for move in order:
if move == "diag" and i > 0 and j > 0 and \
dp[i][j] == dp[i - 1][j - 1] + (a[i - 1] != b[j - 1]):
ops.append(("keep" if a[i - 1] == b[j - 1] else "sub", a[i - 1], b[j - 1]))
i, j = i - 1, j - 1
break
if move == "del" and i > 0 and dp[i][j] == dp[i - 1][j] + 1:
ops.append(("del", a[i - 1], ""))
i -= 1
break
if move == "ins" and j > 0 and dp[i][j] == dp[i][j - 1] + 1:
ops.append(("ins", "", b[j - 1]))
j -= 1
break
else:
raise AssertionError("no valid predecessor; table is inconsistent")
ops.reverse()
return ops
def check(a, b, ops, distance):
assert "".join(x for _, x, _ in ops) == a
assert "".join(y for _, _, y in ops) == b
assert sum(op != "keep" for op, _, _ in ops) == distance
a, b = "ab", "ba"
dp = build_table(a, b)
for order in [("diag", "del", "ins"), ("del", "ins", "diag"), ("ins", "del", "diag")]:
ops = traceback(a, b, dp, order)
check(a, b, ops, dp[-1][-1])
print(order, ops)All three orders produce cost-2 scripts for ab → ba. One uses two substitutions. The other two each use a deletion, a keep, and an insertion. The check function is a cheap test you can add to any traceback. Concatenating the source side must give a, the target side must give b, and the non-keep operations must add up to the distance.
Common Mistakes
- Off-by-one indexing. Cell
(i, j)refers to the charactersa[i-1]andb[j-1]. Usinga[i]reads the wrong character, and it crashes ati = m. - Stopping at a border. A loop condition of
while i > 0 and j > 0stops too early and drops the leading insertions or deletions. Useor, and guard each move. - Forgetting to reverse. Traceback collects operations from the end of the strings to the start.
- Throwing away the table. Traceback needs every cell on the path, so it needs the full O(mn) table. The two-row trick in the next chapter computes the distance but loses this information. Recovering the script in linear space takes Hirschberg's divide-and-conquer approach, which the next chapter introduces.
Back-Pointers versus Recomputation
Another approach stores a back-pointer, a small code for the winning move, in each cell while the table is filled. Traceback then just follows the pointers. This avoids recomputing the comparisons, but it adds a second m × n array and fixes the tie-breaking policy at fill time. Recomputing from values, as above, costs only O(m + n) extra time and lets you change policy without refilling the table. For most uses, recomputation is the simpler choice.
Exercise
Using the kitten/sitting table above, trace back from (6, 7) with the order deletion, insertion, diagonal. What script do you get, and is its cost still 3?
Show answer
At (6,7) deletion needs dp[5][7]+1 = 5, which fails, and insertion needs dp[6][6]+1 = 3, which fits: insert g. At (6,6) deletion needs 4 and insertion needs 4; both fail, so take the diagonal match n/n. At (5,5) deletion needs dp[4][5]+1 = 3, which fails, and insertion needs dp[5][4]+1 = 3, which fails; the diagonal is sub e→i (1+1 = 2). At (4,4), (3,3) and (2,2) the up and left neighbors are both 2, so deletion and insertion need 3 and fail; take the diagonal keeps. At (1,1) deletion needs dp[0][1]+1 = 2 and insertion needs dp[1][0]+1 = 2, both failing; take sub k→s. The script is the same as with diagonal-first, with cost 3. In this table the ties never fall on the deletion or insertion moves.
Exercise
How many distinct optimal edit scripts turn "ab" into "ba" under unit-cost Levenshtein? List them.
Show answer
There are three. (1) sub a→b, sub b→a. (2) del a, keep b, ins a. (3) ins b, keep a, del b. Each costs 2. Any script with more than two non-keep operations costs more.
Exercise
A colleague's traceback labels a step "keep" whenever dp[i][j] == dp[i-1][j-1]. Explain why this can produce a wrong script, and give the one-line fix.
Show answer
A cell can equal its diagonal neighbor while a[i-1] != b[j-1], because the value came from the up or left neighbor plus 1. The code then records a mismatched pair as "keep", so applying the script does not produce b. The fix is to compare against dp[i-1][j-1] + (a[i-1] != b[j-1]) and label the step "keep" only when the characters are equal.