LCS

Longest Common Subsequence

This is a real problem

Not “some google interview type shit” as some have claimed.

A subsequence

Given a string, a subsequence is a sequence of characters from the string, taken in order but possibly with gaps.

"foobar" -> "fbr"
"foobar" -> "oba"
"foobar" -> "foobar"
"foobar" -> ""

Common subsequence

Given two strings, a common subsequence is any subsequence that can be found in both strings. For instance here are a sample of common subsequences:

"foobar", "oofoxoder" -> "", "oo", "foo", "r", "or"

Longest common subsequence

Of all the common subsequences, the longest one

"foobar", "oofoxoder" -> "foor"

LCS and similarity

When comparing related texts (such as two versions of a file) the longest common sequence tells us a lot about how similar they are.

Some formulas

Let L be the length of the LCS of two strings and S be the sum of the lengths of the two strings:

2L / S Measure of similarity from 0.0 to 1.0
S - 2L Levenshtein Distance, a.k.a. “edit distance”.

LCS and diffs

Finding the LCS is also the first step in computing a “diff” of two texts.

To compute a diff: find the LCS and then use it to compute the series of additions and deletions needed to transform the first string into the second.

Problems

  • Write a recursive method to find the LCS of two strings.

  • Write a tabular dynamic programming based method to find the length of the LCS of two strings.

  • Write a method that uses the table produced in the previous method to reconstruct the actual LCS.