Longest common subsequence
how it works
The idea on crate and cart, the words the books this site follows use for edit distance (volume three, chapter 40). Then the whole method on the watch page's first example, seat and eats.
A subsequence of a word is some of its letters, kept in order, with gaps allowed: cat is a subsequence of crate, skipping r and e. A common subsequence is one of both words. The longest common subsequence is the most letters two words share this way. Crate and cart share 3: c, r and t, or c, a and t. To be sure nothing longer exists, fill a table. Each row stands for a start of crate, the empty start first, and each column for a start of cart. A cell holds the most letters its row's start and its column's start share in order. The first row and column hold 0, as an empty start shares nothing. Fill the other cells row by row. Compare the last letters of the cell's two starts. If they are the same, use that letter: write 1 more than the cell up and to the left. If not, shared letters cannot use both. Each would have to be the last shared letter, and that is one letter, not two different ones (section 4, question 4). So leave one out. Write the larger of the cell above, which leaves out the row's letter, and the cell to the left, which leaves out the column's. For cr and cart, r is not t. Above, c and cart, holds 1. To the left, cr and car, holds 2. So write 2. For crat and cart, t is t. Up and to the left, cra and car, holds 2, so write 3. The last cell is the answer: 3 for crate and cart. To see which letters, read back from the last cell. On a match, step up and to the left and take the letter. If not, step to the cell above or to the left that holds the same number. Stop at the first row or column. Where both hold it, either works: at cra and car, stepping up reads c, r and t, and stepping left reads c, a and t. This page counts cells, one for each cell the rule fills, not the first row and column: 20 for crate and cart, as the watch page counts. The code below fills the same table and gives back the last cell, how many letters. Reading the letters back, the second half of its last step, is left out.
| start | - | c | ca | car | cart |
|---|---|---|---|---|---|
| - | 0 | 0 | 0 | 0 | 0 |
| c | 0 | 1 | 1 | 1 | 1 |
| cr | 0 | 1 | 1 | 2 | 2 |
| cra | 0 | 1 | 2 | 2 | 2 |
| crat | 0 | 1 | 2 | 2 | 3 |
| crate | 0 | 1 | 2 | 2 | 3 |
| cell | holds | step to | letter |
|---|---|---|---|
| crate and cart | 3 | above | - |
| crat and cart | 3 | up-left | t |
| cra and car | 2 | above | - |
| cr and car | 2 | up-left | r |
| c and ca | 1 | left | - |
| c and c | 1 | up-left | c |
step 1 of 18
Find the most letters seat and eats share in the same order. With an empty start nothing is in common, so the first row and column are 0.
what it remembers to know where it is
- letters compared
- not yet
- longest in this cell
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 18
s is not e, so keep the longer of above, 0, and to the left, 0. Write 0.
what it remembers to know where it is
- letters compared
- s e
- longest in this cell
- 0
step 5 of 18
Both letters are s, so this cell has one more in common than the cell up and to the left. Write 1.
what it remembers to know where it is
- letters compared
- s s
- longest in this cell
- 1
step 6 of 18
Both letters are e, so this cell has one more in common than the cell up and to the left. Write 1.
what it remembers to know where it is
- letters compared
- e e
- longest in this cell
- 1
step 11 of 18
Both letters are a, so this cell has one more in common than the cell up and to the left. Write 2.
what it remembers to know where it is
- letters compared
- a a
- longest in this cell
- 2
step 16 of 18
Both letters are t, so this cell has one more in common than the cell up and to the left. Write 3.
what it remembers to know where it is
- letters compared
- t t
- longest in this cell
- 3
step 17 of 18
t is not s, so keep the longer of above, 2, and to the left, 3. Write 3.
what it remembers to know where it is
- letters compared
- t s
- longest in this cell
- 3
step 18 of 18
Done: seat and eats share 3 letters in the same order, such as eat. The marked cells are the way back.
what it remembers to know where it is
- letters compared
- not yet
- longest in this cell
- 3
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- the first row and column: with an empty start, nothing is in commonPython line 9
- for each other cell, row by row, compare the two letters it stands forPython lines 10, 11 and 12
- the same letter, so one more than the cell up and to the leftPython line 13
- different: the longer of the cell above and the cell to the leftPython lines 14 and 15
- the last cell is the length, and following the cells back reads the lettersPython line 16
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def longest_common_subsequence(a, b):
"""The most letters words a and b share in the same order.
The letters need not be side by side, only in the same order.
a and b are words of any length. Returns how many letters.
"""
m, n = len(a), len(b)
# cell[i][j]: the most letters a's first i and b's first j share in order
cell = [[0] * (n + 1) for _ in range(m + 1)] # first row and column: 0
for i in range(1, m + 1): # each other cell, row by row
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]: # the same last letter: use it
cell[i][j] = cell[i - 1][j - 1] + 1 # 1 more than up-left
else: # leave one letter out: the larger of above and left
cell[i][j] = max(cell[i - 1][j], cell[i][j - 1])
return cell[m][n] # the last cell
how it scales
The plot counts the cells the method fills on two words of letters each, measured from 10 to 100,000 letters.
Each mark across or up is ten times the one before. The line climbs two marks up for each mark across: 10,000 cells at 100 and 1,000,000 at 1,000: ten times the letters, 100 times the cells. Here the cost is the cells, and a slope of 2 means they grow as , as section 4's question 1 derives. Twice the letters make 4 times the cells.
cells filled, ten times more at each mark up
, how many letters the second word has, ten times more at each mark to the right
- two words of letters each, whatever their letterssolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
| cells filled | time | |
|---|---|---|
| 1,000 | 1,000,000 | about 1 millisecond |
| 100,000 | 10,000,000,000 | about 10 seconds |
| 10,000,000 | 100,000,000,000,000 | about 1.2 days |
The cells filled are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count longest common subsequence's cells yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each n from 10 to 100,000 it prints
the cells the method fills on two words of n letters each. The counts are
the same on any computer, whatever the letters; only the time differs.
"""
def longest_common_subsequence(a, b):
"""The most letters words a and b share in the same order.
The letters need not be side by side, only in the same order.
a and b are words of any length. Returns how many letters.
"""
m, n = len(a), len(b)
# cell[i][j]: the most letters a's first i and b's first j share in order
cell = [[0] * (n + 1) for _ in range(m + 1)] # first row and column: 0
for i in range(1, m + 1): # each other cell, row by row
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]: # the same last letter: use it
cell[i][j] = cell[i - 1][j - 1] + 1 # 1 more than up-left
else: # leave one letter out: the larger of above and left
cell[i][j] = max(cell[i - 1][j], cell[i][j - 1])
return cell[m][n] # the last cell
def count(a, b):
"""How many cells the method fills: each letter of a makes a row, with
one cell for each letter of b, whatever the letters."""
cells = 0
for _ in a: # a row for each letter of a
cells += len(b) # a cell in it for each letter of b
return cells
LETTERS = "abcdefghijklmnopqrstuvwxyz"
def plot_words(n):
"""The plot's two words of n letters: the first from a, the second
from n, round the alphabet."""
first = "".join(LETTERS[k % 26] for k in range(n))
second = "".join(LETTERS[(13 + k) % 26] for k in range(n))
return first, second
if __name__ == "__main__":
print(f"{'n':>7} {'cells':>12}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
print(f"{n:>7} {count(*plot_words(n)):>12}")
best, worst and average
Best, worst and average usually name different inputs of one size. Here the size is , the second word's length, and this page gives the first word letters too. Then every pair fills the same cells, whatever its letters. So the grid below has one column, under the name worst, and no average is worked out. In it, from 1 up means for any of 1 or more.
A case is one kind of input: here, which letters. A bound says how fast its cost grows as the words grow.
The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. With its first row and column, the table holds numbers, as question 2 works out: at 1,000 letters each, 1,000,000 plus 2,001, and the 2,001 hardly matters. So how a cost grows is what tells one method from another, and the bounds keep just that.
| worsttwo words of letters each, whatever their letters | |
|---|---|
| cells filled | , from 1 up |
| how the cells filled grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
extra memory: A table of one number for each pair of starts, or two rows for how many letters alone.
Extra memory is the room it needs on top of the input itself, while it runs.
| first word | second word | cells | longest |
|---|---|---|---|
| arm | arm | 9 | 3 |
| arm | ram | 9 | 2 |
| arm | dog | 9 | 0 |
| n | cells | numbers held |
|---|---|---|
| 1 | 1 | 4 |
| 2 | 4 | 9 |
| 3 | 9 | 16 |
| 7 | 49 | 64 |
| 100 | 10,000 | 10,201 |
| 1,000 | 1,000,000 | 1,002,001 |
where the formula comes from
Five questions, each worked line by line. Question 1 is the count the plot draws.
the move: a row for each letter
the line:order - r ra ram - given given given given a given 1 2 3 ar given 4 5 6 arm given 7 8 9 Arm and ram, each cell numbered in the order it is filled, row by row. Given cells are written first, not counted. 3 rows of 3, 9 cells. why it is allowed: Each letter of the first word has a row, and each row fills one cell for each letter of the second. Crate and cart fill 5 times 4, 20 cells.
the move: both of n letters
the line:why it is allowed: Here the first word has letters too, so is . For 3, 3 times 3, which is 9.
guess it, thenthe move: write it shorter
the line:why it is allowed: times is written , read squared. For 3, 9.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3, as a number is at most itself.
guess it, thenthe move: read the bound
the line:why it is allowed: means at most a fixed multiple of , from some on, and reads is in. By line 4, is at most 1 times , from 1 up.
guess it, thenthe move: a floor
the line:why it is allowed: By line 3, as a number is at least itself.
guess it, thenthe move: read the bound
the line:why it is allowed: means at least a fixed multiple of , above 0, from some on. By line 6, is at least 1 times , from 1 up.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 7 bound by the same growth. means both.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: count the rows and columns
the line:start - r ra ram - 0 0 0 0 a 0 0 1 1 ar 0 1 1 1 arm 0 1 1 2 Arm and ram, 4 rows of 4 numbers, 16 in all. The first row and column count, though no step fills them. why it is allowed: A row for the empty start, then one for each letter of the first word, so rows. The columns are the same for the second word. For 3, 4 times 4, which is 16.
the move: multiply out
the line:why it is allowed: times , the filled cells; twice, the first row and the first column past the corner; 1 times 1, the corner, the empty start against the empty start. For 3, 9 + 6 + 1, which is 16.
guess it, thenthe move: a ceiling
the line:why it is allowed: From 1 up, is at most , and so is 1, so is at most 3 lots of , and line 2's sum at most 4 lots. For 3, 16 is at most 36.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3, with the fixed multiple 4.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2: take away from , and is left, which is less. For 3, 16 is at least 9.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: what a cell reads
the line:row - r ra ram a 0 0 1 1 ar 0 1 1 ? Arm and ram, filling the last cell of row ar. r is not m, so it reads 1 above and 1 to the left, both in these two rows, and writes 1. why it is allowed: The cells above and up-left are in the row above, and the left is in the cell's own row. So once a row is full, the rows above it are never read again.
the move: keep two rows
the line:why it is allowed: So keep two rows of numbers, one for each column, as question 2 counts: the row above and the row being filled, reused in turn. For 3, 8 numbers, against the table's 16.
guess it, thenthe move: but not the letters
the line:why it is allowed: On crate and cart, reading back climbs through every row, from crate up to the empty row, as section 1's reading back shows. Two rows keep only crat and crate. So two rows give how many letters, but not always which ones, as the books note for edit distance (volume three, chapter 40).
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: the promise
the line:why it is allowed: This is what to prove. Lines 2 to 10 prove it, cell by cell, in the order the cells are filled.
the move: it starts right
the line:why it is allowed: An empty start shares no letter, so each holds 0, as the method writes.
guess it, thenthe move: suppose so far
the line:why it is allowed: Cells are checked in the order they are filled, after line 2's first row and column. So when a cell's turn comes, the three it may read, above, to the left and up and to the left, are checked already. In question 1's picture, cell 5 may read cells 1, 2 and 4. So suppose each of them holds the most.
guess it, thenthe move: shared letters are pairs
the line:Am, shared by arm and ram. Each line joins a letter's place in arm to its place in ram, and the lines do not cross. why it is allowed: A shared letter is in both starts, so it has a place in each. Kept in order, their places climb in both, so no two lines cross.
guess it, thenthe move: the last letters
the line:Crat and cart share c, r and t. T is last in both words, so its line joins the two last letters. why it is allowed: Suppose shared letters use both last letters. Each is then the last shared letter of its start. By line 4 no two lines cross, so the two are joined to each other, and must be the same letter. Crat and cart share c, r and t: t is last in both, so t pairs with t. Crate and cart's c, r and t leave out crate's e.
guess it, thenthe move: so no more than
the line:why it is allowed: By line 5, one of three things happens. Shared letters leave out the row's last letter, so they are all shared by above's starts: at most above, by line 3. Or they leave out the column's: at most the left. Or they pair the two last letters, which by line 5 happens only on a match. Then the rest is shared by up-left's starts: at most up-left, plus 1 for the pair. For cr and cart, r is not t, so at most the larger of 1 and 2.
guess it, thenthe move: each is reached
the line:why it is allowed: By line 3, above's starts share as many letters as above holds. Above's starts are this cell's without the row's last letter, so this cell's starts share them too; the same for the left. On a match, take the most letters up-left's starts share, by line 3, and add the matching letter to both. For crat and cart, take c and a from cra and car, up and to the left, and add t: 3.
guess it, thenthe move: the most is the largest
the line:why it is allowed: By line 6, the most letters shared is no more than the largest of the three numbers, and by line 7 that largest is reached, so they are equal. For cr and cart, both are 2. When the last letters differ, that is the larger of above and the left, which the method writes. When they match, line 9 shows it is up-left + 1.
guess it, thenthe move: a match adds 1
the line:why it is allowed: Could above or the left beat up-left + 1? Above's starts share above's number of letters, by line 3. Take those letters, and leave out any that uses the column's last letter. At most one goes, as that letter is used at most once, and the rest is shared by up-left's starts: at most up-left, by line 3. So above is at most up-left + 1, and so is the left. So by line 8, the method's up-left + 1 is right. For crat and cart, up-left + 1 is 3, and above and the left hold 2 each.
guess it, thenthe move: every cell
the line:why it is allowed: By line 2, the first row and column are. By lines 3 to 9, each later cell is right once those before it are. So, filled in order, every cell is, the last included.
guess it, thenthe move: count them
the line:why it is allowed: Every number the table holds, each right by line 10: the same count as question 2's . For 3, 16.
guess it, then
try it with a small : at , line 11 gives , which you can work out by hand
the move: count the calls
the line:- first time
- asked before, and every call under it
Comparing ab and cd takes 11 calls. Each box is one call, joined to the call that asked for it. A dashed box asks again for a pair already worked out: a and c, asked twice, with the two below it. n calls 2 times the row above 2 to the n 0 1 - 1 1 3 2 2 2 11 6 4 3 39 22 8 4 139 78 16 5 503 278 32 Calls counted by running the plain method. Each row is more than 2 times the row above, so at least 2 to the n. why it is allowed: A call is one ask for a cell's answer. The first call counts 1. Its last letters differ, so it asks for above and to the left. Each makes all its own calls, as nothing is written down. A pair with an empty word asks for nothing.
the move: at least up-left's calls
the line:why it is allowed: In the picture, ab and cd asks for a and cd, above, and ab and c, to the left, and each of those asks for a and c, up-left. Above's own left is up-left, and the left's own above is up-left. So each makes all of up-left's calls, and more. When up-left has an empty word, above and the left have one too, and each makes 1 call, as up-left does.
guess it, thenthe move: put line 2 into line 1
the line:why it is allowed: By line 2, each of line 1's two cells makes at least up-left's calls, and up-left has letters each. For 3, 39 is at least 1 + 2 times 11, which is 23.
guess it, thenthe move: leave out the 1
the line:why it is allowed: Line 3 without the first call's 1. For 3, 39 is more than 22.
guess it, thenthe move: repeat from 0
the line:why it is allowed: 0 letters make 1 call, and no 2s multiplied together is 1. By line 4, each extra letter more than doubles the calls: for 3, more than 2 (3 calls), so more than 4 (11), so more than 8 (39).
guess it, thenthe move: write it shorter
the line:why it is allowed: 2s multiplied together is written ; name it . So the calls are at least . For 10, at least 1,024, and counted, 369,511, against the table's 100 cells.
guess it, then
try it with a small : at , line 6 gives , which you can work out by hand
count it yourself
Arm and ram, step by step. Each cell filled adds 1 to the count on its own step.
| step | what happens | cells filled |
|---|---|---|
| 1 | Find the most letters arm and ram share in the same order. With an empty start nothing is in common, so the first row and column are 0. | 0 |
| 2 | a is not r, so keep the longer of above, 0, and to the left, 0. Write 0. | 1 |
| 3 | Both letters are a, so this cell has one more in common than the cell up and to the left. Write 1. | 2 |
| 4 | a is not m, so keep the longer of above, 0, and to the left, 1. Write 1. | 3 |
| 5 | Both letters are r, so this cell has one more in common than the cell up and to the left. Write 1. | 4 |
| 6 | r is not a, so keep the longer of above, 1, and to the left, 1. Write 1. | 5 |
| 7 | r is not m, so keep the longer of above, 1, and to the left, 1. Write 1. | 6 |
| 8 | m is not r, so keep the longer of above, 1, and to the left, 0. Write 1. | 7 |
| 9 | m is not a, so keep the longer of above, 1, and to the left, 1. Write 1. | 8 |
| 10 | Both letters are m, so this cell has one more in common than the cell up and to the left. Write 2. | 9 |
| 11 | Done: arm and ram share 2 letters in the same order, such as am. The marked cells are the way back. | 9 |
In all, 9 cells filled. The formula from section 4, , gives at : the same.
where you meet it
The books meet it in every diff, a list of what changed between two versions of a file (volume three, chapter 40).
What changed in a file
James Hunt and Douglas McIlroy wrote diff, the program that lists how two files differ, and explained how it works in a 1976 report. Diff treats each line as one letter and finds a longest common subsequence of the two files' lines. Those lines stay; every other line was deleted or added.
source: J. W. Hunt and M. D. McIlroy, An algorithm for differential file comparison (opens in a new tab), Bell Laboratories Computing Science Technical Report 41, 1976
Versions of a project
Git, a tool that keeps every version of a project's files, shows the changes between two versions as a diff. Its documentation lists four diff algorithms to choose from. Two tools can show different changes for the same files, the books note, as they break ties differently (volume three, chapter 40). Where two choices are equally good, as the cell above and the cell to the left at cra and car in section 1, each tool picks its own.
source: the books' volume three, chapter 40, and the Git documentation on its diff algorithm option, git diff (opens in a new tab)
The letters in little space
Two rows give how many letters but not always which, as question 3 shows. In a 1975 paper, Daniel Hirschberg showed how to find the letters too, keeping only a few rows. Cut the first word in half, find where a longest answer crosses the middle, and solve each half the same way. It fills about twice the cells, as the books note (volume three, chapter 40).
source: D. S. Hirschberg, A linear space algorithm for computing maximal common subsequences (opens in a new tab), Communications of the ACM 18, 1975, and the books' volume three, chapter 40
what is used instead
Hunt and McIlroy's diff did not fill every cell. It looked only at pairs of lines that match, and on everyday files it ran far faster than a method that fills every cell. Their report measured files of 3,500 lines: a quarter to three quarters of a minute, against about 5 minutes for a faster version of Hirschberg's method above.
how it compares
The plain method asks for each cell it needs as a call, with no table. So on many words, such as two with no letter in common, it works the same cells out again and again. A memo keeps each answer once worked out, as the page on solving each smaller problem once shows. The table fills every cell once, row by row, with no calls, and two rows are enough for how many letters alone. Edit distance fills the same kind of table, counting edits instead of shared letters, as the books note (volume three, chapter 40).
| way | work, 8 letters each | numbers kept |
|---|---|---|
| plain method | 25,739 calls | none |
| with a memo | 129 calls | 80 |
| the table | 64 cells | 81 |
| two rows | 64 cells | 18 |