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
Compare the last characters of the two prefixes. If they are equal, they extend the LCS: add 1 and recurse on both shorter prefixes. If they differ, drop the last character of one string or the other and keep whichever result is larger.
def longestCommonSubsequence(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.
With two length-1000 strings and few matches, the recursion branches into an exponentially large tree, so this times out.
Approach 2 — Top-down memoization
Only the pair (i, j) varies, giving (m+1)(n+1) distinct subproblems. Cache each result and the recursion tree reduces to filling that grid once.
from functools import lru_cache
def longestCommonSubsequence(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
dp[i][j] is the length of the LCS of text1[:i] and text2[:j]. Each cell depends only on its diagonal, top, and left neighbors:
flowchart LR
D["dp[i-1][j-1]"] -->|"chars match: +1"| C["dp[i][j]"]
T["dp[i-1][j]"] -->|"mismatch: max"| C
L["dp[i][j-1]"] -->|"mismatch: max"| C
Because every cell reads only cells above and to the left, filling row by row (left to right) guarantees the inputs are ready.
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
def longestCommonSubsequence(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 increments at a, c, and e accumulate to dp[5][3] = 3.
Complexity: O(m × n) time, O(m × n) space.
Approach 4 — Space-optimized two rows
Each cell reads only the previous row and the current row’s left neighbor, so two rows suffice. Keep prev and fill curr.
def longestCommonSubsequence(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 standard 2-D string DP: a match takes the diagonal plus one, a mismatch takes the max of the top and left neighbors. The same grid underlies edit distance, string interleaving, and diff tools. When a problem asks you to align two sequences while preserving order, use the (i, j) prefix table.