Longest Common Subsequence
Problem Statement
Given two strings, find the length of their longest common subsequence (not necessarily contiguous). This medium-level DP puzzle is a treasure hunt—dig out the longest shared thread between two texts!
Example
Input: text1 = "abcde", text2 = "ace"
Output: 3 ("ace")
Input: text1 = "abc", text2 = "abc"
Output: 3 ("abc")
Input: text1 = "abc", text2 = "def"
Output: 0 (no common subsequence)
Code
Java
Python
JavaScript
public class Solution { 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]; } }
def longest_common_subsequence(text1, text2): m, n = len(text1), len(text2) 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] # Example usage print(longest_common_subsequence("abcde", "ace")) # 3 print(longest_common_subsequence("abc", "def")) # 0
function longestCommonSubsequence(text1, text2) { let m = text1.length, n = text2.length; let dp = Array(m + 1).fill().map(() => 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]; } // Example usage console.log(longestCommonSubsequence("abcde", "ace")); // 3 console.log(longestCommonSubsequence("abc", "def")); // 0
Explanation
- DP Insight: Build a 2D table where dp[i][j] = LCS length up to i,j.
- Steps: If chars match, add 1 to diagonal; else, max of left or up.
- Flow Example ("abc","ace"): dp[1][1]=1 (a), dp[2][2]=1, dp[3][3]=2 (ac), final=3 (ace).
- Why It Works: Captures all possible subsequences efficiently.
Note
Time complexity: O(m*n), Space complexity: O(m*n). A textual treasure hunt solved with DP brilliance!