Skip to content

Longest common subsequence

planning ahead

Level 2 of 3

Also called LCS and Longest common subsequence, by dynamic programming.

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.

crt: 3 letters in the same order in both1c2r3a4t5ec1a2r3t4cat: 3 letters in the same order in both1c2r3a4t5ec1a2r3t4
The two longest common subsequences of crate and cart. Each line joins a shared letter in crate to the same letter in cart. No two lines cross, so the order is kept.
start-ccacarcart
-00000
c01111
cr01122
cra01222
crat01223
crate01223
Crate and cart. Each row is a start of crate and each column a start of cart, and a dash is the empty start. The last cell holds 3, the answer.
cellholdsstep toletter
crate and cart3above-
crat and cart3up-leftt
cra and car2above-
cr and car2up-leftr
c and ca1left-
c and c1up-leftc
Reading back from the last cell, stepping up where above and the left both hold the number. Up and to the left takes a letter, and a dash means none. Read from the bottom: c, r and t.
Seat and eats: 8 moments of its 18 steps, the steps between them left for the watch page
  1. step 1 of 18

    eatsseat000000000

    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.

    watch from here

  2. step 2 of 18

    eatsseat0000000000

    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

    watch from here

  3. step 5 of 18

    eatsseat0000000001000

    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

    watch from here

  4. step 6 of 18

    eatsseat00000000010100

    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

    watch from here

  5. step 11 of 18

    eatsseat0000000001011110120

    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

    watch from here

  6. step 16 of 18

    eatsseat000000000101111012220123

    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

    watch from here

  7. step 17 of 18

    eatsseat0000000001011110122201233

    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

    watch from here

  8. step 18 of 18

    eatsseat0000000001011110122201233

    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.

    watch from here

the steps, in plain words
  1. the first row and column: with an empty start, nothing is in commonPython line 9
  2. for each other cell, row by row, compare the two letters it stands forPython lines 10, 11 and 12
  3. the same letter, so one more than the cell up and to the leftPython line 13
  4. different: the longer of the cell above and the cell to the leftPython lines 14 and 15
  5. 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 nn 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 n2n^2, as section 4's question 1 derives. Twice the letters make 4 times the cells.

cells filled, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

nn, how many letters the second word has, ten times more at each mark to the right

  • two words of nn 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
how long filling the cells takes, at a billion a second
nncells filledtime
1,0001,000,000about 1 millisecond
100,00010,000,000,000about 10 seconds
10,000,000100,000,000,000,000about 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 nn, the second word's length, and this page gives the first word nn 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 nn 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 n2+2n+1n^2 + 2n + 1 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
worsttwo words of nn letters each, whatever their letters
cells filledn2n^2, from 1 up
how the cells filled grow in each case
tight, Θ\ThetaΘ(n2)\Theta(n^2)
ceiling, OOO(n2)O(n^2)
floor, Ω\OmegaΩ(n2)\Omega(n^2)

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 wordsecond wordcellslongest
armarm93
armram92
armdog90
Three pairs of 3 letters, counted by the run. The longest common subsequence changes with the letters, and the cells do not, 3 times 3.
ncellsnumbers held
114
249
3916
74964
10010,00010,201
1,0001,000,0001,002,001
Two words of nn letters each. The table also holds its first row and column, as question 2 counts.

where the formula comes from

Five questions, each worked line by line. Question 1 is the count the plot draws.

Question 1: how many cells, CC, does the method fill on two words of nn letters, from 1 up?
  1. the move: a row for each letter

    the line:
    m letters and n letters:m×n cells\begin{gathered} m \text{ letters and } n \text{ letters:} \\ m \times n \text{ cells} \end{gathered}
    order-rraram
    -givengivengivengiven
    agiven123
    argiven456
    armgiven789
    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.

  2. the move: both of n letters

    the line:
    C=n×nC = n \times n

    why it is allowed: Here the first word has nn letters too, so mm is nn. For 3, 3 times 3, which is 9.

  3. the move: write it shorter

    the line:
    C=n2C = n^2

    why it is allowed: nn times nn is written n2n^2, read nn squared. For 3, 9.

  4. the move: a ceiling

    the line:
    C≤n2C \le n^2

    why it is allowed: By line 3, as a number is at most itself.

  5. the move: read the bound

    the line:
    C∈O(n2)C \in O(n^2)

    why it is allowed: O(n2)O(n^2) means at most a fixed multiple of n2n^2, from some nn on, and ∈\in reads is in. By line 4, CC is at most 1 times n2n^2, from 1 up.

  6. the move: a floor

    the line:
    C≥n2C \ge n^2

    why it is allowed: By line 3, as a number is at least itself.

  7. the move: read the bound

    the line:
    C∈Ω(n2)C \in \Omega(n^2)

    why it is allowed: Ω(n2)\Omega(n^2) means at least a fixed multiple of n2n^2, above 0, from some nn on. By line 6, CC is at least 1 times n2n^2, from 1 up.

  8. the move: both together

    the line:
    C∈Θ(n2)C \in \Theta(n^2)

    why it is allowed: Lines 5 and 7 bound CC by the same growth. Θ(n2)\Theta(n^2) means both.

try it with a small nn: at n=3n = 3, line 2 gives C=9C = 9, which you can work out by hand

Question 2: how many numbers, TT, does the table hold on two words of nn letters, from 1 up?
  1. the move: count the rows and columns

    the line:
    T=(n+1)×(n+1)T = (n + 1) \times (n + 1)
    start-rraram
    -0000
    a0011
    ar0111
    arm0112
    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 n+1n + 1 rows. The columns are the same for the second word. For 3, 4 times 4, which is 16.

  2. the move: multiply out

    the line:
    T=n2+2n+1T = n^2 + 2n + 1

    why it is allowed: nn times nn, the filled cells; nn 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.

  3. the move: a ceiling

    the line:
    T≤4n2T \le 4n^2

    why it is allowed: From 1 up, nn is at most n2n^2, and so is 1, so 2n+12n + 1 is at most 3 lots of n2n^2, and line 2's sum at most 4 lots. For 3, 16 is at most 36.

  4. the move: read the bound

    the line:
    T∈O(n2)T \in O(n^2)

    why it is allowed: By line 3, with the fixed multiple 4.

  5. the move: a floor

    the line:
    T≥n2T \ge n^2

    why it is allowed: By line 2: take 2n+12n + 1 away from TT, and n2n^2 is left, which is less. For 3, 16 is at least 9.

  6. the move: read the bound

    the line:
    T∈Ω(n2)T \in \Omega(n^2)

    why it is allowed: By line 5, with the fixed multiple 1.

  7. the move: both together

    the line:
    T∈Θ(n2)T \in \Theta(n^2)

    why it is allowed: Lines 4 and 6 bound TT by the same growth.

try it with a small nn: at n=3n = 3, line 1 gives T=16T = 16, which you can work out by hand

Question 3: if you want only how many letters, how many numbers, RR, do two rows keep, from 1 up?
  1. the move: what a cell reads

    the line:
    a cell reads only its own rowand the row above\begin{gathered} \text{a cell reads only its own row} \\ \text{and the row above} \end{gathered}
    row-rraram
    a0011
    ar011?
    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.

  2. the move: keep two rows

    the line:
    R=2(n+1)R = 2(n + 1)

    why it is allowed: So keep two rows of n+1n + 1 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.

  3. the move: but not the letters

    the line:
    reading back may needrows long gone\begin{gathered} \text{reading back may need} \\ \text{rows long gone} \end{gathered}

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

try it with a small nn: at n=3n = 3, line 2 gives R=8R = 8, which you can work out by hand

Question 4: why is every number in the table right, and how many is that? Let KK be how many, for two words of nn letters.
  1. the move: the promise

    the line:
    each cell holds the mostletters its two startsshare in order\begin{gathered} \text{each cell holds the most} \\ \text{letters its two starts} \\ \text{share in order} \end{gathered}

    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.

  2. the move: it starts right

    the line:
    the first row andcolumn are right\begin{gathered} \text{the first row and} \\ \text{column are right} \end{gathered}

    why it is allowed: An empty start shares no letter, so each holds 0, as the method writes.

  3. the move: suppose so far

    the line:
    suppose every cellbefore this one is right\begin{gathered} \text{suppose every cell} \\ \text{before this one is right} \end{gathered}

    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.

  4. the move: shared letters are pairs

    the line:
    each shared letter pairsa place in one start withone in the other, andno two lines cross\begin{gathered} \text{each shared letter pairs} \\ \text{a place in one start with} \\ \text{one in the other, and} \\ \text{no two lines cross} \end{gathered}
    am: 2 letters in the same order in both1a2r3mr1a2m3
    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.

  5. the move: the last letters

    the line:
    shared letters leave outa last letter, or pairthe two last letters\begin{gathered} \text{shared letters leave out} \\ \text{a last letter, or pair} \\ \text{the two last letters} \end{gathered}
    crt: 3 letters in the same order in both1c2r3a4tc1a2r3t4
    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.

  6. the move: so no more than

    the line:
    no more than the largestof above, left, andup-left+1 on a match\begin{gathered} \text{no more than the largest} \\ \text{of above, left, and} \\ \text{up-left} + 1 \text{ on a match} \end{gathered}

    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.

  7. the move: each is reached

    the line:
    each of these is reachedby letters both starts share\begin{gathered} \text{each of these is reached} \\ \text{by letters both starts share} \end{gathered}

    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.

  8. the move: the most is the largest

    the line:
    the most is the largestof these\begin{gathered} \text{the most is the largest} \\ \text{of these} \end{gathered}

    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.

  9. the move: a match adds 1

    the line:
    on a match, up-left+1is the largest\begin{gathered} \text{on a match, up-left} + 1 \\ \text{is the largest} \end{gathered}

    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.

  10. the move: every cell

    the line:
    every cell is right\text{every cell is right}

    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.

  11. the move: count them

    the line:
    K=(n+1)×(n+1)K = (n + 1) \times (n + 1)

    why it is allowed: Every number the table holds, each right by line 10: the same count as question 2's TT. For 3, 16.

try it with a small nn: at n=3n = 3, line 11 gives K=16K = 16, which you can work out by hand

Question 5: how fast must the plain method's calls grow? It asks for the same cells as calls, with no table. Take two words of nn letters with no letter in common, and let LL be a floor.
  1. the move: count the calls

    the line:
    calls for n letters each,from 1 up: 1+the callsof the two it asks for\begin{gathered} \text{calls for } n \text{ letters each,} \\ \text{from 1 up: } 1 + \text{the calls} \\ \text{of the two it asks for} \end{gathered}
    11 calls, 8 different pairs of startsabcdacd-cdac-ca-abcac-ca-ab-
    • 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.
    ncalls2 times the row above2 to the n
    01-1
    1322
    21164
    339228
    41397816
    550327832
    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.

  2. the move: at least up-left's calls

    the line:
    above and to the left each makeat least the calls of up-left\begin{gathered} \text{above and to the left each make} \\ \text{at least the calls of up-left} \end{gathered}

    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.

  3. the move: put line 2 into line 1

    the line:
    calls for n are at least 1+2×the calls for n−1\begin{gathered} \text{calls for } n \text{ are at least } 1 \\ + 2 \times \text{the calls for } n - 1 \end{gathered}

    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 n−1n - 1 letters each. For 3, 39 is at least 1 + 2 times 11, which is 23.

  4. the move: leave out the 1

    the line:
    calls for n are more than 2times the calls for n−1\begin{gathered} \text{calls for } n \text{ are more than } 2 \\ \text{times the calls for } n - 1 \end{gathered}

    why it is allowed: Line 3 without the first call's 1. For 3, 39 is more than 22.

  5. the move: repeat from 0

    the line:
    calls for n are at leastn 2s multiplied together\begin{gathered} \text{calls for } n \text{ are at least} \\ n \text{ 2s multiplied together} \end{gathered}

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

  6. the move: write it shorter

    the line:
    L=2nL = 2^n

    why it is allowed: nn 2s multiplied together is written 2n2^n; name it LL. So the calls are at least LL. For 10, at least 1,024, and counted, 369,511, against the table's 100 cells.

try it with a small nn: at n=3n = 3, line 6 gives L=8L = 8, 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.

arm, ram, every step written down
stepwhat happenscells filled
1Find 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
2a is not r, so keep the longer of above, 0, and to the left, 0. Write 0.1
3Both letters are a, so this cell has one more in common than the cell up and to the left. Write 1.2
4a is not m, so keep the longer of above, 0, and to the left, 1. Write 1.3
5Both letters are r, so this cell has one more in common than the cell up and to the left. Write 1.4
6r is not a, so keep the longer of above, 1, and to the left, 1. Write 1.5
7r is not m, so keep the longer of above, 1, and to the left, 1. Write 1.6
8m is not r, so keep the longer of above, 1, and to the left, 0. Write 1.7
9m is not a, so keep the longer of above, 1, and to the left, 1. Write 1.8
10Both letters are m, so this cell has one more in common than the cell up and to the left. Write 2.9
11Done: 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, n2n^2, gives C=9C = 9 at n=3n = 3: 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).

waywork, 8 letters eachnumbers kept
plain method25,739 callsnone
with a memo129 calls80
the table64 cells81
two rows64 cells18
Two words of 8 letters with no letter in common, each row counted by running the method. The memo never asks for the empty start against the empty start, so it keeps 80. A call and a cell are different steps, so read this for the size of each number.