Longest Common Subsequence
How similar are two strings? One natural answer: find the longest sequence of characters that appears in both, in the same order, though not necessarily side by side. That sequence is a longest common subsequence (LCS). It measures the similarity of DNA strands, it is how diff and version-control systems decide which lines of a file changed, and it is the cleanest example of a DP over pairs of prefixes, the table shape behind edit distance, sequence alignment and many string problems.
Subsequences
A subsequence of is what remains after deleting any number of characters, keeping the order: GRTM is a subsequence of ALGORITHM, but MTG is not. A common subsequence of and is a subsequence of both. The problem: given of length and of length , find a common subsequence of maximum length.
Brute force would list the subsequences of and test each against in time: . The DP below takes .
Optimal substructure
Write for the prefix of length (so is empty), and likewise . Let be any LCS of and . Look at the last characters.
- If , then , and is an LCS of and .
- If and , then is an LCS of and .
- If and , then is an LCS of and .
Proof
(1) If , appending to would give a common subsequence of length , contradicting maximality; so . Then is a common subsequence of and of length . If those prefixes had a longer common subsequence , then followed by would be a common subsequence of and longer than , a contradiction.
(2) If , then does not use , so it is a common subsequence of and . A longer one would also be a common subsequence of and , contradicting maximality of . (3) is symmetric.
When the last characters differ, an LCS cannot use both of them, so it is an LCS of one of the two shortened pairs, whichever is better. With the LCS length of and :
There are subproblems, each with at most three ingredients, the cells above, to the left and diagonally up-left. Filling row by row, left to right, guarantees all three are ready.
The table
The animation fills the table for $X = $ ALGORITHM and $Y = $ LOGARITHM, two anagrams of each other. A highlighted diagonal step means "match, add one"; otherwise the cell takes the larger of its upper and left neighbours. The final frame traces an LCS back from the corner.
LCS-LENGTH(x, y) // x has length m, y has length n
1 c = new table [0..m, 0..n] filled with 0
2 for i = 1 to m
3 for j = 1 to n
4 if x[i - 1] == y[j - 1] // characters are 0-based
5 c[i, j] = c[i - 1, j - 1] + 1
6 else c[i, j] = max(c[i - 1, j], c[i, j - 1])
7 return c
TRACE-LCS(c, x, y, i, j) // call with i = m, j = n
1 out = empty string
2 while i > 0 and j > 0
3 if x[i - 1] == y[j - 1]
4 out = x[i - 1] + out; i = i - 1; j = j - 1
5 elseif c[i - 1, j] >= c[i, j - 1]
6 i = i - 1 // ties go up
7 else j = j - 1
8 return outThe walk back needs no extra table: at each cell it re-derives which case produced the value. The Python version prints the finished table and the same LCS as the animation, because it breaks ties the same way (up before left).
def lcs_table(x, y):
m, n = len(x), len(y)
c = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
c[i][j] = c[i - 1][j - 1] + 1
else:
c[i][j] = max(c[i - 1][j], c[i][j - 1])
return c
def trace_lcs(c, x, y):
i, j, out = len(x), len(y), []
while i > 0 and j > 0:
if x[i - 1] == y[j - 1]:
out.append(x[i - 1]); i -= 1; j -= 1
elif c[i - 1][j] >= c[i][j - 1]:
i -= 1
else:
j -= 1
return "".join(reversed(out))
x, y = "ALGORITHM", "LOGARITHM"
c = lcs_table(x, y)
print(" " + " ".join(y))
for i in range(len(x) + 1):
print((" " if i == 0 else x[i - 1]) + " " + " ".join(str(v) for v in c[i][1:]))
print("LCS:", trace_lcs(c, x, y), "length", c[-1][-1]) L O G A R I T H M
0 0 0 0 0 0 0 0 0
A 0 0 0 1 1 1 1 1 1
L 1 1 1 1 1 1 1 1 1
G 1 1 2 2 2 2 2 2 2
O 1 2 2 2 2 2 2 2 2
R 1 2 2 2 3 3 3 3 3
I 1 2 2 2 3 4 4 4 4
T 1 2 2 2 3 4 5 5 5
H 1 2 2 2 3 4 5 6 6
M 1 2 2 2 3 4 5 6 7
LCS: LGRITHM length 7
The row for ALGORITHM's A is mostly zeros because the only A in LOGARITHM sits in position 4. The last five characters, RITHM, are common to both words and match along the diagonal at the end, lifting the length from 2 to 7. The LCS found is LGRITHM; another one of the same length is LORITHM, which a different tie rule would find.
Running time and space
Each of the cells takes time, so LCS-LENGTH runs in time and space, and TRACE-LCS in , since every step decreases or . If only the length is needed, two rows suffice, because row reads only row : space after swapping the strings so the shorter one indexes the columns. Recovering the subsequence itself in linear space is also possible, with Hirschberg's divide-and-conquer algorithm, at about twice the time.
import random
def lcs_length_two_rows(x, y):
if len(y) > len(x):
x, y = y, x # columns = the shorter string
prev = [0] * (len(y) + 1)
for ch in x:
cur = [0]
for j, d in enumerate(y, 1):
cur.append(prev[j - 1] + 1 if ch == d else max(prev[j], cur[j - 1]))
prev = cur
return prev[-1]
rng = random.Random(7)
for n in [10, 100, 1000]:
a = "".join(rng.choice("ACGT") for _ in range(n))
b = "".join(rng.choice("ACGT") for _ in range(n))
L = lcs_length_two_rows(a, b)
print(f"two random DNA strings of length {n:4}: LCS {L:4}, ratio {L / n:.3f}")two random DNA strings of length 10: LCS 6, ratio 0.600
two random DNA strings of length 100: LCS 61, ratio 0.610
two random DNA strings of length 1000: LCS 644, ratio 0.644
For random strings over four letters the LCS length is a roughly constant fraction of , about for long strings (the exact limit, the Chvátal-Sankoff constant for a four-letter alphabet, is not known in closed form). That fraction is how biologists tell related sequences, which score far higher, from unrelated ones.
In C++
The full table and the trace-back in C++, with the same tie rule as the animation.
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
std::string lcs(const std::string& x, const std::string& y) {
size_t m = x.size(), n = y.size();
std::vector<std::vector<int>> c(m + 1, std::vector<int>(n + 1, 0));
for (size_t i = 1; i <= m; ++i)
for (size_t j = 1; j <= n; ++j)
c[i][j] = x[i - 1] == y[j - 1] ? c[i - 1][j - 1] + 1 : std::max(c[i - 1][j], c[i][j - 1]);
std::string out;
size_t i = m, j = n;
while (i > 0 && j > 0) {
if (x[i - 1] == y[j - 1]) { out.push_back(x[i - 1]); --i; --j; }
else if (c[i - 1][j] >= c[i][j - 1]) --i;
else --j;
}
std::reverse(out.begin(), out.end());
return out;
}
int main() {
std::printf("%s\n", lcs("ALGORITHM", "LOGARITHM").c_str());
std::printf("%s\n", lcs("DYNAMIC", "DIAGRAM").c_str());
std::printf("%s\n", lcs("PROGRAMMING", "GAMING").c_str());
}LGRITHM
DAM
GAMING
Application: what diff does
Treat each line of a file as one character. An LCS of the old and new versions is the set of lines that stayed; every other old line was deleted and every other new line was inserted. Real tools (GNU diff, Git) use Myers' algorithm, which finds the same kind of answer in time when the files differ in lines, but the DP is the idea.
old = ["def area(r):", " pi = 3.14", " return pi * r * r", "# demo", "print(area(2))"]
new = ["import math", "def area(r):", " return math.pi * r * r", "# demo", "print(area(2))", "print(area(3))"]
m, n = len(old), len(new)
c = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1): # suffix version: c[i][j] = LCS of old[i:], new[j:]
for j in range(n - 1, -1, -1):
c[i][j] = c[i + 1][j + 1] + 1 if old[i] == new[j] else max(c[i + 1][j], c[i][j + 1])
i = j = 0
while i < m or j < n:
if i < m and j < n and old[i] == new[j]:
print(" " + old[i]); i += 1; j += 1
elif i < m and (j == n or c[i + 1][j] >= c[i][j + 1]):
print("- " + old[i]); i += 1 # deletions first, as diff prints them
else:
print("+ " + new[j]); j += 1+ import math
def area(r):
- pi = 3.14
- return pi * r * r
+ return math.pi * r * r
# demo
print(area(2))
+ print(area(3))
This version fills the table over suffixes instead of prefixes, so the walk can print the lines from top to bottom. Either direction gives a valid LCS DP; choosing the one that suits the reconstruction is a small but typical design decision. Try the practice problem Longest Common Subsequence next.
Test yourself
What is the length of an LCS of ABCAB and BACBA?
- 2
- 3
- 4
- 5
If , which entries does depend on?
- Only
- and
- All entries in row
- and
How much space does computing only the LCS length of strings of lengths need?