DP on Strings

How to compare two strings with a table of prefixes to find the longest common subsequence and the edit distance, and what interviewers ask about them.

15 minLesson 5 of 6
On this page
  1. How the longest common subsequence table works
  2. Variants
  3. Pitfalls
  4. In the interview
  5. What to practise next

Dynamic programming on two strings fills a table in which cell [i][j] holds the answer for the first i characters of one string and the first j characters of the other. It solves problems that compare two strings, mainly the longest common subsequence (the longest sequence of characters that appears in both, in the same order but not necessarily next to each other) and the edit distance (the fewest single-character changes that turn one string into the other). You reach for it when a problem gives you two strings and asks how similar they are.

Without the table you would have to compare subsequences directly, and a string of length 20 already has over a million of them. The table works because every question about two strings reduces to the same question about two shorter prefixes, so each prefix pair only needs to be answered once.

How the longest common subsequence table works

Take the words ROAD and BOARD. Their longest common subsequence is OAD, with length 3. To find it, look at the last character of each word.

  • If the last characters match, as the final D does in ROAD and BOARD, you can use that character. The rest of the answer is the longest common subsequence of ROA and BOAR, plus 1.
  • If the last characters differ, at least one of them is not part of the answer. You drop the last character of one word or of the other, solve both smaller problems, and keep the larger result.

Both cases ask about shorter prefixes, so the table has one word down the side and the other across the top. Let L[i][j] be the length of the longest common subsequence of the first i characters of a and the first j characters of b.

  • When a[i − 1] == b[j − 1], L[i][j] = L[i − 1][j − 1] + 1.
  • Otherwise L[i][j] = max(L[i − 1][j], L[i][j − 1]).
  • Row 0 and column 0 are the empty prefix, so they are all 0.
  • Each cell depends on the cell above, the cell to the left and the cell diagonally up and to the left, as in DP on grids, so you fill the table row by row from left to right.
  • The answer is the bottom-right cell, L[len(a)][len(b)].

Because row 0 stands for the empty prefix, row i corresponds to the character a[i − 1]. The trace below fills the table for ROAD and BOARD.

Longest common subsequence of ROAD and BOARDUse the arrows or ← → keys
L[i][0] = 0 and L[0][j] = 0for i from 1 to len(a):  for j from 1 to len(b):    if a[i-1] == b[j-1]:      L[i][j] = L[i-1][j-1] + 1    else:      L[i][j] = max(L[i-1][j], L[i][j-1])return L[len(a)][len(b)]
  1. L[i][j]
    ""BOARD
    ""000000
    R0
    O0
    A0
    D0

    1The first row and the first column are 0, because an empty prefix has nothing in common with any other prefix. The rows are the letters of ROAD and the columns are the letters of BOARD.

  2. L[i][j]
    ""BOARD
    ""000000
    R00
    O0
    A0
    D0
    a prefix
    R
    b prefix
    B

    2R and B differ, so the cell is the larger of the cell above (0) and the cell to the left (0), which is 0.

  3. L[i][j]
    ""BOARD
    ""000000
    R000
    O0
    A0
    D0
    a prefix
    R
    b prefix
    BO

    3R and O differ, so the cell is the larger of the cell above (0) and the cell to the left (0), which is 0.

  4. L[i][j]
    ""BOARD
    ""000000
    R0000
    O0
    A0
    D0
    a prefix
    R
    b prefix
    BOA

    4R and A differ, so the cell is the larger of the cell above (0) and the cell to the left (0), which is 0.

  5. L[i][j]
    ""BOARD
    ""000000
    R00001
    O0
    A0
    D0
    a prefix
    R
    b prefix
    BOAR

    5R and R match, so the cell is the diagonal value 0 plus 1, which is 1.

  6. L[i][j]
    ""BOARD
    ""000000
    R000011
    O0
    A0
    D0
    a prefix
    R
    b prefix
    BOARD

    6R and D differ, so the cell is the larger of the cell above (0) and the cell to the left (1), which is 1.

  7. L[i][j]
    ""BOARD
    ""000000
    R000011
    O00
    A0
    D0
    a prefix
    RO
    b prefix
    B

    7O and B differ, so the cell is the larger of the cell above (0) and the cell to the left (0), which is 0.

  8. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001
    A0
    D0
    a prefix
    RO
    b prefix
    BO

    8O and O match, so the cell is the diagonal value 0 plus 1, which is 1.

  9. L[i][j]
    ""BOARD
    ""000000
    R000011
    O0011
    A0
    D0
    a prefix
    RO
    b prefix
    BOA

    9O and A differ, so the cell is the larger of the cell above (0) and the cell to the left (1), which is 1.

  10. L[i][j]
    ""BOARD
    ""000000
    R000011
    O00111
    A0
    D0
    a prefix
    RO
    b prefix
    BOAR

    10O and R differ, so the cell is the larger of the cell above (1) and the cell to the left (1), which is 1.

  11. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A0
    D0
    a prefix
    RO
    b prefix
    BOARD

    11O and D differ, so the cell is the larger of the cell above (1) and the cell to the left (1), which is 1.

  12. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A00
    D0
    a prefix
    ROA
    b prefix
    B

    12A and B differ, so the cell is the larger of the cell above (0) and the cell to the left (0), which is 0.

  13. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A001
    D0
    a prefix
    ROA
    b prefix
    BO

    13A and O differ, so the cell is the larger of the cell above (1) and the cell to the left (0), which is 1.

  14. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A0012
    D0
    a prefix
    ROA
    b prefix
    BOA

    14A and A match, so the cell is the diagonal value 1 plus 1, which is 2.

  15. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A00122
    D0
    a prefix
    ROA
    b prefix
    BOAR

    15A and R differ, so the cell is the larger of the cell above (1) and the cell to the left (2), which is 2.

  16. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A001222
    D0
    a prefix
    ROA
    b prefix
    BOARD

    16A and D differ, so the cell is the larger of the cell above (1) and the cell to the left (2), which is 2.

  17. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A001222
    D00
    a prefix
    ROAD
    b prefix
    B

    17D and B differ, so the cell is the larger of the cell above (0) and the cell to the left (0), which is 0.

  18. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A001222
    D001
    a prefix
    ROAD
    b prefix
    BO

    18D and O differ, so the cell is the larger of the cell above (1) and the cell to the left (0), which is 1.

  19. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A001222
    D0012
    a prefix
    ROAD
    b prefix
    BOA

    19D and A differ, so the cell is the larger of the cell above (2) and the cell to the left (1), which is 2.

  20. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A001222
    D00122
    a prefix
    ROAD
    b prefix
    BOAR

    20D and R differ, so the cell is the larger of the cell above (2) and the cell to the left (2), which is 2.

  21. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A001222
    D001223
    a prefix
    ROAD
    b prefix
    BOARD

    21D and D match, so the cell is the diagonal value 2 plus 1, which is 3.

  22. L[i][j]
    ""BOARD
    ""000000
    R000011
    O001111
    A001222
    D001223
    answer
    3
    shared
    OAD

    22The answer is L[4][5] = 3. Walking back from the bottom-right corner, a match steps diagonally and keeps the letter, and a mismatch steps to the larger of the cell above and the cell to the left. The kept letters spell OAD.

1 / 22
Longest common subsequence
function lcsLength(a, b) {
  const L = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
  for (let i = 1; i <= a.length; i++) {
    for (let j = 1; j <= b.length; j++) {
      if (a[i - 1] === b[j - 1]) {
        L[i][j] = L[i - 1][j - 1] + 1; // use the matching letter
      } else {
        L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); // drop one letter
      }
    }
  }
  return L[a.length][b.length];
}
 
lcsLength("ROAD", "BOARD"); // 3
def lcs_length(a, b):
    L = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                L[i][j] = L[i - 1][j - 1] + 1  # use the matching letter
            else:
                L[i][j] = max(L[i - 1][j], L[i][j - 1])  # drop one letter
    return L[len(a)][len(b)]
 
lcs_length("ROAD", "BOARD")  # 3
ApproachTimeSpaceWhy
LCS tableO(m × n)O(m × n)There is one cell for each pair of prefixes, and each cell takes constant work.
Edit distance tableO(m × n)O(m × n)The table has the same size. Keeping only two rows reduces the space to O(n) when you need just the number.

Variants

Edit distance

The edit distance from a to b is the fewest single-character insertions, deletions and replacements that turn a into b. Spell checkers and fuzzy search use it to rank how close a typed word is to a dictionary word. It uses the same table of prefixes, with E[i][j] as the fewest edits that turn the first i characters of a into the first j characters of b.

If the last characters match, no edit is needed for them and E[i][j] = E[i − 1][j − 1]. If they differ, the last edit was one of three, and each of them leads to a neighbouring cell. A replacement turns a[i − 1] into b[j − 1] and leaves the diagonal cell to solve. A deletion removes a[i − 1] and leaves the cell above. An insertion adds b[j − 1] and leaves the cell to the left. So E[i][j] = 1 + min(E[i − 1][j − 1], E[i − 1][j], E[i][j − 1]).

[i−1][j−1] [i−1][j] [i][j−1] [i][j] replace or match delete a[i−1] insert b[j−1]
Each kind of edit leads to one neighbouring cell, and a match takes the diagonal at no cost.

The base cases differ from the subsequence table. Turning the first i characters of a into the empty string takes i deletions, so E[i][0] = i, and building the first j characters of b from nothing takes j insertions, so E[0][j] = j. The fill order and the position of the answer are the same as before. For ROAD and BOARD the finished table is:

""BOARD
""012345
R112334
O221234
A332123
D443222

The corner holds 2: replace R with B to get BOAD, then insert R before the D to get BOARD. As a check on one cell, row O and column O is a match, so it copies the diagonal cell (row R, column B), which is 1.

Edit distance
function editDistance(a, b) {
  const E = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
  for (let i = 0; i <= a.length; i++) E[i][0] = i; // delete everything
  for (let j = 0; j <= b.length; j++) E[0][j] = j; // insert everything
  for (let i = 1; i <= a.length; i++) {
    for (let j = 1; j <= b.length; j++) {
      if (a[i - 1] === b[j - 1]) {
        E[i][j] = E[i - 1][j - 1]; // free match
      } else {
        E[i][j] = 1 + Math.min(E[i - 1][j - 1], E[i - 1][j], E[i][j - 1]);
      }
    }
  }
  return E[a.length][b.length];
}
 
editDistance("ROAD", "BOARD"); // 2
def edit_distance(a, b):
    E = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(len(a) + 1):
        E[i][0] = i  # delete everything
    for j in range(len(b) + 1):
        E[0][j] = j  # insert everything
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                E[i][j] = E[i - 1][j - 1]  # free match
            else:
                E[i][j] = 1 + min(E[i - 1][j - 1], E[i - 1][j], E[i][j - 1])
    return E[len(a)][len(b)]
 
edit_distance("ROAD", "BOARD")  # 2

If the problem gives each kind of edit its own cost, replace the 1 in front of each of the three options with that option's cost. The structure stays the same. If only insertions and deletions are allowed, drop the replacement option, and the answer becomes len(a) + len(b) − 2 × LCS.

Longest common substring

A substring is an unbroken run of characters, while a subsequence may skip characters. OAD is a subsequence of BOARD but not a substring of it. For the longest common substring, a mismatch cannot be repaired by dropping a character, so the cell is set to 0 instead of taking a maximum. A match still gives S[i − 1][j − 1] + 1. The answer is the largest value anywhere in the table, not the bottom-right cell, because the best run can end in the middle of either string.

Longest palindromic subsequence

The longest palindromic subsequence of a string is the longest common subsequence of the string and its reverse. This lets you reuse the LCS code without writing a new recurrence.

Recovering the string itself

The table gives only the length. To get the actual subsequence, or the actual edits, start at the bottom-right corner and walk back, as the last step of the trace shows. On a match, keep the character and move diagonally. Otherwise move to the neighbour whose value produced the current cell. This needs the full table, so you cannot use the two-row space saving when you also need the string.

When this technique does not apply

Checking whether one string is a subsequence of another needs no table. Two pointers that move forward through the strings answer it in O(m + n). A table is needed only when you must choose which characters to keep.

Pitfalls

In the interview

Two strings in the problem statement, together with a question about the longest shared part, the number of changes, or whether one can be turned into the other, point to this technique. Words such as "subsequence", "minimum number of operations" and "convert" are the usual signals. Start by stating the meaning of L[i][j] in one sentence, because interviewers check that definition first, and then give the recurrence and the base cases.

Questions to expect:

  • "What is the time and space complexity, and can you reduce the space?" The time is O(m × n) and the table also takes O(m × n) space. Each row depends only on the row above it, so two rows are enough when you need only the number, which gives O(min(m, n)) space if the shorter string runs across the table.
  • "How do you return the subsequence itself, not just its length?" Keep the full table and walk back from the corner. On a match, add the character and move diagonally. Otherwise move to the larger neighbour. Reverse the collected characters at the end.
  • "Why is a match always safe to take?" If the last characters are equal, some optimal answer pairs them. Suppose an optimal answer uses neither last character: adding the pair would make it longer, which is a contradiction. Suppose it uses the last character of only one string: you can pair that character with the matching last character of the other string instead, and the length stays the same. So in that cell you never need to consider dropping a character.
  • "What changes if the edits have different costs?" Put each cost on its own option in the minimum. The table, the order of filling and the complexity do not change.
  • "Can you solve it recursively?" Yes. Write the recurrence as a function of (i, j) and cache the results. It has the same O(m × n) cost, but long strings can exceed the recursion limit, which is why the table is the usual answer.
  • "What is the difference between a subsequence and a substring?" A substring is contiguous and a subsequence is not. The substring recurrence resets a mismatch to 0 and takes the maximum over the whole table.
Quick check

What is the length of the longest common subsequence of "TEAM" and "MEAT"?

In the LCS table the characters for cell [i][j] differ, L[i − 1][j] = 2 and L[i][j − 1] = 3. What is L[i][j]?

What is the edit distance from "CAT" to "CUT"?

What to practise next

The next lesson is Longest Increasing Subsequence, which finds a subsequence inside one list of numbers and then speeds it up with binary search. For practice, try Shared Dance Moves for the longest common subsequence and Spelling Test Fixes for edit distance.