TL;DR
Classic LCS DP over prefix pairs (i, j) β O(m Γ n) time, O(min(m, n)) space after rolling to two rows.
Approach 1 β Brute-force recursion
Intuition: compare the current last characters. Equal β they extend the LCS, so add 1 and shrink both. Unequal β drop the last character of one string or the other and keep whichever gives more.
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
def dfs(i: int, j: int) -> int:
if i == 0 or j == 0:
return 0
if text1[i - 1] == text2[j - 1]:
return 1 + dfs(i - 1, j - 1)
return max(dfs(i - 1, j), dfs(i, j - 1))
return dfs(len(text1), len(text2))
Complexity: O(2^(m+n)) time worst case, O(m+n) recursion depth.
Why the constraints kill it: two length-1000 strings with few matches branch into an astronomically large tree.
Approach 2 β Top-down memoization
The insight: only (i, j) varies, giving (m+1)(n+1) distinct subproblems. Cache them and the tree collapses into the grid.
from functools import lru_cache
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
@lru_cache(maxsize=None)
def dfs(i: int, j: int) -> int:
if i == 0 or j == 0:
return 0
if text1[i - 1] == text2[j - 1]:
return 1 + dfs(i - 1, j - 1)
return max(dfs(i - 1, j), dfs(i, j - 1))
return dfs(len(text1), len(text2))
Complexity: O(m Γ n) time and space.
Approach 3 β Bottom-up 2-D table
Table meaning: dp[i][j] = length of the LCS of text1[:i] and text2[:j].
2-D recurrence:
dp[i][0] = 0, dp[0][j] = 0 # empty prefix shares nothing
if text1[i-1] == text2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1 # extend the diagonal match
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) # best of dropping one char
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[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]
Walkthrough on text1 = "abcde", text2 = "ace":
| "" | 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 |
The diagonal bumps at a, c, e build up to dp[5][3] = 3.
Complexity: O(m Γ n) time, O(m Γ n) space.
Approach 4 β Space-optimized two rows
The insight: each cell reads only the previous row and the current rowβs left neighbor, so two rows suffice. Keep prev and fill curr.
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
prev = [0] * (n + 1)
for i in range(1, m + 1):
curr = [0] * (n + 1)
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev[n]
Complexity: O(m Γ n) time, O(n) space. (Iterate over the longer string as the outer loop and the shorter as inner for O(min(m, n)) space.)
Common pitfalls
- Using
max on the diagonal for a match β when characters match you must take dp[i-1][j-1] + 1; taking max(dp[i-1][j], dp[i][j-1]) there silently drops valid pairings.
- Confusing subsequence with substring β LCS allows gaps; the longest common substring problem uses a different recurrence (reset to 0 on mismatch).
- Index vs length off-by-one β
dp[i][j] uses characters text1[i-1] and text2[j-1]; mixing 0-based and 1-based indexing here is the classic bug.
- In the rolled version, allocate a fresh
curr (or clear it) each row so stale values donβt leak in.
Pattern takeaway
LCS is the archetype 2-D string DP: a match walks the diagonal and adds one, a mismatch takes the max of the two orthogonal neighbors. This same grid underlies edit distance, interleaving, and diff tools β recognize βalign two sequences, order-preservingβ and reach for the (i, j) prefix table.