Sub topic 7
Recovering the Edit Script with Traceback
This chapter assumes you have read the earlier chapters on the recurrence and the dynamic programming table. You should be comfortable with dp[i][j] as the distance between the first i characters of a and the first j characters of b. The table gives you the number of edits. Often you also need to know which edits they are, for example to highlight changes in a diff or to explain a spelling correction. Traceback recovers those edits from the finished table.
The idea: walk back along the choices
Every cell got its value from one of three neighbors:
| Neighbor | Move | Meaning |
|---|---|---|
| `dp[i-1][j-1]` | diagonal | keep (if `a[i-1] == b[j-1]`) or substitute |
| `dp[i-1][j]` | up | delete `a[i-1]` |
| `dp[i][j-1]` | left | insert `b[j-1]` |
Start at the bottom-right cell dp[m][n]. Find a neighbor whose value, plus the cost of its move, equals the current cell's value. That neighbor is the choice the minimum came from. Record the operation, step to that neighbor, and repeat until you reach dp[0][0]. The operations come out in reverse order, so reverse the list at the end.
Implementation
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)Output:
('sub', 'k', 's')
('keep', 'i', 'i')
('keep', 't', 't')
('keep', 't', 't')
('sub', 'e', 'i')
('keep', 'n', 'n')
('ins', '', 'g')The guards i > 0 and j > 0 handle the table's edges. Along row 0 only insertions are possible, and along column 0 only deletions are possible.
Common errors
- Assuming the script is unique. Several optimal scripts can exist. The order of the
ifchecks is a tie-breaking rule. This code prefers diagonal moves, then deletions, then insertions. If you change the order, you may get a different script with the same total cost. - Comparing values without the move cost. Checking
dp[i-1][j] < dp[i][j]is wrong. A neighbor is valid only when its value plus the move's cost equals the current value exactly. - Forgetting to reverse. Traceback runs from the end of both strings back to the start.
- Discarding the table. Traceback needs the whole
(m+1) × (n+1)table. The walk itself takes only O(m + n) steps, but storing the table takes O(mn) memory.
Exercise
Why can the final else branch record an insertion without checking dp[i][j] == dp[i][j-1] + 1?
Show answer
Every cell's value is the minimum of the three candidate moves, so at least one of them must match. If the diagonal and delete checks both fail, the insert move must be the one that produced the value. The branch is also safe at the edge: when i == 0, we have j > 0, so an insertion is the only possible move.
Exercise
Suppose you reorder the checks so deletions are tried before diagonal moves. Can the distance change? Can the script change?
Show answer
The distance cannot change, because it is read from dp[m][n] before traceback starts. The script can change when there are ties. You still get a valid optimal script, but it may use a different mix of operations, and those operations may happen at different positions.