Longest Common Subsequence
Pattern: Strings DP
dp[i][j] is the LCS of the first i characters of a and the first j of b. Matching last characters extend dp[i-1][j-1]; otherwise drop one of them and take the better.
Solve on LeetCodeSolve on GeeksforGeeks
The problem
Return the length of the longest common subsequence of text1 and text2. 'abcde' and 'ace' give 3.
Think first
- If the last characters match, what can you do?
- If not, which smaller problems are left?
- What is the table size?
Hints
Brute force, and why it fails
Try every subsequence of one string: 2ᵐ.
The key insight
Every comparison only ever needs the prefixes of both strings.
Dry run
| lcs | 1 |
|---|
'abcde' and 'ace'. 'a' matches 'a': 1.
Step 1 of 2
The plan
dp[i][j] = dp[i-1][j-1] + 1 if a[i-1] == b[j-1] else max(dp[i-1][j], dp[i][j-1])
Complexity
- Time
O(m × n)- Space
O(n)
Two rows are enough.
Edge cases
- An empty string: 0.
- Identical strings: their length.
- No common letters: 0.
I've built my logic, show the code
Java
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
int[][] dp = new int[m + 1][n + 1]; // dp[i][j]: the LCS of the first i and first j characters
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = text1.charAt(i - 1) == text2.charAt(j - 1)
? dp[i - 1][j - 1] + 1 // the last characters match: use both
: Math.max(dp[i - 1][j], dp[i][j - 1]); // otherwise drop one of them
return dp[m][n];
}
}C++
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = static_cast<int>(text1.size()), n = static_cast<int>(text2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); // the LCS of the first i and first j characters
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = text1[i - 1] == text2[j - 1]
? dp[i - 1][j - 1] + 1 // the last characters match: use both
: max(dp[i - 1][j], dp[i][j - 1]); // otherwise drop one of them
return dp[m][n];
}
};Python
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
prev = [0] * (len(text2) + 1) # the previous row of the table
for a in text1:
cur = [0]
for j, b in enumerate(text2, 1):
cur.append(prev[j - 1] + 1 if a == b else max(prev[j], cur[j - 1])) # match, or drop one
prev = cur
return prev[-1]Common mistakes
- Confusing substring and subsequence.
- Off-by-one indexes.