TExcelTAD

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 X=x1x2⋯xmX = x_1 x_2 \cdots x_m 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 XX and YY is a subsequence of both. The problem: given XX of length mm and YY of length nn, find a common subsequence of maximum length.

Brute force would list the 2m2^m subsequences of XX and test each against YY in O(n)O(n) time: Θ(n2m)\Theta(n 2^m). The DP below takes Θ(mn)\Theta(mn).

Optimal substructure

Write Xi=x1⋯xiX_i = x_1 \cdots x_i for the prefix of length ii (so X0X_0 is empty), and likewise YjY_j. Let Z=z1⋯zkZ = z_1 \cdots z_k be any LCS of XmX_m and YnY_n. Look at the last characters.

  1. If xm=ynx_m = y_n, then zk=xm=ynz_k = x_m = y_n, and Zk−1Z_{k-1} is an LCS of Xm−1X_{m-1} and Yn−1Y_{n-1}.
  2. If xm≠ynx_m \ne y_n and zk≠xmz_k \ne x_m, then ZZ is an LCS of Xm−1X_{m-1} and YnY_n.
  3. If xm≠ynx_m \ne y_n and zk≠ynz_k \ne y_n, then ZZ is an LCS of XmX_m and Yn−1Y_{n-1}.
Proof

(1) If zk≠xmz_k \ne x_m, appending xm=ynx_m = y_n to ZZ would give a common subsequence of length k+1k + 1, contradicting maximality; so zk=xmz_k = x_m. Then Zk−1Z_{k-1} is a common subsequence of Xm−1X_{m-1} and Yn−1Y_{n-1} of length k−1k - 1. If those prefixes had a longer common subsequence WW, then WW followed by xmx_m would be a common subsequence of XX and YY longer than kk, a contradiction.

(2) If zk≠xmz_k \ne x_m, then ZZ does not use xmx_m, so it is a common subsequence of Xm−1X_{m-1} and YY. A longer one would also be a common subsequence of XX and YY, contradicting maximality of ZZ. (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 c[i,j]c[i, j] the LCS length of XiX_i and YjY_j:

c[i,j]={0if i=0 or j=0,c[i−1,j−1]+1if i,j>0 and xi=yj,max⁡(c[i−1,j], c[i,j−1])if i,j>0 and xi≠yj.c[i, j] = \begin{cases} 0 & \text{if } i = 0 \text{ or } j = 0, \\ c[i-1, j-1] + 1 & \text{if } i, j > 0 \text{ and } x_i = y_j, \\ \max(c[i-1, j],\ c[i, j-1]) & \text{if } i, j > 0 \text{ and } x_i \ne y_j. \end{cases}

There are (m+1)(n+1)(m+1)(n+1) 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.

text
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 out

The 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).

python · try it yourself
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 mnmn cells takes O(1)O(1) time, so LCS-LENGTH runs in Θ(mn)\Theta(mn) time and space, and TRACE-LCS in O(m+n)O(m + n), since every step decreases ii or jj. If only the length is needed, two rows suffice, because row ii reads only row i−1i - 1: O(min⁡(m,n))O(\min(m, n)) 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.

python · try it yourself
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 nn, about 0.650.65 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.

cpp · try it yourself
#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 O((m+n)D)O((m + n) D) time when the files differ in DD lines, but the DP is the idea.

python · try it yourself
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?

  1. 2
  2. 3
  3. 4
  4. 5

If xi≠yjx_i \ne y_j, which entries does c[i,j]c[i, j] depend on?

  1. Only c[i−1,j−1]c[i-1, j-1]
  2. c[i−1,j]c[i-1, j] and c[i,j−1]c[i, j-1]
  3. All entries in row i−1i - 1
  4. c[i−1,j−1]c[i-1, j-1] and c[i−1,j]c[i-1, j]

How much space does computing only the LCS length of strings of lengths m≥nm \ge n need?

  1. O(mn)O(mn)
  2. O(m)O(m)
  3. O(n)O(n)
  4. O(1)O(1)