Longest Common Subsequence
Given two strings text1text2
Example 1
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Solution Approach - 2D DP
We build a 2D DP table where dp[i][j]itext1jtext2
- Base case:
anddp[0][j] = 0 for all i, j (empty string has LCS of length 0).dp[i][0] = 0 - If characters match:
.dp[i][j] = dp[i-1][j-1] + 1 - If characters don't match:
.dp[i][j] = max(dp[i-1][j], dp[i][j-1]) - The answer is
.dp[m][n]
Java
public class LongestCommonSubsequence {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
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 Analysis:
Time complexity: O(m * n) where m and n are the lengths of the two strings.
Space complexity: O(m * n) for the DP table.