Search

Search papers and lessons

Longest Common Subsequence

Level 2 · 13 min read

The longest common subsequence of two sequences is the longest run of items they share in the same order, and a table finds its length in time proportional to the product of their lengths.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Algorithms
  • Calculus
  • ReadReady to readNot yet

TL;DR

A subsequence is what you get by deleting some items from a sequence and keeping the rest in their original order. A longest common subsequence (LCS) of two sequences is the longest list that is a subsequence of both. For the strings "cat" and "cut" it is "ct", which has length 2. The idea sits under tools that show what changed between two versions of a file, and a dynamic programming table finds its length in time proportional to the product of the two lengths.

Builds on: Dynamic Programming, Recursion · Leads to: Sequence Alignment, Version Control

Where it's used

Showing changes in files. The diff command lists which lines were removed and which were added between two versions of a file. Its core is an LCS of the lines: the lines that stay in place form the common subsequence, and every other line is a deletion or an addition. The Unix diff tool, built in the 1970s, worked this way.

Comparing biological sequences. Two DNA or protein sequences are compared by asking which stretches they share in order. Full Sequence Alignment scores matches and gaps with weights rather than only counting shared items, but it fills the same kind of table.

Rough measures of shared text. The length of an LCS, divided by the length of the shorter text, gives a quick sense of how much of one passage appears, in order, inside another. It ignores how far apart the shared pieces sit, so it is a rough measure rather than a proof of copying.

How it works

Take two short strings, a = "cat" and b = "cut". The table holds, for every pair of prefixes, the length of the best common subsequence of that pair. The answer for the full strings is the last cell.

  1. Name the prefixes. Let L(i, j) be the length of the LCS of the first i characters of a and the first j characters of b. The answer is L(3, 3). The values go in a table with one row per i and one column per j. Check: L(3, 3) is the cell for the full "cat" against the full "cut".

  2. Set the border to zero. An empty prefix shares nothing with anything, so row 0 and column 0 are all 0. Check: L(0, 2) = 0, because the empty string has no characters to match.

  3. If the last characters match, extend. For a cell (i, j), compare the last character of each prefix. If they are equal, the LCS can end with that shared character, so the cell is one more than the cell diagonally up and to the left. The cell for "t" against "t" in the bottom-right corner gives L(2, 2) + 1 = 1 + 1 = 2. Check: "c" against "c" gives 0 + 1 = 1.

  4. If they differ, take the better of dropping one. The two last characters cannot both be in the LCS. So either drop the last character of a, which looks at the cell above, or drop the last character of b, which looks at the cell to the left. Keep the larger of those two. For "c" in a against "u" in b, the cell is max(0, 1) = 1. Check: the chosen value is never larger than either neighbour.

  5. Fill row by row and read the answer. Each cell only looks above or to the left, so those cells are already filled. The full table for "cat" and "cut" is:

    (empty)cut
    (empty)0000
    c0111
    a0111
    t0112

    The bottom-right cell is 2. To find the subsequence itself, walk back from that cell: each diagonal step that came from a match is one shared character. That gives "c" then "t", so the LCS is "ct". Check: "ct" is in "cat" at positions 1 and 3, and in "cut" at positions 1 and 3.

The decision in steps 3 and 4 is the whole method:

flowchart TD
  A["Look at cell (i, j)"] --> B{"Do a_i and b_j match?"}
  B -- "Yes" --> C["Take L(i-1, j-1) + 1"]
  B -- "No" --> D["Take the larger of L(i-1, j) and L(i, j-1)"]
  C --> E["Store the value in cell (i, j)"]
  D --> E

The math

Definition: Longest common subsequence

Let a have length m and b have length n. Let a_i be the i-th character of a and b_j the j-th character of b. Write L(i, j) for the length of the longest common subsequence of the first i characters of a and the first j characters of b. Then

L(0,j)=0,L(i,0)=0L(0,j)=0, \qquad L(i,0)=0L(i,j)={L(i−1,j−1)+1if ai=bjmax⁡(L(i−1,j),  L(i,j−1))if ai≠bjL(i,j)=\begin{cases} L(i-1,j-1)+1 & \text{if } a_i = b_j \\ \max\bigl(L(i-1,j),\; L(i,j-1)\bigr) & \text{if } a_i \neq b_j \end{cases}

The length of the LCS of a and b is L(m, n).

The first line is the border of the table. The second line is the match rule and the mismatch rule, which are the two cases of the walkthrough.

Step 1 in symbols

L(i, j) is defined for every pair of prefixes, so the table has (m + 1)(n + 1) cells. The answer is the cell L(m, n).

Step 2 in symbols

The border values L(0, j) = 0 and L(i, 0) = 0 are the base cases of the recursion. They come from the fact that a subsequence of an empty string is only the empty string, which has length 0. This is the anchor that the recursive definition needs.

Step 3 in symbols

Suppose a_i = b_j. Take a longest common subsequence of the two prefixes. If it uses both last characters, the rest is a common subsequence of the shorter prefixes, so its length is at most L(i-1, j-1) + 1. If it does not use both, its length is at most max(L(i-1, j), L(i, j-1)), which is never more than the first case. So the value L(i-1, j-1) + 1 is achieved and is the largest. Using both last characters is always safe here because they are equal.

Step 4 in symbols

Suppose a_i differs from b_j. Then a longest common subsequence of the prefixes cannot use both last characters, since they are different. So it omits a_i, which gives a common subsequence of the first i - 1 characters of a and the first j characters of b, or it omits b_j, which gives a common subsequence of the first i characters of a and the first j - 1 characters of b. Taking the larger of the two lengths gives the answer.

Step 5 in symbols

The table has (m + 1)(n + 1) cells, and each takes constant work once its neighbours are known. So the time is O(mn), which is the cost of filling the table. Computing only the length needs just the previous row at any time, so the memory can be O(min(m, n)). Recovering the subsequence needs the full table, or a pointer per cell that records which move was taken.

Worked examples

Example
Example 1: order matters

Setup: a = "ab" and b = "ba". Both strings have two letters, and they share the letters a and b.

  1. Compare the last characters: a_2 = "b" and b_2 = "a". They differ, so use the mismatch rule.
  2. Option one: drop the last character of a, giving L(1, 2). That is the LCS of "a" and "ba", which is "a", so the length is 1.
  3. Option two: drop the last character of b, giving L(2, 1). That is the LCS of "ab" and "b", which is "b", so the length is 1.
  4. Take the larger: L(2, 2) = max(1, 1) = 1.
  5. Check that no common subsequence of length 2 exists. "ab" is not in "ba", because in "ba" the "b" comes before the "a".

Interpretation: the same letters in a different order do not make a common subsequence. The answer is 1, not 2.

Example
Example 2: the standard case

Setup: a = "ABCBDAB" (m = 7) and b = "BDCABA" (n = 6). The table has 8 rows and 7 columns, counting the border.

  1. Fill the row for the first character of a, which is "A". It matches the letter "A" at positions 4 and 6 of b. So the row, read left to right over prefixes of b of length 0 to 6, is 0, 0, 0, 0, 1, 1, 1.
  2. Fill the row for "AB" (the first two characters of a). At the end of b, the prefix "BDCAB" contains "AB" in order, so L(2, 5) = 2. The row is 0, 1, 1, 1, 1, 2, 2.
  3. Carry on row by row. The last row, for the full a, ends with the value 4 in the last column.
  4. Read the answer: L(7, 6) = 4. One common subsequence of length 4 is "BCBA": B, C, B, A appear in order in both strings. Another is "BDAB", so the answer is not unique.
  5. Interpretation: out of 7 characters in a and 6 in b, at most 4 can be kept in order, so at least 3 deletions from a and 2 from b are needed to make them line up.

Try it: compute the LCS of "ABC" and "CBA" using the same rule. Answer: 1. The letters A, B and C each appear in both, but no two of them appear in the same order in both strings: "AB" is in "ABC" but in "CBA" the B comes before the A, and "BC" is in "ABC" but in "CBA" the C comes first. So any common subsequence has one letter.

Example
Example 3: comparing two versions of a document

Setup: each line of a document is one item. The old version has four lines, "title", "intro", "body", "end". The new version has four lines, "title", "body", "summary", "end".

  1. List the lines that appear in both versions, in order: "title", "body", "end". The line "intro" is missing from the new version, and "summary" is missing from the old one.
  2. Check that no longer list exists. Adding "intro" would need it in the new version, which it does not have. So the LCS length is 3.
  3. Count the changes. Old lines not kept: 4 - 3 = 1 ("intro"), a deletion. New lines not kept: 4 - 3 = 1 ("summary"), an addition.
  4. Check with the formula: the number of edits is m + n - 2L = 4 + 4 - 2 * 3 = 2, which matches one deletion plus one addition.
  5. Interpretation: a diff tool shows "-intro" and "+summary". The more lines the LCS keeps, the smaller the diff.

Try it: the old file is the lines a, b, c, d, e and the new file is a, c, e, f. How many edits does the diff show? Answer: 3. The common lines in order are a, c, e, so L = 3. The edits are m + n - 2L = 5 + 4 - 6 = 3: delete b, delete d and add f.

Common mistakes and tradeoffs

It is tempting to think a longest common subsequence must be a contiguous block. In fact a subsequence may skip items. In "abcd" and "bcxd", the common subsequence "bcd" has length 3, while the longest common substring, which must be contiguous, is "bc" with length 2.

It is tempting to think you can match greedily: scan both strings once and take each match as soon as you see it. In fact that can lose the best answer. For "abc" and "bca", the first "a" in the first string matches the "a" at the end of the second, and then nothing is left. The greedy answer is 1. The true LCS is "bc", with length 2, which the table finds because it keeps the best value for every pair of prefixes.

It is tempting to think the LCS is unique. In fact there can be many. "ABCBDAB" and "BDCABA" have the common subsequences "BCBA", "BDAB" and "BCAB", all of length 4.

It is tempting to think the LCS length is the edit distance. In fact the two differ as soon as substitutions are allowed. For "ab" and "cd", the LCS is empty, but the edit distance is 2, because two substitutions change one string into the other. The formula m + n - 2L counts only insertions and deletions, so it equals the edit distance only when substitutions are not allowed.

It is also tempting to store the full table when only the length is needed. In fact one row at a time is enough for the length. The full table is needed only to recover the subsequence.

When to use it: comparing two sequences where order matters and the changes are insertions and deletions, such as line-based diffs. When not to use it: when substitutions matter, which calls for Edit Distance, or when matches should earn different scores and gaps should cost something, which calls for Sequence Alignment. Alternatives: Myers' O(ND) algorithm, which is fast when the two sequences are mostly alike, finds the same kind of diff in time that depends on the number of changes rather than on the full product of the lengths.

History

In the 1970s, comparing two files became a practical problem for programmers. In 1975 Dan Hirschberg showed how to recover a longest common subsequence while using only linear memory, which matters for long files. In 1976 James Hunt and Douglas McIlroy described a file comparison method built on the LCS, and it became the basis of the Unix diff tool. In 1986 Eugene Myers published the O(ND) algorithm, which made diffs fast for similar files. The dynamic programming table used here is the standard method that all of these refine, and it is an example of dynamic programming: a problem is split into prefixes, and each answer is stored and reused.

Recap

  • A subsequence keeps the order of the original but may skip items, and the LCS is the longest one shared by two sequences.
  • The table entry L(i, j) holds the answer for every pair of prefixes, and the border is all 0.
  • A match extends the diagonal cell by 1. A mismatch takes the better of dropping the last character of either string.
  • The answer is the bottom-right cell, and the time is O(mn).
  • With only insertions and deletions, the number of edits between two sequences is m + n - 2L, which is how diff tools count changes.

Read next: Edit Distance, which allows substitutions and so gives a different count, and Sequence Alignment, which weights the matches and gaps.

Check yourself

QuestionRecall: what is the difference between a subsequence and a substring?Show answer
A subsequence keeps the order of the original but may skip items, so its items need not be next to each other. A substring is a contiguous block with no gaps. Every substring is a subsequence, but not every subsequence is a substring. The LCS uses subsequences, which is why it can be longer than the longest common substring.
QuestionComputation: what is the length of the longest common subsequence of ABCDGH and AEDFHR? Give the number and one sequence that achieves it.Show answer
The answer is 3, achieved by ADH. Only three letters appear in both strings: A, D and H. Any common subsequence can use only these letters, so its length is at most 3. The sequence A, D, H appears in order in both: in the first string at positions 1, 4 and 6, and in the second at positions 1, 3 and 5.
QuestionWhy: when the last characters of the two prefixes differ, why does the table take the maximum of two cells rather than adding one to a single cell?Show answer
When the last characters differ, they cannot both be in the LCS. So the best answer either leaves out the last character of the first string or leaves out the last character of the second. Adding one to a single cell would only be right when the two characters match, because only then is there a shared item to count. Taking the maximum covers both ways of dropping an item and keeps the larger result.
QuestionApplied: a diff tool compares an old file of 10 lines with a new file of 12 lines. Its LCS keeps 7 lines. How many lines are deleted, how many are added, and how many edits in total?Show answer
Lines deleted: 10 - 7 = 3. Lines added: 12 - 7 = 5. Total edits: 3 + 5 = 8, which matches the formula 10 + 12 - 2 * 7 = 8. The diff would show 3 removed lines and 5 added lines.

Sources