Dynamic programming on two strings: LCS

Many DP problems compare two sequences, like edit distance and diff tools. They use a 2D table where cell [i][j] answers the question for the first i items of one and the first j items of the other.

For the longest common subsequence (LCS), a subsequence keeps order but may skip characters. "ace" is a subsequence of "abcde". Fill the table row by row:

  • if a[i - 1] == b[j - 1], then t[i][j] = t[i - 1][j - 1] + 1
  • otherwise t[i][j] = max(t[i - 1][j], t[i][j - 1])

Row 0 and column 0 are 0, for the empty prefix. That is O(n × m) time. You only need the row above, so keep two rows.

A common mistake: off by one errors. The table is one bigger than each string, so cell [i][j] looks at a[i - 1] and b[j - 1].

Exercise: finish lcs_length so it returns the length of the longest common subsequence of a and b. Press Check to run the tests.