Longest Common Subsequence
Difficulty: Medium
Given two strings, find the length of their longest common subsequence — the longest sequence of characters that appears in both in the same order, though not necessarily next to each other.
For example, "ace" is a subsequence of "abcde": delete "b" and "d" and "ace" is left, in order.
Examples
Input: text1 = "abcde", text2 = "ace"
Output: 3
"ace" is the longest string that is a subsequence of both.
Input: text1 = "abc", text2 = "abc"
Output: 3
Input: text1 = "abc", text2 = "def"
Output: 0
The two strings share no characters at all.
Constraints
1 <= text1.length, text2.length <= 1000
Both strings contain only lowercase English letters
Approach
Build a table where cell (i, j) is the longest common subsequence of the first i characters of text1 and the first j characters of text2.
- If the
i-th character oftext1equals thej-th oftext2, it can safely be used, so(i, j)is 1 plus(i-1, j-1). - Otherwise, take the better of dropping the last character of
text1((i-1, j)) or oftext2((i, j-1)).
An empty prefix shares nothing, so the first row and column are all 0 — the base case.
Solutions
Brute Force — Recursion
Walk both strings from the front. On a match, take the character and advance both. Otherwise, try skipping a character from either string and keep the better result. This revisits the same (i, j) pairs many times.
function longestCommonSubsequence(text1, text2) {
function lcs(i, j) {
if (i === text1.length || j === text2.length) return 0;
if (text1[i] === text2[j]) return 1 + lcs(i + 1, j + 1);
return Math.max(lcs(i + 1, j), lcs(i, j + 1));
}
return lcs(0, 0);
}Time: O(2^(m + n)) · Space: O(m + n) — recursion depth
Optimal — Bottom-Up 2D Table
Build a table indexed by (prefix length of text1, prefix length of text2). Row and column 0 are 0, since an empty prefix shares nothing. Fill the rest left to right, top to bottom: on a match, add one to the diagonal; otherwise take the better of the cell above or to the left.
function longestCommonSubsequence(text1, text2) {
const m = text1.length;
const n = text2.length;
const table = 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]) {
table[i][j] = table[i - 1][j - 1] + 1;
} else {
table[i][j] = Math.max(table[i - 1][j], table[i][j - 1]);
}
}
}
return table[m][n];
}Time: O(m * n) · Space: O(m * n)