Memra

Longest common subsequence

◈ 4 cards

The 3-case LCS recurrence, the Θ(mn) table, and reconstructing one actual LCS string.

The problem

A subsequence drops zero or more elements from a sequence without reordering the rest (ACE is a subsequence of ABCDE). Given two sequences and , the longest common subsequence (LCS) is a longest sequence that is a subsequence of both. It powers diff tools, version control, and DNA alignment.

Optimal substructure (Theorem 14.1)

Let be an LCS of and , with prefixes :

  1. If , then and is an LCS of and .
  2. If and , then is an LCS of and .
  3. If and , then is an LCS of and .

These three cases are exhaustive — a matched pair must be the LCS's last element; an unmatched last element can be dropped from one side.

The recurrence

Let be the length of an LCS of and :

The diagonal-vs-max decision is the whole algorithm. Match go diagonal . Mismatch take the better of dropping (up) or (left).

Worked example: X = ABCBDAB, Y = BDCABA

Fill the table in row-major order, so , , are always ready before . The final cell gives length 4; reconstructing back from it yields BCBA (other length-4 LCSs like BDAB exist — any one is correct).

Cost

subproblems, work each time and space. Reconstruction is : from , on a match emit and step diagonally; otherwise step toward the larger neighbor. (CLRS stores arrows in a table; you can instead re-derive the direction from the values, as the code below does.)

j-1ji-1c[i-1,j-1]c[i-1,j]ic[i,j-1]c[i,j]
Every LCS cell reads exactly three already-filled neighbours. On a match it takes the diagonal plus one; on a mismatch it takes the larger of up and left. Because all three sit above-or-left, row-major order always has them ready.
X down / YacrossBDCAA0001B1111C1122B1122Row 0 and column 0 are all zeros, not drawn.
The first four characters of each string — the top-left corner of the full c table, since c[i,j] depends only on the prefixes X_i and Y_j. The traceback starts at the bottom-right and walks up-or-left, stepping diagonally only on the two match cells (i=2/j=1 and i=3/j=3), which emit B and C. Run the same walk on the full 7 by 6 table and it emits BCBA.
NORMAL ~/memra/learn/comp-372/longest-common-subsequence utf-8 LF