Skip to main content
TRACK B · ALGORITHMmedium•NOVEMBER 2026•7 MIN

2D Sequence DP: Prefix-Length Alignment Tables

Compare or align two sequences (LCS, Edit Distance, Regex Matching) on an (n + 1) × (m + 1) table indexed by prefix lengths (i, j).

2d dynamic programmingsequence alignmentlcsedit-distancedp-table

The core idea

When a problem compares two sequences A and B, a 1D DP array cannot track independent positions in both inputs. Define dp[i][j] over prefix lengths A[:i] and B[:j] (0 ≤ i ≤ n, 0 ≤ j ≤ m) so row 0 and column 0 cleanly represent empty prefixes.

Watch it run

Step through the trace below to see how matching tail characters (A[i - 1] == B[j - 1]) pull from the diagonal dp[i - 1][j - 1] while mismatches pull from max(top, left).

LOADING 2D SEQUENCE DP SIM...

Key Takeaway

Canonical Python template

def longest_common_subsequence(a: str, b: str) -> int:
    n, m = len(a), len(b)
    dp = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = 1 + dp[i - 1][j - 1]
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[n][m]

Related Lab Entries