Longest common subsequence
medium 20 minGiven two strings, find the longest sequence of characters that appears in both in the same order, gaps allowed.
See it run
Watch a table of two strings fill one cell at a time, a match stepping in from the diagonal and a mismatch taking the better of up and left, then walk back from the corner to spell out the answer.
Operations
Fill the table: ABCDE vs ACE
dp[i][j] is the LCS length of the first i characters of s1 and the first j characters of s2. Row 0 and column 0 are 0 (an empty prefix shares nothing). Every other cell is diagonal + 1 on a match, or max(up, left) on a mismatch. The answer lands in the bottom-right corner.
Step 1 of 18
An empty 6 × 4 table
| "" | A | C | E | |
|---|---|---|---|---|
| "" | · | · | · | · |
| A | · | · | · | · |
| B | · | · | · | · |
| C | · | · | · | · |
| D | · | · | · | · |
| E | · | · | · | · |
dp[i][j] = LCS of s1[:i] and s2[:j] · answer at dp[5][3]
Rows are the prefixes of s1 = "ABCDE" and columns the prefixes of s2 = "ACE", each starting with the empty prefix "". So the table is (m + 1) \times (n + 1). Cell dp[i][j] will hold the LCS length of s1[:i] and s2[:j].
Step 1: An empty 6 × 4 table
def lcs(s1, s2): m, n = len(s1), len(s2) dp = [[0] * (n + 1) for _ in range(m + 1)] # row 0 and column 0 stay 0 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 # match: diagonal + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) # skip one: best of up, left return dp[m][n]- Time
- O(m·n)
- Space
- O(m·n)
- table size
- (5 + 1) × (3 + 1) = 24
- cells computed
- m · n = 15
- answer
- 3 (ACE)
Say the recurrence before you code: match means diagonal + 1, mismatch means the better of skipping a character from either string.
In the real world
The same longest common subsequence doing real jobs. Pick one and step through it.
Two six-letter strings whose LCS, ADH, is spread out with gaps in both. The 7 × 7 table and a walk back that meets a tie.
Step 1 of 5
Two strings, gaps in both
| "" | A | E | D | F | H | R | |
|---|---|---|---|---|---|---|---|
| "" | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A | 0 | · | · | · | · | · | · |
| B | 0 | · | · | · | · | · | · |
| C | 0 | · | · | · | · | · | · |
| D | 0 | · | · | · | · | · | · |
| G | 0 | · | · | · | · | · | · |
| H | 0 | · | · | · | · | · | · |
lcs("ABCDGH", "AEDFHR") = ?
A, D and H appear in both strings in the same order, but never next to each other. The table has 7 \times 7 cells including the empty row and column.
Step 1: Two strings, gaps in both
print(lcs("ABCDGH", "AEDFHR"), lcs_string("ABCDGH", "AEDFHR")) # 3 ADHCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Sizing the table m × n instead of (m + 1) × (n + 1)
criticalWithout the empty row and column, the first real row has no up or diagonal neighbour, so you either special-case it or read dp[-1], which Python wraps to the last row silently. The extra row and column of zeros are the base case.
Wrongdp = [[0] * n for _ in range(m)]for i in range(m): for j in range(n): if s1[i] == s2[j]: dp[i][j] = dp[i - 1][j - 1] + 1 # i = 0 reads dp[-1]Rightdp = [[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] + 1Comparing s1[i] with s2[j] in a 1-based table
criticalRow i of the table stands for the prefix s1[:i], whose last character is s1[i - 1]. Using s1i compares the wrong characters and runs off the end at i = m.
Wrongif s1[i] == s2[j]: # off by one, IndexError at i = mRightif s1[i - 1] == s2[j - 1]: # the last characters of s1[:i] and s2[:j]Taking diagonal + 1 on a mismatch, or max on a match
majorOn a mismatch the diagonal ignores that one of the two characters might still pair with something earlier; max(up, left) covers both choices. On a match, max(up, left) misses the +1 the pair earns. Mixing them up gives wrong lengths.
Wrongelse: dp[i][j] = dp[i - 1][j - 1] # loses answers that skip only one sideRightelse: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])Building the table with [[0] * (n + 1)] * (m + 1)
criticalList multiplication repeats one reference: every row is the same list, so writing one row writes them all.
Wrongdp = [[0] * (n + 1)] * (m + 1) # m + 1 references to ONE rowRightdp = [[0] * (n + 1) for _ in range(m + 1)]Two rows without a fresh or swapped curr
majorIf curr is the same list as prev, the left neighbour overwrites the up and diagonal values you still need. Make a new curr per row, or swap two lists and remember curr[0] must be 0.
Wrongprev = curr = [0] * (n + 1) # one list under two namesfor ch in s1: for j in range(1, n + 1): ...Rightprev = [0] * (n + 1)for ch in s1: curr = [0] * (n + 1) for j in range(1, n + 1): ... prev = currReturning the corner for longest common substring
minorIn the substring table a mismatch resets to 0, so the corner is only the run ending at the last characters. The answer is the largest value anywhere; track it as you fill.
Wrongreturn dp[m][n] # 0 for "ABCXA" vs "ABCX"; the answer is 4Rightbest = max(best, dp[i][j]) # inside the match branchreturn best
Interview tips
How to explain it
- dp[i][j] is the LCS of the first i characters of s1 and the first j of s2; row 0 and column 0 are 0.
- If the last characters match, both are in some LCS: diagonal + 1. If not, at least one is not: max(up, left).
- O(m·n) time and space; two rows give O(min(m, n)) space for the length; walk back from the corner for the string.
Spot it in problems
- Two sequences and the words common, shared, align, in order, or delete to make equal.
- Answers like m + n − LCS (shortest supersequence) or m + n − 2·LCS (deletions).
- One string compared with its reverse: longest palindromic subsequence is LCS(s, reversed s).
Memory tricks
- Match: diagonal plus one. Miss: best of up and left.
- Common ancestors: the same people in the same order, gaps allowed.
- Substring resets, subsequence carries.
Watch out
- Table is (m + 1) × (n + 1); compare s1[i - 1] with s2[j - 1].
- Two rows lose the traceback: keep the full table if you need the string.
- The LCS string is not unique; the length is.