Don't memorize LCS — watch the table fill, then walk it backwards. The longest common subsequence of two strings grows one cell at a time: when the two characters match, the cell extends the diagonal by one; when they mismatch, it copies the better of the cell above or to the left. Fill the whole grid and the corner holds the length. Then backtrack from the corner along the diagonals to read off the actual subsequence.
match → diagonal + 1 · mismatch → max(up, left) · backtrack to recover
SUBSEQUENCE
Keep order, drop some characters (gaps allowed). LCS is the longest one shared by both strings.
DP TABLE
dp[i][j] = LCS length of the first i of A and first j of B. Empty prefixes are 0.
MATCH
If A[i−1] = B[j−1]: dp[i][j] = dp[i−1][j−1] + 1 — grow the diagonal.
MISMATCH
Else dp[i][j] = max(dp[i−1][j], dp[i][j−1]) — the best of dropping a char.
lcs.sim — A = ABCBDAB · B = BDCAB
Ready
Rows are A = ABCBDAB, columns B = BDCAB. Each cell is the LCS length of the prefixes that lead to it. Press Step: fill by the match / mismatch rule, then backtrack from the corner to recover the subsequence.
Dynamic programming turns an exponential search — there are 2ⁿ subsequences of a string — into a grid you fill once. Define dp[i][j] as the LCS length of the first i characters of A and the first j of B. An empty prefix shares nothing, so the top row and left column are all zero. Now every other cell follows from its three already-computed neighbours. If the newest characters A[i−1] and B[j−1] are equal, they can jointly end a longer subsequence, so the answer is one more than the diagonal cell: dp[i−1][j−1] + 1. If they differ, at least one of them is not used, so you take the better of ignoring A's last char (the cell above) or B's last char (the cell to the left). Two rules, filled row by row, and dp[n][m] is the length.
01
Define the subproblem
dp[i][j] = LCS length of prefixes A[0..i) and B[0..j). Base row and column are 0.
02
Match extends the diagonal
If the last characters are equal, that pair joins the LCS: dp[i][j] = dp[i−1][j−1] + 1.
03
Mismatch takes the max
Otherwise drop one character: dp[i][j] = max(dp[i−1][j], dp[i][j−1]).
04
Backtrack to recover
From the corner, step diagonally on matches (collecting the char), else toward the larger neighbour.
Time
O(n · m)
Space
O(n · m)
Length
dp[n][m]
String
Backtrack
The length only needs two rows at a time, so you can compute it in O(min(n, m)) space — but recovering the string itself wants the full grid (or the clever Hirschberg trick for linear space). LCS is the sibling of edit distance: the same table shape, one counting shared characters and the other counting edits. It powers diff tools, version-control merges, and DNA sequence alignment. Once you see this grid, the whole family of two-string DP problems reads the same way.
The picture: the filled table and the walk back
Highlighted cells are the traceback from the corner, which holds 4. A diagonal step (both characters used) happens where the letters match: B, A, C, B read from the end, giving BCAB. Vertical and horizontal steps are characters skipped from A or from B.
Worked example, step by step
Take A = ABCBDAB and B = BDCAB. Every row is the table row for one more letter of A; each entry is the LCS length of that prefix of A and the prefix of B named in the column header. The first column and the first row are all 0 (an empty prefix shares nothing).
A prefix
∅
B[..1] B
B[..2] D
B[..3] C
B[..4] A
B[..5] B
∅
0
0
0
0
0
0
A
0
0
0
0
1
1
AB
0
1
1
1
1
2
ABC
0
1
1
2
2
2
ABCB
0
1
1
2
2
3
ABCBD
0
1
2
2
2
3
ABCBDA
0
1
2
2
3
3
ABCBDAB
0
1
2
2
3
4
Bold entries are the matches (diagonal + 1); everything else copied the larger of the cell above or to the left. The corner is 4. To recover the string, start there and ask, at each cell, “do the last letters match?” If yes, keep the letter and move diagonally; if not, move toward the larger neighbour (up on a tie). This walk visits 8 cells and reads off BCAB. It is not the only answer: a brute force over every subsequence finds 2 of length 4, BCAB and BDAB. Breaking ties left instead of up would have produced the other. The table stores the length; the traceback chooses among equals.
Complexity and trade-offs
Case
Time
Space
Why
Full table
O(n·m)
O(n·m)
One cell per prefix pair. Needed if you want to walk back and recover the string by the simple method.
Two rolling rows
O(n·m)
O(min(n, m))
Each row depends only on the one above. Gives the length but loses the traceback.
Hirschberg
O(n·m)
O(min(n, m))
Recovers the sequence itself in linear space by splitting on the middle row and recursing; about twice the work.
Brute force
O(2ⁿ·m)
O(n)
Try each of the 2ⁿ subsequences of A and test it against B. Fine for tiny strings only.
Myers diff (O(ND))
O(N·D)
O(N) with the linear-space refinement
N is the total length, D the number of edits. Very fast when the strings are nearly equal, which is the usual case for files.
The table approach is quadratic regardless of how similar the inputs are, so two 100,000-character strings cost 10¹⁰ cell updates, and a full table does not fit in memory. Real diff tools therefore exploit similarity: Myers’ algorithm costs in proportion to the number of differences, not to n·m. The rolling-row and Hirschberg variants are the standard fix when memory, not time, is the limit.
Common mistakes
A table with no padding row and column
Sizing it n × m instead of (n+1) × (m+1) makes dp[i-1][j-1] a negative index at the edges. In Python that wraps silently to the far side. On the page’s strings this returns 7, which is impossible: the LCS can’t exceed the shorter string, 5. Allocate the extra row and column of zeros.
Confusing subsequence with substring
A substring must be contiguous. For these strings the longest common substring has length 2, while the LCS has length 4. Using the substring recurrence (reset to 0 on mismatch) answers a different question.
Taking only the diagonal on a mismatch
If a mismatch copies dp[i-1][j-1] instead of the max of up and left, the table counts only a strictly paired walk. On the page’s strings it returns 2 rather than 4. A mismatch means one of the two letters is dropped, and you don’t know which.
Reading “the” LCS out of a length
The table gives a length; the string needs a traceback, and there can be several answers (here BCAB and BDAB). If a test expects one specific string, the tie-break rule is part of the specification.
Recursing top-down on long strings
A memoized recursion on (i, j) can go up to i + j frames deep. Two 600-character strings can need 1,200 frames, past Python’s default limit of 1,000. Fill the table iteratively.
Where this shows up
diff and version control
A file diff is an LCS of two lists of lines: lines in the LCS are unchanged, the rest are insertions and deletions. Git’s default diff algorithm is Myers’, which computes this in time proportional to the number of edits.
Sequence alignment
Comparing DNA or protein sequences is the same table with scores in place of 1 and 0 and a penalty for gaps (Needleman–Wunsch). LCS is the special case where only insertions and deletions are allowed.
Longest increasing subsequence
The LIS of a sequence of distinct numbers equals the LCS of the sequence and its sorted copy. That gives an O(n²) solution with the same table, though a binary-search method reaches O(n log n).
Plagiarism and similarity checks
The length of the LCS divided by the length of the longer text is a simple similarity score for documents or code, tolerant of inserted and removed passages.
SOLVE IT YOURSELF
Solve it: longest common subsequence
This one is yours to write — in Python or TypeScript, running for real in your browser. Edit the stub below, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.
YOUR TASK
Implement lcs_length(a, b): return the length of the longest common subsequence of two strings (keep order, drop characters freely from each). Fill a 2-D table dp[i][j] = LCS length of the first i chars of a and first j of b. O(n·m).
HINTS — 4 IDEAS
Let dp[i][j] be the LCS length of a[:i] and b[:j]. An empty prefix gives 0, so row 0 and column 0 are all zero.
If the current characters match (a[i-1] == b[j-1]), extend the diagonal: dp[i][j] = dp[i-1][j-1] + 1.
Otherwise drop one character and take the better side: dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
The answer is dp[n][m], the bottom-right corner.
CPython · WebAssembly✓ Solved
1
1
Check yourself
1 · When A[i−1] = B[j−1], what is dp[i][j]?
A matching pair can end a subsequence one longer than the best for the two shorter prefixes, which sits on the diagonal.
2 · On a mismatch, the cell takes…
If the last characters differ, at least one is unused, so you keep the better of dropping A's last char (up) or B's last char (left).
3 · How do you recover the actual subsequence?
Each diagonal step on a match contributed a character; walking back from dp[n][m] and collecting those (in reverse) rebuilds one LCS.
Questions
Subsequence vs substring?
A subsequence keeps the original order but may skip characters (B_C_B from ABCBDAB); a substring must be contiguous. So the longest common subsequence is generally different from — and at least as long as — the longest common substring.
How does this relate to edit distance?
Same table shape. Edit distance counts insertions, deletions and replacements to convert A into B; LCS counts shared characters. With only insertions and deletions allowed, edit(A, B) = n + m − 2·LCS(A, B) — they are two views of one grid.
Can I save memory?
For the length alone, keep just the previous and current rows: O(min(n, m)) space. To reconstruct the string in linear space, use Hirschberg's divide-and-conquer method, which still runs in O(n·m) time.
One grid, every two-string DP.
Match grows the diagonal, mismatch keeps the best neighbour, and a walk back from the corner spells out the answer.