Advanced 12 min

Longest common subsequence

A common subsequence appears in both strings in the same order and can skip characters.

How it works

Build a grid with one row per prefix of the first string and one column per prefix of the second. The empty row and column start at zero. When letters match, extend the shorter prefixes’ diagonal answer. When they differ, check the best result from leaving out either final letter.

Walk through an example

Between ABC and AC, the letters A and C can be kept even though they are separated in the first string. Use a table for prefixes of each string. Matching final letters extend the diagonal answer by one.

What to watch for

On a mismatch, use the larger of the two neighboring answers. A substring would require adjacent characters and follows different rules.

Code example

def lcs_length(a, b):
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i, left in enumerate(a, 1):
        for j, right in enumerate(b, 1):
            if left == right:
                dp[i][j] = dp[i-1][j-1] + 1
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])
    return dp[-1][-1]

Check your understanding

Give a longest common subsequence.

See the example and explanation
Worked example
Given ABC and AXC
Answer AC

Both strings contain A before C. Their middle letters differ, so no length-three common subsequence exists.

Open practice problem
Next lessonFenwick trees and dynamic prefix sums