Longest Common Subsequence
The problem
Section titled “The problem”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" -> 0Key insight
Section titled “Key insight”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 0a 0 1 1 1b 0 1 1 1c 0 1 2 2d 0 1 2 2e 0 1 2 3 <- answerThe 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]export function longestCommonSubsequence(text1: string, text2: string): number { const m = text1.length; const n = text2.length; // dp[i][j] = LCS length of text1[0..i) and text2[0..j); row/col 0 = empty prefix const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0)); for (let i = 1; i <= m; i++) { for (let j = 1; j <= n; j++) { if (text1[i - 1] === text2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[m][n];}class Solution { public int longestCommonSubsequence(String text1, String text2) { int m = text1.length(), n = text2.length(); // dp[i][j] = LCS length of text1[0..i) and text2[0..j); row/col 0 = empty prefix int[][] dp = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (text1.charAt(i - 1) == text2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[m][n]; }}Complexity
Section titled “Complexity”- 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).
Watch out for
Section titled “Watch out for”- Off-by-one between table and string.
dp[i][j]coversicharacters, so the characters compared aretext1[i-1]andtext2[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.
Variations
Section titled “Variations”Edit Distance (LeetCode 72)
Section titled “Edit Distance (LeetCode 72)”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).
Uncrossed Lines (LeetCode 1035)
Section titled “Uncrossed Lines (LeetCode 1035)”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.