Skip to content

Two-dimensional dynamic programming

A state with two indices can describe a pair of prefixes. Each cell records an answer for those prefixes, and its dependencies determine the table order. The indices have a meaning before they have a position in a Python list.

Read one-dimensional dynamic programming first. This lesson computes unit-cost edit distance between invented strings. An insertion, deletion, or substitution costs one. An unchanged character costs zero. The result is the minimum cost to transform the entire first string into the entire second string.

This global distance does not model affine gap penalties or local sequence alignment. Python string elements are Unicode code points, so a displayed character can occupy more than one element.

Download the English captions for this video.

Let dp[i][j] be the edit distance from source[:i] to target[:j]. The empty source needs j insertions, so dp[0][j] = j. The empty target needs i deletions, so dp[i][0] = i. The empty pair has dp[0][0] = 0.

For positive i and j, consider the last alignment step.

Step Preceding state Added cost
Delete the source character. dp[i - 1][j] 1
Insert the target character. dp[i][j - 1] 1
Match or substitute the two characters. dp[i - 1][j - 1] 0 for equality; otherwise 1

Take the minimum of these three candidate costs. They cover every possible final alignment step. A cell depends on the cell above, the cell to its left, and the diagonal cell above and left.

The function returns every prefix answer so the trace can show each state. Rows represent source prefixes; columns represent target prefixes.

def edit_distance_table(source: str, target: str) -> list[list[int]]:
"""Return unit-cost edit distances for every pair of string prefixes.
Args:
source: Original string, interpreted as Unicode code points.
target: Required string, interpreted as Unicode code points.
Returns:
A table whose entry [i][j] gives the minimum cost to transform
source[:i] into target[:j].
"""
table = [[0] * (len(target) + 1) for _ in range(len(source) + 1)]
for row in range(len(source) + 1):
table[row][0] = row
for column in range(len(target) + 1):
table[0][column] = column
for row in range(1, len(source) + 1):
for column in range(1, len(target) + 1):
mismatch = int(source[row - 1] != target[column - 1])
deletion = table[row - 1][column] + 1
insertion = table[row][column - 1] + 1
substitution = table[row - 1][column - 1] + mismatch
table[row][column] = min(deletion, insertion, substitution)
return table
source = "GAT"
target = "GCTT"
table = edit_distance_table(source, target)
prefixes = [target[:column] for column in range(len(target) + 1)]
print("Target prefixes:", prefixes)
for row, costs in enumerate(table):
print("Source prefix", repr(source[:row]), "costs", costs)
print("Minimum edit cost:", table[-1][-1])
Target prefixes: ['', 'G', 'GC', 'GCT', 'GCTT']
Source prefix '' costs [0, 1, 2, 3, 4]
Source prefix 'G' costs [1, 0, 1, 2, 3]
Source prefix 'GA' costs [2, 1, 1, 2, 3]
Source prefix 'GAT' costs [3, 2, 2, 1, 2]
Minimum edit cost: 2

Before the code fills a cell, its three dependencies contain correct prefix answers. The initialized boundary cells start this invariant. The minimum therefore gives the correct answer for the new cell.

The substitution step can align the differing middle characters in this example. An insertion can then account for the additional final character. The table checks whether any other alignment has lower cost.

For source length m and target length n, the table contains (m + 1)(n + 1) cells. Time and returned storage are O((m + 1)(n + 1)). For nonempty strings, this is O(mn). The expanded form also describes the boundary row or column when one string is empty.

The function returns its table, so that table is output space. If an answer-only function keeps the table internally, the same allocation is auxiliary space. The trace makes prefix slices for explanation; these slices are outside the algorithm’s stated cost.

List repetition copies references. Repeating one row creates several references to the same list, so a cell update then changes every apparent row.

shared_rows = [[0] * 3] * 2
shared_rows[0][1] = 9
separate_rows = [[0] * 3 for _ in range(2)]
separate_rows[0][1] = 9
print("Repeated row reference:", shared_rows)
print("Independent rows:", separate_rows)
print("Repeated rows share identity:", shared_rows[0] is shared_rows[1])
print("Independent rows share identity:", separate_rows[0] is separate_rows[1])
Repeated row reference: [[0, 9, 0], [0, 9, 0]]
Independent rows: [[0, 9, 0], [0, 0, 0]]
Repeated rows share identity: True
Independent rows share identity: False

The table function uses a comprehension to allocate each row separately. This rule also applies to grid paths, knapsack tables, and other mutable matrices.

The next row needs the preceding row and the current row’s earlier cells. Two rows therefore suffice when the task requests only the final distance. Unit insertion and deletion costs make this distance symmetric, so the shorter string can define the columns.

def edit_distance(source: str, target: str) -> int:
"""Return unit-cost edit distance with storage for two short rows.
Args:
source: Original string, interpreted as Unicode code points.
target: Required string, interpreted as Unicode code points.
Returns:
The minimum number of insertions, deletions, and substitutions.
"""
if len(source) < len(target):
source, target = target, source
if not target:
return len(source)
previous = list(range(len(target) + 1))
for row, source_character in enumerate(source, start=1):
current = [row] + [0] * len(target)
for column, target_character in enumerate(target, start=1):
mismatch = int(source_character != target_character)
current[column] = min(
previous[column] + 1,
current[column - 1] + 1,
previous[column - 1] + mismatch,
)
previous = current
return previous[-1]
print("Distance with two rows:", edit_distance(source, target))
print("Distance with arguments reversed:", edit_distance(target, source))
print("Distance from an empty string:", edit_distance("", target))
assert edit_distance(source, target) == table[-1][-1]
Distance with two rows: 2
Distance with arguments reversed: 2
Distance from an empty string: 4

For nonempty strings, time is O(mn) and auxiliary space is O(min(m, n)). The early return gives O(1) time and space when either string is empty. These bounds count integer arithmetic as constant-time work.

Replacing a row loses the earlier alignment decisions. To return the edits, keep predecessor choices or reconstruct a path through the full table. Swapping the strings also needs reconsideration when insertion and deletion costs differ.

Test empty strings and competing operations

Section titled “Test empty strings and competing operations”

An equal pair needs no edit. An empty string requires one edit per code point of the other string. A reversal can expose a model that incorrectly treats a character transposition as one permitted operation.

cases = [
("", ""),
("", "AC"),
("AC", ""),
("AAA", "AAA"),
("AB", "BA"),
("A", "TTTT"),
("é", "e"),
]
for first, second in cases:
full_table = edit_distance_table(first, second)
distance = edit_distance(first, second)
assert distance == full_table[-1][-1]
assert distance == edit_distance(second, first)
assert abs(len(first) - len(second)) <= distance <= max(
len(first), len(second)
)
print(repr(first), "to", repr(second), "cost", distance)
assert edit_distance("AB", "BA") == 2
assert edit_distance("AAA", "AAA") == 0
print("Boundary and operation checks passed.")
'' to '' cost 0
'' to 'AC' cost 2
'AC' to '' cost 2
'AAA' to 'AAA' cost 0
'AB' to 'BA' cost 2
'A' to 'TTTT' cost 4
'é' to 'e' cost 1
Boundary and operation checks passed.

Edit Distance uses the same operation costs. Explain the empty-prefix boundaries before reducing the table to two rows.

Longest Common Subsequence uses a different recurrence over two prefixes. Define what a cell maximizes and why a mismatch permits skipping a character from either string.

Download the Python source to run the complete example locally.

MIT’s edit-distance lecture notes develop string subproblems and their dependencies. Compare its suffix states with this lesson’s prefix states while keeping the minimum-cost objective.

Python’s sequence documentation explains repetition and shared references. Its repeated-list example explains why a matrix needs independently allocated rows.