Longest common subsequence
◈ 4 cardsThe 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 :
- If , then and is an LCS of and .
- If and , then is an LCS of and .
- 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.)