Recover the edit operations behind a Levenshtein distance by backtracking
Why it matters Edit scripts power word error rate reports for speech models, spelling suggestions and token-level diffs of model outputs.
The edit distance number says how far two strings are; the edit script says HOW, which is what spell checkers, ASR error reports and diff tools show. You get it by backtracking through the dynamic programming table.
Write edit_script(src, tgt). src and tgt are lists of tokens. Build the standard Levenshtein table with insert, delete and substitute all costing 1. Then backtrack from the bottom-right cell to (0, 0), preferring at each step, in this order:
1. ('keep', s) if the tokens are equal and the diagonal cell has the same cost,
2. ('sub', s, t) if the diagonal cell plus 1 gives the cost,
3. ('del', s) if the cell above (one fewer src token) plus 1 gives the cost,
4. ('ins', t) otherwise (the cell to the left plus 1).
Moves are only allowed when the needed index exists. Return (distance, ops) with ops in left-to-right order.
def edit_script(src, tgt)Example
edit_script(list('cat'), list('cut')) is (1, [('keep', 'c'), ('sub', 'a', 'u'), ('keep', 't')]).
Understand the idea
Levenshtein distance is the fewest single-token edits (insert, delete, substitute) to turn src into tgt. Dynamic programming fills a table D where D[i][j] is the distance between the first i tokens of src and the first j of tgt:
D[i][j] = min(D[i-1][j-1] + (0 if equal else 1), D[i-1][j] + 1, D[i][j-1] + 1).
The script is found by walking back from the corner along cells that explain each value.
Worked example: cat to cut. The last letters t and t are equal and the diagonal has the same cost, so 'keep t'. Then a vs u: the diagonal plus 1 matches, so 'sub a to u'. Then c and c: 'keep c'. Reversed: keep c, sub a u, keep t, distance 1.
Rule: backtrack with a fixed preference (here keep, sub, del, ins). Different preferences give different but equally short scripts.
ASR word error rate reports, spell checkers and text diff tools all use this table and backtrace.