Longest common subsequence
medium 20 minGiven two strings, find the longest sequence of characters that appears in both in the same order, gaps allowed.
Video lesson · Chapter 1 of 8
The damaged title cards
Longest common subsequence in 75 seconds
1:23Reel
How it works
Step through the idea, or press Play.
Build the table. (m + 1) × (n + 1) cells; row 0 and column 0 are 0 because an empty prefix shares nothing
Understand it
Start here
Two strings, one shared skeleton
The longest common subsequence (LCS) of two strings is the longest sequence of characters that appears in both, in the same order, but not necessarily next to each other. For "ABCDGH" and "AEDFHR" it is "ADH", length 3: A, D and H appear in that order in each string, with other letters in between. Our running example is "ABCDE" and "ACE", whose LCS is "ACE" itself.
Recap: dynamic programming
Split a problem into overlapping subproblems and solve each once. If that is new, read dynamic programming first.
Recap: a 2D table
Unique paths filled a grid where each cell came from the cell above and the cell to the left. LCS adds a third neighbour: the diagonal.
The new idea
A subproblem is a pair of prefixes: the first characters of one string and the first of the other. That pair is the cell .
Definitions
Subsequence vs substring
| Subsequence | Substring | |
|---|---|---|
| Rule | keep the order, gaps allowed | one unbroken run |
From ABCDEF | BDF is one | BCD is one, BDF is not |
| How many (length ) | choices of positions | non-empty runs |
Common to ABCDE and ACE | ACE (3) | A, C or E (1) |
| DP rule on a mismatch | carry max(up, left) | reset to 0 |
Why brute force has no chance
First attempt
Try every subsequence
List the subsequences of the shorter string (length ), longest first, and test each one against the longer string (length ) with a single left-to-right scan. The first one that fits is an LCS.
Cost of the brute force
from itertools import combinationsdef is_subsequence(t, s): it = iter(s) return all(ch in it for ch in t) # each 'in' resumes where the last one stoppeddef lcs_brute(s1, s2): short, long_ = sorted((s1, s2), key=len) for k in range(len(short), -1, -1): # longest candidates first for idx in combinations(range(len(short)), k): cand = "".join(short[p] for p in idx) if is_subsequence(cand, long_): return cand return ""print(lcs_brute("ABCDE", "ACE"), lcs_brute("ABCDGH", "AEDFHR")) # ACE ADHThe key idea
Look at the last characters
Let be the LCS length of the first characters of and the first characters of . Compare the last two characters, s1[i-1] and s2[j-1]. Either they are equal, and the pair can end the common subsequence together, or they differ, and at least one of them is not part of it.
The recurrence
Working out one cell
Match: ↖ + 1
Both characters contribute, so take the answer without either of them,
dp[i-1][j-1], and add one.Skip from s1: ↑
dp[i-1][j]is the best when the last character of is left out.Skip from s2: ←
dp[i][j-1]is the best when the last character of is left out. On a mismatch, keep the larger of the two.
Why it works
Two cases, both safe
Match case
Mismatch case
Overlapping subproblems
Plain recursion repeats itself
def lcs_rec(s1, s2): def f(i, j): if i == 0 or j == 0: return 0 if s1[i - 1] == s2[j - 1]: return 1 + f(i - 1, j - 1) return max(f(i - 1, j), f(i, j - 1)) return f(len(s1), len(s2))print(lcs_rec("ABCDE", "ACE"), lcs_rec("ABCDGH", "AEDFHR")) # 3 3Call tree of f(5, 3) for ABCDE and ACE
The worst case: no common characters
| Strings (no common letter) | Plain recursion | With memo | Table cells |
|---|---|---|---|
| 3 and 3 | 39 | 19 | 16 |
| 5 and 5 | 503 | 51 | 36 |
| 8 and 8 | 25,739 | 129 | 81 |
| 10 and 10 | 369,511 | 201 | 121 |
| 12 and 12 | 5,408,311 | 289 | 169 |
Top-down vs bottom-up
Memo vs tabulation
A memoised call
from functools import cachedef lcs_memo(s1, s2): @cache def f(i, j): if i == 0 or j == 0: return 0 if s1[i - 1] == s2[j - 1]: return 1 + f(i - 1, j - 1) return max(f(i - 1, j), f(i, j - 1)) return f(len(s1), len(s2))print(lcs_memo("ABCDE", "ACE"), lcs_memo("A" * 10, "B" * 10)) # 3 0functools.cache. Only the states that are actually asked for get computed.| Memoisation (top-down) | Tabulation (bottom-up) | |
|---|---|---|
| How | recursion + cache by | loops fill dp[i][j] row by row |
| Cells computed | only those reachable from | all |
| Time / space | / + stack | / |
| Recursion depth | up to : RecursionError on long strings | none |
| Space trick | hard | easy: keep two rows |
The table
Fill it cell by cell
- 1Create table(m + 1) × (n + 1) zeros
- 2Base casesrow 0, column 0 stay 0
- 3Fillmatch ↖ + 1, else max(↑, ←)
- 4Answerdp[m][n], then trace back
| "" | A | C | E | |
|---|---|---|---|---|
| "" | 0 | 0 | 0 | 0 |
| A | 0 | 1 ↖ | 1 | 1 |
| B | 0 | 1 | 1 | 1 |
| C | 0 | 1 | 2 ↖ | 2 |
| D | 0 | 1 | 2 | 2 |
| E | 0 | 1 | 2 | 3 ↖ |
ABCDE down the side, ACE across the top. Bold cells are matches that came from the diagonal; every other cell copied the larger of up and left.def lcs(s1, s2): m, n = len(s1), len(s2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if s1[i - 1] == s2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[m][n]print(lcs("ABCDE", "ACE"), lcs("ABCDGH", "AEDFHR"), lcs("abc", "def")) # 3 3 0Reconstruction
Trace back the actual subsequence
The corner only says how long the LCS is. To get the letters, start at and retrace the decisions: on a match the character is in the answer and we step diagonally; on a mismatch we step to whichever neighbour the value was copied from. Characters come out backwards, so reverse at the end. For ABCDE and ACE the walk is , collecting E, C, A.
One step of the walk back
def lcs_string(s1, s2): m, n = len(s1), len(s2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if s1[i - 1] == s2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) out, i, j = [], m, n while i > 0 and j > 0: if s1[i - 1] == s2[j - 1]: out.append(s1[i - 1]) i, j = i - 1, j - 1 elif dp[i - 1][j] >= dp[i][j - 1]: i -= 1 else: j -= 1 return "".join(reversed(out))print(lcs_string("ABCDE", "ACE"), lcs_string("ABCDGH", "AEDFHR"), lcs_string("AGCAT", "GAC")) # ACE ADH ACComplexity
O(m·n) time, two rows for space
Cost of the table
def lcs_two_rows(s1, s2): if len(s2) > len(s1): s1, s2 = s2, s1 # columns = the shorter string n = len(s2) prev = [0] * (n + 1) for ch in s1: curr = [0] * (n + 1) for j in range(1, n + 1): if ch == s2[j - 1]: curr[j] = prev[j - 1] + 1 # diagonal is in prev else: curr[j] = max(prev[j], curr[j - 1]) # up in prev, left in curr prev = curr return prev[n]print(lcs_two_rows("ABCDE", "ACE"), lcs_two_rows("ACE", "ABCDE")) # 3 3| Approach | Time | Space | Gives the string? |
|---|---|---|---|
| Every subsequence | Yes | ||
| Plain recursion | stack | With extra work | |
| Memoised recursion | Yes, walk the memo | ||
| Full table | Yes, trace back | ||
| Two rows | No (Hirschberg's method can, in linear space) |
Siblings
Edit distance, substring and friends
Edit distance (Levenshtein): same table, min instead of max
kitten → sitting is 3.Longest common substring: reset instead of carry
ABCXA and ABCA have substring 3 (ABC) but subsequence 4 (ABCA).Which two-string DP is this?
Shortest common supersequence
The shortest string containing both as subsequences has length : write the LCS once and every other character once.
Delete to make equal
Deleting characters from both until they match takes deletions: everything outside the LCS goes.
Longest palindromic subsequence
It is :
charactergivescarac, length 5. See palindromes.Diff tools and DNA
difftreats lines as characters and shows what is outside the LCS as-and+. Biologists align DNA with a scored version of the same table (Needleman–Wunsch).
Recap
Key takeaways
Key points
- A subsequence keeps the order and allows gaps; a substring is one unbroken run.
- Brute force tries all 2^n subsequences of the shorter string: O(m · 2^n).
- dp[i][j] = LCS of s1[:i] and s2[:j]; the table is (m + 1) × (n + 1) with a row and column of zeros.
- Match: dp[i-1][j-1] + 1. Mismatch: max(dp[i-1][j], dp[i][j-1]). Answer: dp[m][n].
- Plain recursion repeats subproblems and is exponential; memo or table gives O(m·n).
- Walk back from the corner to get the string: diagonal on a match, else towards the larger neighbour.
- Two rows give O(min(m, n)) space for the length but lose the traceback.
- Edit distance (min, base cases i and j) and longest common substring (reset to 0) are the same table.