When a problem involves two sequences, the natural DP state is a pair of prefixes: dp[i][j] describes the first i items of one sequence and the first j of the other. The two archetypes are the longest common subsequence (how much do two sequences share?) and edit distance (how many edits turn one into the other?). Together they power diff, DNA alignment, spell checkers and fuzzy search.
Think of it like
Lining up two strands of beads
Lay two strands of colored beads side by side and connect beads of the same color with strings, never letting two strings cross. The most strings you can attach is the LCS. Edit distance asks the opposite question: how many beads must you swap, add or remove so the strands match exactly? Both are solved by deciding, from the end, what happens to the last bead of each strand.
The two-sequence pattern
For sequences a (length m) and b (length n), build an (m+1) × (n+1) table. Row 0 and column 0 represent empty prefixes, which makes base cases trivial. Each cell (i, j) is decided by looking at the last characters a[i-1] and b[j-1], and reads at most three neighbors: up-left (both characters consumed), up (only a's consumed) and left (only b's consumed).
- Subsequence
- Characters taken in order but not necessarily adjacent:
ACEis a subsequence ofABCDE. - Substring
- A contiguous run of characters:
BCDis a substring ofABCDE,ACEis not. - Prefix
a[0..i), the firsticharacters. Two-sequence DP is indexed by prefix lengths, not positions.- Alignment
- A way of lining two sequences up with gaps, where each column is a match, a mismatch, or a gap in one sequence. LCS and edit distance are both optimal alignments under different scoring rules.
Longest common subsequence
Find the length of the longest sequence that is a subsequence of both a and b. Brute force enumerates the 2ᵐ subsequences of a. The DP looks only at last characters.
- 1
State
L[i][j]= the length of the LCS ofa[0..i)andb[0..j). - 2
Last characters equal
If
a[i-1] == b[j-1], match them:L[i][j] = L[i-1][j-1] + 1. - 3
Last characters differ
They cannot both be the last character of a common subsequence, so drop one of them:
L[i][j] = max(L[i-1][j], L[i][j-1]). - 4
Base cases
L[0][j] = L[i][0] = 0: an empty prefix shares nothing. - 5
Order and answer
Row by row, left to right, so up, left and up-left are ready. The answer is
L[m][n].
Worked example: a = "ABCBDAB", b = "BDCABA". The visualization above fills a table like this one cell at a time; diagonal arrows mark matches.
| ∅ | B | D | C | A | B | A | |
|---|---|---|---|---|---|---|---|
| ∅ | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A | 0 | 0 | 0 | 0 | 1 | 1 | 1 |
| B | 0 | 1 | 1 | 1 | 1 | 2 | 2 |
| C | 0 | 1 | 1 | 2 | 2 | 2 | 2 |
| B | 0 | 1 | 1 | 2 | 2 | 3 | 3 |
| D | 0 | 1 | 2 | 2 | 2 | 3 | 3 |
| A | 0 | 1 | 2 | 2 | 3 | 3 | 4 |
| B | 0 | 1 | 2 | 2 | 3 | 4 | 4 |
Reconstructing the subsequence
The table stores lengths, not strings, but the path that produced the answer can be retraced. Start at (m, n) and walk back until a row or column hits 0:
- 1If
a[i-1] == b[j-1], that character is part of the LCS: record it and move diagonally to(i-1, j-1). - 2Otherwise move toward the larger neighbor: up if
L[i-1][j] ≥ L[i][j-1], else left. - 3Reverse the recorded characters at the end.
In the example the walk goes up from (7,6), matches A at (6,6), goes up, matches B at (4,5), goes left, matches C at (3,3), goes left and matches B at (2,1). Reversed, that spells BCBA. Breaking ties toward "left" instead would yield a different but equally long answer.
Optimizing space
Row i reads only row i-1, so two rows of length min(m, n) + 1 suffice for the length. The reconstruction walk, however, needs the whole table. Hirschberg's algorithm recovers the actual subsequence in O(min(m, n)) space and still O(m·n) time by splitting a in half, running the two-row DP forward on the left half and backward on the right half, finding where the optimal path crosses the middle row, and recursing on both sides: a nice use of Divide & Conquer.
Longest common substring vs subsequence
A common substring must be contiguous, so a mismatch breaks the run. The state changes meaning: S[i][j] is the length of the longest common substring that ends exactly at a[i-1] and b[j-1].
Longest common subsequence
- Gaps allowed
- Mismatch:
max(up, left) - Answer in the corner
L[m][n] "XABCY"vs"ABZC"→ABC(3)
Longest common substring
- Must be contiguous
- Mismatch: reset to 0
- Answer is the maximum cell anywhere in the table
"XABCY"vs"ABZC"→AB(2)
Edit distance (Levenshtein)
The edit distance between a and b is the minimum number of single-character insertions, deletions and replacements that transform a into b. "kitten" → "sitting" takes 3: replace k→s, replace e→i, insert g.
- 1
State
D[i][j]= the edit distance betweena[0..i)andb[0..j). - 2
Last characters equal
No edit needed for them:
D[i][j] = D[i-1][j-1]. - 3
Last characters differ
The last operation was one of: replace
a[i-1]byb[j-1](D[i-1][j-1] + 1), deletea[i-1](D[i-1][j] + 1), or insertb[j-1]at the end (D[i][j-1] + 1). Take the minimum. - 4
Base cases
D[i][0] = i(delete all i characters) andD[0][j] = j(insert all j characters). - 5
Order and answer
Row by row; the answer is
D[m][n].
| ∅ | r | o | s | |
|---|---|---|---|---|
| ∅ | 0 | 1 | 2 | 3 |
| h | 1 | 1 | 2 | 3 |
| o | 2 | 2 | 1 | 2 |
| r | 3 | 2 | 2 | 2 |
| s | 4 | 3 | 3 | 2 |
| e | 5 | 4 | 4 | 3 |
Reconstructing the operations
| Move from (i, j) to | Condition | Operation |
|---|---|---|
| (i−1, j−1) | a[i-1] == b[j-1] and D[i][j] == D[i-1][j-1] | Keep the character |
| (i−1, j−1) | D[i][j] == D[i-1][j-1] + 1 | Replace a[i-1] with b[j-1] |
| (i−1, j) | D[i][j] == D[i-1][j] + 1 | Delete a[i-1] |
| (i, j−1) | D[i][j] == D[i][j-1] + 1 | Insert b[j-1] |
For horse → ros the walk produces: replace h→r, keep o, delete r, keep s, delete e. Applied in order: horse → rorse → rose → ros, three edits.
Space. As with LCS, only the previous row is needed. With a single row you must save the old diagonal value D[i-1][j-1] in a variable before overwriting dp[j], because the update for j needs the previous row's j-1 entry, which was just overwritten for the current row.
Shortest common supersequence
The shortest string that contains both a and b as subsequences. Characters in the LCS can be shared; everything else must appear separately, so the length follows directly from the LCS.
- 1Build the LCS table for
aandb. - 2Walk back from
(m, n). On a match, emit the character once and move diagonally. - 3On a mismatch, move toward the larger LCS neighbor and emit the character you stepped past (
a[i-1]when moving up,b[j-1]when moving left). - 4When one string runs out, emit the rest of the other. Reverse the result.
Where these algorithms run
| Application | Underlying DP | Notes |
|---|---|---|
diff, git, code review tools | LCS / shortest edit script over lines | Classic Unix diff (Hunt and McIlroy) computed an LCS of lines; git defaults to Myers' O((m + n)·D) algorithm, fast when the number of differences D is small |
| DNA and protein alignment | Weighted edit distance | Needleman-Wunsch (global alignment) and Smith-Waterman (local alignment, cells reset to 0 like longest common substring) with substitution matrices and gap penalties |
| Spell checking and "did you mean" | Levenshtein / Damerau distance | Candidates within distance 1 or 2, accelerated with BK-trees, Tries (Prefix Trees) or Levenshtein automata |
| Fuzzy search, record linkage | Edit distance on names and addresses | Finds near-duplicate customer records |
| Speech recognition | Edit distance over words | Word error rate = word-level edit distance ÷ reference length |
| Plagiarism and clone detection | LCS / longest common substring | Often on tokens rather than characters |
The two-sequence family
| Problem | State | Key transition |
|---|---|---|
| Longest common subsequence | LCS of prefixes | match → diagonal + 1, else max(up, left) |
| Uncrossed lines | same as LCS | It is LCS on integer arrays |
| Delete operation for two strings | deletions to equalize prefixes | m + n − 2·LCS |
| Minimum ASCII delete sum | cost to equalize prefixes | Edit distance with deletions only, weighted by character code |
| Edit distance | edits between prefixes | match → diagonal, else 1 + min of three |
| Distinct subsequences | ways b[0..j) appears in a[0..i) | match → diagonal + up, else up |
| Interleaving string | can a[0..i) and b[0..j) form c[0..i+j)? | OR of up and left when the characters line up |
| Wildcard / regex matching | does pattern prefix match text prefix? | * reads left (empty) or up (one more char) |
Complexity
| Problem / version | Time | Space | Notes |
|---|---|---|---|
| LCS, full table | O(m·n) | O(m·n) | Needed to reconstruct the subsequence |
| LCS length, two rows | O(m·n) | O(min(m, n)) | Iterate over the longer string, store rows for the shorter |
| LCS string, Hirschberg | O(m·n) | O(min(m, n)) | Divide and conquer on the middle row |
| Longest common substring | O(m·n) | O(min(m, n)) | Answer is the max cell, not the corner |
| Edit distance | O(m·n) | O(min(m, n)) | Full table if the edit script is required |
| Shortest common supersequence | O(m·n) | O(m·n) | Built by walking the LCS table |
Reconstruction walks are O(m + n) once the table exists. Under the strong exponential time hypothesis, edit distance and LCS have no strongly subquadratic algorithm.
Implementation
Fills the full table, then walks back from the corner to recover one LCS.
def lcs(a: str, b: str) -> str:
m, n = len(a), len(b)
L = [[0] * (n + 1) for _ in range(m + 1)] # L[i][j] = LCS of a[:i], b[:j]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
out, i, j = [], m, n
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]: # part of the LCS: go diagonal
out.append(a[i - 1])
i -= 1
j -= 1
elif L[i - 1][j] >= L[i][j - 1]:
i -= 1 # drop a[i-1]
else:
j -= 1 # drop b[j-1]
return "".join(reversed(out))
print(lcs("ABCBDAB", "BDCABA")) # BCBAKey takeaways
- Two-sequence DP indexes by prefix lengths
(i, j)with an extra empty row and column, and decides each cell from the last characters. - LCS: match → diagonal + 1, mismatch → max(up, left). Edit distance: match → diagonal, mismatch → 1 + min(replace, delete, insert).
- Reconstruct by walking back from
(m, n)and asking which neighbor produced the current value; this needs the full table (or Hirschberg). - Longest common substring resets to 0 on a mismatch and takes the max over all cells; shortest common supersequence has length m + n − LCS.
- These recurrences run real tools: diff, git, DNA aligners, spell checkers and speech-recognition scoring.
Common pitfalls
- Off-by-one errors from mixing positions and prefix lengths: cell
(i, j)comparesa[i-1]andb[j-1]. - Forgetting the nonzero borders in edit distance (
D[i][0] = i,D[0][j] = j). - Returning the corner cell for longest common substring instead of the maximum over the table.
- In the one-row version, reading
row[j-1]as the diagonal after it has already been overwritten for the current row. - Confusing subsequence with substring in the problem statement, which changes the recurrence completely.
Interview tips
- State what up, left and diagonal mean for the specific problem before writing the recurrence.
- Walk through a 3 × 3 corner of the table by hand; it catches base-case bugs immediately.
- Offer the space optimization, and mention that reconstructing the answer needs either the full table or Hirschberg's divide and conquer.
- Relate new problems to LCS when possible: delete operation for two strings, uncrossed lines and shortest common supersequence all reduce to it.
Real-world applications
- Line-based diff in version control (git diff, code review tools, patch generation).
- Biological sequence alignment (Needleman-Wunsch, Smith-Waterman, BLAST seeding and extension).
- Spell correction, autocomplete with typo tolerance and fuzzy search in databases.
- Speech and OCR evaluation (word and character error rates).
- Data cleaning and record linkage: matching near-duplicate names and addresses.
Practice problems
Test yourself
What is the edit distance between "kitten" and "sitting"?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.