Skip to content

Longest Common Subsequence

MediumLeetCode #1143Time O(m * n)Space O(m * n)

Given two strings, return the length of their longest common subsequence: characters taken in order from each string, with gaps allowed. If there is none, return 0.

text1 = "abcde", text2 = "ace" -> 3 ("ace")
text1 = "abc", text2 = "def" -> 0

Brute force tries every subsequence of one string and checks it against the other: exponential. The state that repeats is “how much of each string have I used?”, so let dp[i][j] be the LCS length of the first i characters of text1 and the first j of text2.

Compare the last characters of those two prefixes. If they match, that character is part of some best answer, so take the diagonal plus one. If not, at least one of them is unused, so drop one and take the better result.

dp[i][j] = dp[i-1][j-1] + 1 if text1[i-1] == text2[j-1], else max(dp[i-1][j], dp[i][j-1]). Row 0 and column 0 are 0: an empty prefix has nothing in common.

text1 = "abcde" (rows), text2 = "ace" (columns)
"" 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 <- answer

The full table is shown because it is easiest to reason about. Each row reads only the row above, so you can keep two rows and cut space to O(min(m, n)) if asked. Reconstructing the subsequence itself needs the full table: walk back from dp[m][n].

Show solutionHide solution
def longest_common_subsequence(text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
# dp[i][j] = LCS length of text1[:i] and text2[:j]; row/col 0 = empty prefix
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]
  • Time: O(m * n) — each of the (m+1) * (n+1) cells is filled once with O(1) work.
  • Space: O(m * n) — the full table. Two rolling rows would make it O(n).
  • Off-by-one between table and string. dp[i][j] covers i characters, so the characters compared are text1[i-1] and text2[j-1].
  • Subsequence is not substring. Gaps are allowed, which is why a mismatch carries over a neighbour’s value instead of resetting to 0.
  • Table size is (m+1) x (n+1). The extra row and column are the empty-prefix base case.

Minimum insert/delete/replace operations to turn one word into another. The trick: same table. On a match take the diagonal; otherwise 1 + min(above, left, diagonal). Base row and column are j and i (turning a prefix into empty).

Draw non-crossing lines between equal numbers in two arrays. The trick: it is exactly LCS on arrays instead of strings. Non-crossing means order is preserved.