Longest Common Subsequence
Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #1143
Return the length of the longest subsequence common to both strings (characters in order, not necessarily contiguous), or 0 if there is none.
Examples
text
text1 = "ABCBDAB", text2 = "BDCAB" → 4 ("BCAB" or "BDAB")
text1 = "abc", text2 = "abc" → 3
text1 = "abc", text2 = "def" → 0Hints
- dp[i][j] = LCS length of text1[:i] and text2[:j].
- If the last characters match, they can both be part of the LCS.
- If not, drop the last character of one string or the other.
Approach
dp[i][j] = LCS of prefixes of length i and j. If text1[i−1] == text2[j−1]: dp[i][j] = dp[i−1][j−1] + 1. Otherwise: dp[i][j] = max(dp[i−1][j], dp[i][j−1]). Row 0 and column 0 are 0. The answer is dp[m][n]. Step through the table in the visualizer above. Two rolling rows reduce space to O(min(m, n)).
Complexity
Time: O(m·n). Space: O(n).
Python solution
def longestCommonSubsequence(text1, text2):
m, n = len(text1), len(text2)
prev = [0] * (n + 1)
for i in range(1, m + 1):
cur = [0] * (n + 1)
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
cur[j] = prev[j - 1] + 1
else:
cur[j] = max(prev[j], cur[j - 1])
prev = cur
return prev[n]JavaScript solution
function longestCommonSubsequence(text1, text2) {
const m = text1.length, n = text2.length;
let prev = new Array(n + 1).fill(0);
for (let i = 1; i <= m; i++) {
const cur = new Array(n + 1).fill(0);
for (let j = 1; j <= n; j++) {
cur[j] = text1[i - 1] === text2[j - 1] ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
}
prev = cur;
}
return prev[n];
}