Skip to the workspace
Pebellslearn by building
Sequence DP: the Diff Engine  ›  Lesson

Reconstructing the Answer & the Edit Script

Reconstructing the Answer 30 minWalk a finished table backwards to recover the answer itself, and do it in linear space

dsa / Reconstructing the Answer & the Edit Script

Explore each scene at your own pace.

01 · Walking back from the corner

Walking back from the corner

Reconstructing the Answer & the Edit Script

Definition
Reconstruction recovers the actual solution from a filled dynamic-programming table by walking back from the final cell to the start, following the choices that produced each value. The sequence of steps it records forms an edit script.
In plain words
A finished table tells you the total, not the route. It is like retracing a trip by asking at each stop how you got there, then reading your notes backwards. The result is a list of what to keep, delete and add.

In short: a DP table's final cell only gives a number. To get the actual answer — which items were kept, inserted or deleted — walk back from that cell to (0, 0), replaying at each step which neighbour it was built from: a diagonal match is kept, otherwise the walk goes left (insert) or up (delete) depending on which neighbour holds the table's value. The walk runs backwards, so reverse the emitted list at the end. Hirschberg's trick gets the same path in O(n) space by never keeping the whole table at all.

Seven boxes in a staircase, each labelled with an emitted operation (=E, +C, -T, =A, =R, +T, -C) connected by arrows pointing from the corner back to the start

The survival score says 4 of 5 lines survived, but not which 4, and a history panel that can't show what changed isn't much use. Quarry needs an edit script: an ordered list of keep, delete and insert that turns the old version into the new one.

Every number in a DP table was chosen from a neighbour. Walk those choices backwards from the final cell and you recover the answer itself, not just its size, and with one more idea you can do it without storing the table.

Walking back from the corner

Take the LCS table from lesson 2, for CRATE against TRACE. Start at the bottom-right cell (i, j) = (5, 5) and repeat until you reach (0, 0):

  • If a[i-1] == b[j-1], that item is kept. Emit = and step diagonally.
  • Otherwise, if moving left keeps the same value (table[i][j-1] >= table[i-1][j]), then b[j-1] was inserted. Emit + and step left.
  • Otherwise a[i-1] was deleted. Emit - and step up.
  • Once i or j reaches 0, only one direction is left: the remaining items of b are inserts, or the remaining items of a are deletes.

The walk emits the script backwards, so reverse it at the end.

watch it move · grid

Walking back from the corner replays every choice the fill made. Diagonals are kept items, left steps are inserts and up steps are deletes.

Start in the corner, which holds 3. E equals E, so E was kept. Emit = E and step diagonally. 6 by 6 table. At row 5, column 5 — value 3. 36 of 36 cells filled.

1 / 8
python

The walk visits at most m + n cells, so it costs O(m + n) on top of the fill. Filling the table is the same O(m · n) time as lesson 2, and keeping the whole table to walk back over it costs O(m · n) space — the price this lesson pays for the extra arrows, until Hirschberg's trick below. The expensive part is keeping the table.

Step through a tiny walk and watch i and j fall:

step through it
1old, new = ["a", "b"], ["b", "c"]
2t = [[0, 0, 0], [0, 0, 0], [0, 1, 1]]
3script, i, j = [], 2, 2
4while i > 0 or j > 0:
5 if i > 0 and j > 0 and old[i - 1] == new[j - 1]:
6 script.append("=" + old[i - 1])
7 i, j = i - 1, j - 1
8 elif j > 0 and (i == 0 or t[i][j - 1] >= t[i - 1][j]):
9 script.append("+" + new[j - 1])
10 j -= 1
11 else:
12 script.append("-" + old[i - 1])
13 i -= 1
14print(script[::-1])
What does this print?
old, new = ["a", "b"], ["b", "c"]
t = [[0, 0, 0], [0, 0, 0], [0, 1, 1]]
script, i, j = [], 2, 2
while i > 0 or j > 0:
    if i > 0 and j > 0 and old[i - 1] == new[j - 1]:
        script.append("=" + old[i - 1])
        i, j = i - 1, j - 1
    elif j > 0 and (i == 0 or t[i][j - 1] >= t[i - 1][j]):
        script.append("+" + new[j - 1])
        j -= 1
    else:
        script.append("-" + old[i - 1])
        i -= 1
print(script[0])

Why ties go left

A replaced line is a delete plus an insert, and both orders are equally short. Which one you get depends only on how you break the tie. Walking backwards and preferring the insert means the insert is emitted first, so after the reverse it comes second. That gives the order every diff reader expects: the old line, then its replacement.

What does this print?
old, new = ["shards=2"], ["shards=4"]
t = [[0, 0], [0, 0]]
out, i, j = [], 1, 1
while i > 0 or j > 0:
    if i > 0 and j > 0 and old[i - 1] == new[j - 1]:
        out.append("=" + old[i - 1]); i -= 1; j -= 1
    elif j > 0 and (i == 0 or t[i][j - 1] >= t[i - 1][j]):
        out.append("+" + new[j - 1]); j -= 1
    else:
        out.append("-" + old[i - 1]); i -= 1
print(out[::-1])

Here's a walk with the wrong loop condition:

broken — fix it

Turning [a, b] into [b] deletes a, but the script leaves that out because the loop stops as soon as one index hits 0. Make the walk run until both are 0.

Scene 1 of 8
Project context and further resources
You're building a piece ofQuarry — version history
This piece — edit_script(): Turns the finished table into the exact list of keeps, deletes and inserts.
Scenario The history panel has to show what changed, not just how much. The edit script walks the finished LCS table back from its corner and lists every kept, deleted and inserted line.
edit_script.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
edit_script(old, new) → listThe keeps, deletes and inserts that turn old into new.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.