LCS / Two-Sequence
O(n · m)
2D dp on prefixes (i, j); match advances both, mismatch takes the best of skipping one side.
0/13 solved
Recognise it
The signal
Two strings/arrays compared, aligned, or interleaved: LCS, edit distance, transform A→B, count occurrences as a subsequence.
1Brute force
Enumerate subsequences of one string: exponential.
2The observation
Exponential alignment: prefixes pairs overlap.
3Why it works
dp[i][j] is optimal for the prefixes of length i and j; each step matches the last chars or skips one side.
Reach for it when
- +Two sequences compared — common subsequence, edit distance, alignment, interleaving, transform A→B.
- +The decision is naturally 'match the last chars or skip one side'.
- +Both lengths are moderate (O(n·m) table fits).
Not when
- ×One sequence with self-structure (increasing run, palindrome)use LIS or palindrome DP
- ×Longest common substring (contiguous) — you're confusing it with subsequenceuse Same grid, reset to 0 on mismatch
- ×Sequences so large the O(n·m) table doesn't fituse Hirschberg or hashing
- ×One string tiny, the other huge (is it a subsequence?)use Greedy subsequence check / automaton
- ×LCS of two permutationsuse Reduce to LIS in O(n log n)
Intuition
When a problem compares two strings or arrays — "longest common subsequence", "edit distance", "make them equal" — the state is a grid. dp[i][j] = the answer for the first i characters of A and first j characters of B. You fill an (n+1)×(m+1) table; row/column 0 is the "empty prefix" base case.
Read the full intuition
The recurrence always splits on the last characters:
- If
A[i-1] == B[j-1](they match): the pair contributes, so build on the diagonal —dp[i][j] = dp[i-1][j-1] + 1(for LCS). - If they differ: you must drop one side —
dp[i][j] = max(dp[i-1][j], dp[i][j-1])(best of "ignore A's last" vs "ignore B's last").
Picture the grid for A="ace", B="abcde": walking diagonally on matches (a, c, e) traces out the common subsequence; the bottom-right cell holds its length, 3.
Edit distance is the same grid with three moves instead of two: if the last chars match, dp[i-1][j-1] (free); else 1 + min(replace=dp[i-1][j-1], delete=dp[i-1][j], insert=dp[i][j-1])`. The three neighbours = the three edit operations. Base row/col = "turn an empty string into a length-k one" = k insertions.
Key idea
The reflex to build: two indices over two sequences ⇒ a 2-D table, decide by comparing the last element of each prefix, read the answer at
dp[n][m].
Why it costs what it costs
Time O(n·m). every cell of the (n+1)×(m+1) table is filled once in O(1).
Space O(n·m). the full table — collapsible to O(min(n,m)) by keeping two rows, since each cell reads only the previous row and column.
Practice
- Longest Common SubsequenceFoundationFoundationMedium
- Delete Operation for Two StringsApply it · Express answer through LCS.Apply itMedium
- Edit DistanceOne change · Three operations with costs.One changeMedium
- Uncrossed LinesOne change · Not presented as strings.One changeMedium
- Distinct SubsequencesTwists · Count instead of optimise.TwistsHard
- Interleaving StringBranches · Third string drives transitions.BranchesMedium
- Shortest Common Supersequence Advanced · Reconstruct, not just length.AdvancedHard
- Regular Expression MatchingMastery checkMastery checkHard
- Edit DistanceCSESMedium
- Longest Common SubsequenceCSESMedium
- Minimum Total Distance TraveledHard
- Maximum Length of Repeated SubarrayMedium
- Wildcard MatchingHard
Pitfalls
Classic bugs
- !Python
[[0]*m]*naliases one row n times — use[[0]*m for _ in range(n)]. - !Index shift:
dp[i][j]readsA[i-1],B[j-1]because the table is over prefixes. - !Base cases: LCS row/col 0 are 0; edit distance row/col 0 are
i/j. - !Edit distance: diagonal = replace, up = delete, left = insert — keep them straight.
- !Distinct Subsequences sums (not max): always add
dp[i-1][j], add the diagonal only on a match.
Go deepervariants and techniques · 1 combinations · resources
Variants and techniques
- Longest common subsequenceMatch → diag+1, else max of up/left. LCS, Delete Operation (= n+m-2·LCS).
- Edit distanceMatch → diag, else 1+min(diag,up,left). Edit Distance.
- Interleavingdp[i][j] = can A[:i],B[:j] interleave to C[:i+j]; inherit from up or left when that char matches C. Interleaving String.
- Counting subsequencesdp[i][j] += dp[i-1][j-1] on match, always += dp[i-1][j]. Distinct Subsequences.
Combinations
Exchange-Argument Sorting (custom comparator)+LCS / Two-Sequence
match points on a line to capacity-limited targets minimising the total distance
- Exchange-Argument Sorting (custom comparator):
- sort both robots and factories; an optimal matching never crosses
- LCS / Two-Sequence:
- two-sequence DP: dp[i][j] = robots i.. assigned to factories j..