Dynamic programming · Exercise 74 of 100
Longest common subsequence
A common subsequence keeps letters in order but allows skips, and its length is 0 if either string is empty. Build a table for longer and longer prefixes of both strings, adding 1 to the length for the two shorter prefixes when their last letters match. When the last letters differ, at least one must be skipped, so try dropping the last letter from either prefix and keep the larger length.
Try it yourself
What is the length of a longest common subsequence of BRICK and BIRCH?
One-step hint
Write BRICK above BIRCH and connect matching letters. How many pairs can you keep without crossing lines or reusing a position?
Worked solution
- B, I, and C appear in that order in both words, so a common subsequence of length 3 is possible.
- Only B, R, I, and C occur in both words. R and I appear in opposite orders, so no shared subsequence can use all four and the maximum length is 3.