Course outline

Data Structures & Algorithms / Optimization proofs and maintained aggregates / Lesson 21

Edit distance with rolling dynamic-programming rows

Derive a string edit-distance recurrence, compress the table by rows, and verify that previous-layer dependencies remain intact.

About 19 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Define edit-distance states and base cases.
  • Explain each recurrence dependency and rolling-row order.
  • Test empty strings, substitutions, and known cases.
  • Derive the unit-cost edit recurrence and its base cases.
  • Trace rolling-row ownership and distinguish numeric distance from reconstruction.

Define the state

Let the state for prefixes of lengths i and j be the minimum number of single-character insertions, deletions, and substitutions needed to transform the first prefix into the second. All operations have unit cost in this lesson. The empty-to-prefix base case is the prefix length. This contract computes a distance only, not the sequence of edits; reconstructing edits requires retaining additional information.

Derive and compress the recurrence

For each pair of characters, consider deleting from the first prefix, inserting into it, or matching/substituting the last character. The minimum uses the previous row at j, the current row at j-1, and the previous row at j-1. The implementation retains both rows until the current row is complete, then replaces previous. Overwriting a needed previous-row cell too early changes the recurrence.

python Compute distance with two rows
def edit_distance(a, b):
    previous = list(range(len(b) + 1))
    for i, left in enumerate(a, start=1):
        current = [i] + [0] * len(b)
        for j, right in enumerate(b, start=1):
            cost = 0 if left == right else 1
            current[j] = min(previous[j] + 1,
                             current[j - 1] + 1,
                             previous[j - 1] + cost)
        previous = current
    return previous[-1]

Each current cell reads the current left neighbor and two previous-row values.

Check representative examples

The assertions use the function from the first block in the same Python file. Transforming an empty string into abc needs three insertions; equal strings need none; cat to cut needs one substitution; kitten to sitting has distance three. Python iterates strings by Unicode code points, which are not always the same as user-perceived characters. Applications needing grapheme-aware edits need a defined segmentation policy.

python Check known distances
assert edit_distance("", "abc") == 3
assert edit_distance("cat", "cat") == 0
assert edit_distance("cat", "cut") == 1
assert edit_distance("kitten", "sitting") == 3

The cases cover empty input, identity, substitution, and a known multi-edit transformation.

Account for complexity and output

For lengths m and n, the algorithm performs O(mn) state transitions and stores O(n) values for the second string, in addition to input storage. Swapping inputs can reduce the row size for this symmetric unit-cost distance, but verify that any changed operation costs remain symmetric before applying that optimization. Rolling rows discard the path, so they cannot by themselves report which edits were chosen.

Verify layer ownership

Compare the rolling implementation with a full-table reference on small strings, including empty inputs and repeated characters. Check symmetry for this unit-cost contract and the zero distance of identical strings. Trace one substitution by hand to confirm the diagonal uses the previous row. If edit operations or costs change, rederive the base cases and recurrence before reusing the same update order.

Define the transformation and its units

The unit-cost Levenshtein distance in this lesson is the minimum number of insertions, deletions and substitutions transforming string a into string b. Matching an equal symbol costs zero; each allowed edit costs one. A transposition is not a single operation in this contract. The baseline iterates Python strings by Unicode code point, so a visible character made of a base and combining mark can occupy two positions. Decide normalization and segmentation before comparing text if the application needs different equivalence or user-perceived characters.

A numeric distance is not an edit script. Several scripts can attain the same optimum, and rolling rows retain only enough costs for the next layer. If the application needs the actual operations, retain predecessor choices or use a separately justified reconstruction algorithm and define how ties are resolved. Validate a script by applying it to the source, checking that it produces the target, and comparing its cost with the computed optimum.

Derive states from the last action

Let D(i,j) be the minimum cost to transform a[:i] into b[:j]. D(0,j)=j because all j target symbols must be inserted; D(i,0)=i because all i source symbols must be deleted. For positive i and j, the last action is either deletion of a[i-1], insertion of b[j-1], or a match/substitution of the last symbols. These give D(i-1,j)+1, D(i,j-1)+1, and D(i-1,j-1)+cost, where cost is zero for equality and one otherwise.

Every candidate extends a valid smaller-prefix transformation, so the minimum is achievable. Conversely, an optimal transformation can be classified by its final alignment action, and its preceding work cannot cost less than the corresponding subproblem optimum. Taking the minimum therefore gives the optimal value. This reasoning depends on the stated operations and unit costs; adding transposition or context-dependent costs requires a new state or recurrence rather than a casual change to one constant.

Trace row ownership in the baseline

The Python function initializes previous to [0,1,...,len(b)], the row D(0,j). For each source symbol at one-based i it initializes current[0]=i and fills j from one through len(b). At current[j], previous[j] is the deletion predecessor, current[j-1] is the insertion predecessor already computed in this row, and previous[j-1] is the diagonal predecessor for a match or substitution. Only after all columns are complete does previous=current discard the older row.

For a="a" and b="ab", previous begins [0,1,2]. The current row starts [1,0,0]. At j=1 the equal "a" symbols select diagonal 0, giving current[1]=0. At j=2 the insertion from current[1] gives 1, yielding [1,0,1] and distance 1. If a previous diagonal were overwritten before use, the implementation could read a current-layer value and compute a different problem. Keeping two rows makes ownership explicit.

Reason about space, symmetry and boundaries

For lengths m and n the nested loops evaluate m×n interior cells; initialization and row creation add O(m+n) work, yielding O(mn+m+n) in a bound that also covers empty strings. Two rows of n+1 integers use O(n+1) auxiliary values, excluding the strings. For nonempty lengths the usual shorthand is O(mn) time and O(n) space. Under symmetric unit insertion and deletion costs, reversing an edit sequence gives an equally costly reverse transformation, so the distance is symmetric and inputs may be swapped to put the shorter one in columns.

Do not assume symmetry after changing costs: if insertion costs two and deletion costs one, transforming empty to "a" costs two while the reverse costs one. Python integers are exact, but equality and indexing still operate on code points, not bytes or grapheme clusters. A distance-only row compression does not automatically supply the predecessor history. Choose full storage, recomputation, or a proved divide-and-conquer reconstruction when the output requires a script.

Check the recurrence independently

For tiny strings, build a full (m+1) by (n+1) table as a reference and compare each completed rolling row, not merely the final number. Also check identity, both empty directions, symmetry under this unit-cost contract, repeated symbols, and a one-edit example for each operation. The absolute length difference is a lower bound because one insertion or deletion changes length by at most one and a substitution does not change it. A concrete script matching that bound proves optimality in such a case.

Tests must distinguish the documented operation set: "ab" to "ba" is not one transposition here, and can be achieved in two substitutions. Compare code-point sequences deliberately for composed and decomposed Unicode, or normalize consistently before applying the algorithm under a new contract. Finite reference cases and proofs are complementary; synthetic checks do not establish grapheme-aware behavior or a production performance benchmark.

20 worked examples

1. Both empty

Problem: Find the distance between two empty strings.

  1. The empty source already equals the empty target.
  2. No edits are necessary, so D(0,0)=0.
text Synthetic trace
a=""; b=""
distance=0

No edits are necessary, so D(0,0)=0.

Expected result: distance=0

Why this result follows: The empty transformation has zero cost.

2. Insertion base

Problem: Transform empty string into "dog" under unit costs.

  1. The target contains three code points.
  2. Insert d, o and g; fewer than three edits cannot increase length by three.
text Synthetic trace
a=""; b="dog"
distance=3

Insert d, o and g; fewer than three edits cannot increase length by three.

Expected result: distance=3

Why this result follows: The first row equals target prefix length.

3. Deletion base

Problem: Transform "go" into an empty string.

  1. The source contains two code points.
  2. Deleting both characters costs two, matching the length-difference lower bound.
text Synthetic trace
a="go"; b=""
distance=2

Deleting both characters costs two, matching the length-difference lower bound.

Expected result: distance=2

Why this result follows: The first column counts required deletions.

4. Equal symbol

Problem: Compute D(1,1) for source "x" and target "x".

  1. The diagonal D(0,0) is zero.
  2. The symbols match, so diagonal cost 0+0 gives zero.
text Synthetic trace
a="x"; b="x"
D(1,1)=0

The symbols match, so diagonal cost 0+0 gives zero.

Expected result: D(1,1)=0

Why this result follows: Matching equal symbols introduces no edit.

5. One substitution

Problem: Transform "pin" to "pan" with a single edit.

  1. The first and last characters already agree.
  2. Substitute a for i; the strings differ, so zero edits cannot suffice.
text Synthetic trace
"pin" → "pan"
distance=1; substitute i→a

Substitute a for i; the strings differ, so zero edits cannot suffice.

Expected result: distance=1; substitute i→a

Why this result follows: One substitution achieves the lower bound of one for distinct strings.

6. One deletion

Problem: Transform "cart" to "car" under unit costs.

  1. The target is the source without its last character.
  2. Deleting t once reaches the target and matches the length-difference lower bound.
text Synthetic trace
"cart" → "car"
distance=1; delete t

Deleting t once reaches the target and matches the length-difference lower bound.

Expected result: distance=1; delete t

Why this result follows: One deletion changes the length by exactly one.

7. One insertion

Problem: Transform "at" to "cat" under unit costs.

  1. The target adds c before the source.
  2. Inserting c once reaches the target and matches the one-character length difference.
text Synthetic trace
"at" → "cat"
distance=1; insert c

Inserting c once reaches the target and matches the one-character length difference.

Expected result: distance=1; insert c

Why this result follows: One insertion supplies the missing target symbol.

8. One cell

Problem: Compute D(1,1) for "a" to "b".

  1. Deletion and insertion candidates both cost 2 from their base states.
  2. The unequal diagonal costs D(0,0)+1=1, which is the minimum.
text Synthetic trace
a="a"; b="b"
candidates: 2,2,1; D(1,1)=1

The unequal diagonal costs D(0,0)+1=1, which is the minimum.

Expected result: candidates: 2,2,1; D(1,1)=1

Why this result follows: The recurrence chooses the cheapest valid final action.

9. One completed row

Problem: Compute the rolling row for a="a" and b="ab".

  1. The initial previous row is [0,1,2].
  2. Matching a gives current[1]=0, then inserting b gives current[2]=1.
text Synthetic trace
previous=[0,1,2]; source symbol="a"
current=[1,0,1]

Matching a gives current[1]=0, then inserting b gives current[2]=1.

Expected result: current=[1,0,1]

Why this result follows: Each cell uses the correct previous and current neighbors.

10. Repeated character

Problem: Find the distance from "aa" to "a".

  1. Deleting either occurrence yields the target with one edit.
  2. The length difference is one, so no zero-edit solution exists.
text Synthetic trace
a="aa"; b="a"
distance=1

The length difference is one, so no zero-edit solution exists.

Expected result: distance=1

Why this result follows: Different deletion choices can share the same optimum.

11. Full table

Problem: Build the full table for "a" to "b".

  1. The base row is [0,1] and base column is [0,1].
  2. The interior substitution cell is one, giving the table shown.
text Synthetic trace
a="a"; b="b"
D=[[0,1],[1,1]]

The interior substitution cell is one, giving the table shown.

Expected result: D=[[0,1],[1,1]]

Why this result follows: Base cases and the diagonal determine this small table.

12. Row replacement

Problem: When may previous be replaced with current in the baseline?

  1. Every current cell still needs values from the previous row.
  2. Only after the current row is complete can it become the next previous row.
text Synthetic trace
complete current row
previous=current

Only after the current row is complete can it become the next previous row.

Expected result: previous=current

Why this result follows: The next iteration depends on the completed row, not older rows.

13. Symmetry

Problem: Compare distance("a", "ab") and distance("ab", "a").

  1. Inserting b transforms the first into the second at cost one.
  2. Deleting b reverses that transformation at the same unit cost.
text Synthetic trace
"a"→"ab": insert b
"ab"→"a": delete b; both=1

Deleting b reverses that transformation at the same unit cost.

Expected result: "ab"→"a": delete b; both=1

Why this result follows: Unit insertion and deletion have equal reverse costs.

14. Length lower bound

Problem: Give a lower bound for transforming a length-two string into a length-five string.

  1. The target is three characters longer than the source.
  2. Each insertion changes length by one, while substitution changes none, so at least three edits are needed.
text Synthetic trace
source length=2; target length=5
distance≥3

Each insertion changes length by one, while substitution changes none, so at least three edits are needed.

Expected result: distance≥3

Why this result follows: Length difference bounds the number of necessary edits.

15. Transposition boundary

Problem: Find distance from "ab" to "ba" without a transposition operation.

  1. The strings differ at both positions, so one substitution cannot fix both.
  2. Two substitutions produce "ba", and no one insertion or deletion preserves the equal length, so the distance is two.
text Synthetic trace
"ab" → "ba"
distance=2; two substitutions

Two substitutions produce "ba", and no one insertion or deletion preserves the equal length, so the distance is two.

Expected result: distance=2; two substitutions

Why this result follows: Swapping adjacent characters is not a primitive in this contract.

16. Code-point length

Problem: How many Python string elements are in "é"?

  1. The sequence contains a base e and a combining acute mark.
  2. They are two code points even though they may appear as one visual character.
text Synthetic trace
string="é"
code-point length=2

They are two code points even though they may appear as one visual character.

Expected result: code-point length=2

Why this result follows: The baseline iterates code points rather than grapheme clusters.

17. Raw Unicode distance

Problem: Compute distance from "é" to "é" without normalization.

  1. The source has one code point and the target has two distinct code points.
  2. Substitute the composed character with e and insert the combining mark, costing two; one edit cannot produce both target code points.
text Synthetic trace
a="é"; b="é"
raw code-point distance=2

Substitute the composed character with e and insert the combining mark, costing two; one edit cannot produce both target code points.

Expected result: raw code-point distance=2

Why this result follows: Exact representation matters when normalization is absent.

18. Distance versus script

Problem: What does a rolling-row result of 2 provide by itself?

  1. It states the minimum cost under the declared edit operations.
  2. It does not retain enough history by itself to identify which two operations were used.
text Synthetic trace
rolling result=2
output: numeric distance, not a stored script

It does not retain enough history by itself to identify which two operations were used.

Expected result: output: numeric distance, not a stored script

Why this result follows: Discarded predecessor history is needed for direct reconstruction.

19. Save the old diagonal

Problem: Trace saving the old diagonal while updating one row from [0,1,2].

  1. At the first column the previous diagonal D(0,0) is 0, and the old previous[1]=1 must be saved before overwriting.
  2. After the first column, the saved old value 1 becomes the previous diagonal for the second column.
text Synthetic trace
old row=[0,1,2]
j=1: diagonal=0; save old row[1]=1
j=2: diagonal=1

After the first column, the saved old value 1 becomes the previous diagonal for the second column.

Expected result: old diagonal sequence: 0,1

Why this result follows: A temporary retains the previous-layer value before it is overwritten.

20. Row storage

Problem: Count integer slots in two rows when b has length 4.

  1. Each row includes column zero through column four.
  2. There are five entries per row and ten entries across two live rows.
text Synthetic trace
len(b)=4; rows=2
slots=10

There are five entries per row and ten entries across two live rows.

Expected result: slots=10

Why this result follows: Both boundary cells and interior columns consume storage.

Common errors and fixes

A compressed table gives too small a distance

Why it happens
A previous-layer value was overwritten before it was read.
How to fix it
Keep separate previous and current rows or prove a safe in-place update.
Prevent it next time
Compare each row with a full-table reference on tiny inputs.

An empty string gives the wrong answer

Why it happens
Base cases were initialized to zero instead of prefix lengths.
How to fix it
Initialize the first row and each row’s first cell to the required edit counts.
Prevent it next time
Test both empty-to-nonempty directions.

The distance is mistaken for an edit script

Why it happens
Rolling rows retain the final cost but not all predecessor choices.
How to fix it
Store predecessor information or use a reconstruction algorithm.
Prevent it next time
Test the actual requested output contract, not just its numeric cost.

20 practice exercises

1. What is the distance from cat to cut?

Show hint

Compare the corresponding characters and count differing positions.

Show worked solution

It is one: substitute u for a while retaining c and t. The recurrence selects the diagonal substitution cost for the differing character.

The first and last characters c and t match. Substituting u for a transforms cat into cut in one edit, and the strings differ, so the distance cannot be zero.

Check your solution

  • One substitution reaches cut.
  • The optimum is 1.

2. Why are two rows sufficient for the numeric distance?

Show hint

Identify the layer of every recurrence dependency.

Show worked solution

Each cell needs the previous row and the current row’s left neighbor. Once the current row is complete, older rows are no longer needed for the next numeric transition; reconstructing the edit sequence is a separate requirement.

A current cell needs previous[j], previous[j-1], and the already computed current[j-1]. After finishing a row, earlier rows are no longer needed for numeric evaluation; storing an edit script requires additional history or a proven recovery method.

Check your solution

  • The previous row remains intact while the current row is filled.
  • The numeric result alone does not retain a script.

3. State precisely what D(2,3) represents for strings a and b.

Show hint

Use prefix lengths and the allowed operations.

Show worked solution

D(2,3) is the minimum unit-cost insertions, deletions and substitutions needed to transform a[:2] into b[:3]. It is a prefix subproblem, not necessarily the distance between the complete strings.

Check your solution

  • The source prefix has length two.
  • The target prefix has length three.

4. Derive the base row D(0,j) for target "wxyz".

Show hint

Starting from empty requires one insertion per target symbol.

Show worked solution

The row is [0,1,2,3,4]. To form a target prefix of length j from empty, exactly j insertions are necessary and sufficient under unit costs.

Check your solution

  • D(0,0)=0.
  • D(0,4)=4.

5. Build the full table for source "ab" and target "ac".

Show hint

Initialize the base row and column, then fill left to right.

Show worked solution

The rows are [0,1,2], [1,0,1], and [2,1,1]. The final cell is 1: the first symbols match and substituting b with c achieves the optimum.

Check your solution

  • The middle row is [1,0,1].
  • The final distance is 1.

6. A one-row update overwrites the old diagonal before using it. Explain a safe repair.

Show hint

Preserve previous-row values until consumed.

Show worked solution

Use separate previous and current rows as in the baseline, replacing previous only after current is complete. An in-place variant must explicitly save the old diagonal before overwriting and prove each remaining dependency.

Check your solution

  • The diagonal must come from the previous row.
  • The current left neighbor comes from the new row.

7. A script transforms "a" to "ab" by inserting b, then deletes b to return to "a". Is its cost optimal?

Show hint

Compare the final target with the original source.

Show worked solution

The script is valid but costs two edits, while source and final target are identical. The empty script has cost zero, so the proposed round trip is not optimal even though both operations are allowed.

Check your solution

  • The proposed script costs 2.
  • The optimal distance from "a" to itself is 0.

8. Can one substitution transform "dogs" into "dog"? Explain the required operation.

Show hint

Substitution preserves length.

Show worked solution

No: substitution changes a symbol but leaves length four. Delete the final s to obtain the three-character target in one operation, which is optimal by the length difference.

Check your solution

  • Substitution alone cannot change the length.
  • Deleting s gives distance one.

9. Prove the distance from "go" to "going" is three using a witness and a lower bound.

Show hint

Compare lengths, then construct the target.

Show worked solution

The length difference is 5-2=3, so at least three edits are necessary. Insert i, n and g after "go" to reach "going" in exactly three, proving optimality.

Check your solution

  • The lower bound is three.
  • The insertion witness has three edits.

10. If insertion costs 2 and deletion costs 1, compare empty→"a" and "a"→empty.

Show hint

The operations have different reverse costs.

Show worked solution

Empty to "a" requires one insertion costing 2. The reverse requires one deletion costing 1, so the weighted distance is asymmetric and swapping inputs is not automatically safe.

Check your solution

  • The forward cost is 2.
  • The reverse cost is 1.

11. Compare the baseline edit model with a model that adds adjacent transposition at unit cost for "ab"→"ba".

Show hint

The set of allowed operations determines the distance.

Show worked solution

The baseline needs two edits, while the expanded model can swap the adjacent symbols in one. Adding that operation changes the optimization problem and requires a recurrence that explicitly accounts for transpositions.

Check your solution

  • Baseline distance is 2.
  • The expanded model admits a one-step swap.

12. Compare two-row storage when lengths are m=1000 and n=10, before and after swapping symmetric inputs.

Show hint

Each row has one more entry than its column-string length.

Show worked solution

With the 10-character string in columns, two rows hold 2×11=22 values. With the 1000-character string in columns they hold 2×1001=2002; swapping is valid only for the symmetric unit-cost contract.

Check your solution

  • The shorter-column layout has 22 values.
  • The longer-column layout has 2002 values.

13. A proposed script changes cat to dot by substitutions c→d and a→o, but claims target dog. Diagnose it.

Show hint

Apply the operations to the entire source.

Show worked solution

The two substitutions produce dot, not dog, so the script is invalid for the claimed target. A further substitution t→g produces dog with three edits; verify the final string rather than trusting the stated cost.

Check your solution

  • The two-edit result is dot.
  • Replacing t with g reaches dog.

14. An application wants to delete one visible grapheme formed by base plus combining mark. What must change in the baseline?

Show hint

Change the sequence units before applying the recurrence.

Show worked solution

Segment the text into grapheme clusters under a declared policy and apply the recurrence to that sequence. Then one deletion removes the whole cluster; retain a mapping if original code-point or byte positions must be reported.

Check your solution

  • The unit becomes a grapheme cluster.
  • Offsets need an explicit mapping to the original representation.

15. Compare exact distance before and after applying the same canonical normalization to "é" and "é".

Show hint

The raw code-point sequences differ.

Show worked solution

Before normalization their baseline distance is two, because one substitution and one insertion produce the target. After both are normalized to the same canonical form they are identical and their distance is zero.

Check your solution

  • The raw distance is two.
  • The normalized distance is zero.

16. Design a full-table oracle to test rolling rows for all strings of length at most two over {a,b}.

Show hint

Enumerate source and target strings independently.

Show worked solution

Generate the empty string and all one- and two-symbol strings over the alphabet. For every ordered pair compute the full dynamic-programming table and compare its final cell and each row with the rolling implementation.

Check your solution

  • There are seven strings in the test set.
  • There are 49 ordered string pairs.

17. Trace the first cell of each rolling row when a="abc" and b is empty.

Show hint

Each source prefix must be deleted.

Show worked solution

The initial row is [0]. Each source character creates a row whose first cell is its prefix length, yielding [1], [2], then [3]; the final distance is three.

Check your solution

  • The row sequence is [0],[1],[2],[3].
  • The final value is 3.

18. Why must the current row be filled from left to right in this implementation?

Show hint

The insertion candidate reads current[j-1].

Show worked solution

At column j, current[j-1] must already represent D(i,j-1). Filling left to right establishes that value before use; reversing the order would read an uncomputed current-row entry.

Check your solution

  • The insertion predecessor is current[j-1].
  • It is computed earlier in left-to-right order.

19. Count interior recurrence cells for lengths m=3 and n=5.

Show hint

There is one cell for each nonempty prefix pair.

Show worked solution

The nested loops fill 3×5=15 interior cells. Base row and column initialization add separate work; the count does not measure actual execution time.

Check your solution

  • There are 15 interior cells.
  • Boundary initialization is additional work.

20. How does edit distance differ from Hamming distance for "a" and "ab"?

Show hint

Hamming distance ordinarily compares equal-length sequences.

Show worked solution

The baseline edit distance is one because inserting b transforms "a" into "ab". Ordinary Hamming distance on equal-length aligned strings is not defined for this unequal-length pair without an additional convention.

Check your solution

  • Edit distance is 1.
  • Ordinary equal-length Hamming distance is not defined here.

Key takeaways

  • Define state, base cases, and dependencies before compressing storage.
  • Test rolling rows against a full reference and distinguish cost from reconstruction.
  • Each cell compares deletion, insertion and match or substitution.
  • Two rows suffice for the numeric value under this recurrence.
  • Unicode code points and visible graphemes are different units.

Official references