9.4 Longest Common Subsequence (LCS)
চিনবেন কীভাবে
matching two strings/sequences — "common subsequence", "delete to make equal"; 2D dp[i][j] = the answer for the first i and first j characters
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন
Demo: Longest Common Subsequence — LC 1143 (Medium — Amazon/Google/Meta High)
Statement (Demo): Given strings text1 and text2, return the length of their longest common subsequence.
Example: text1="abcde", text2="ace" → 3 ("ace") | ⚡ len(text1), len(text2) ≤ 1000
Approach: If the last characters match, consume both: diagonal + 1. If not, drop the last character of either string and take the larger result.
function longestCommonSubsequence(s1, s2) {
const m = s1.length,
n = s2.length;
const dp = 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++)
dp[i][j] =
s1[i - 1] === s2[j - 1]
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1]);
return dp[m][n];
}
Complexity: Time O(m·n), Space O(m·n) (O(n) keeping two rows)
Demo · Longest Common Subsequenceplan · দিন ০৯৪LC 1143
নোট · ফাঁকা
প্রবলেম
- Longest Palindromic Subsequenceplan · দিন ০৯৫🔥 Must-doLC 516(trick: LCS(s, reverse(s)))
Statement: Given a string
s, return the length of its longest palindromic subsequence.
Example:s="bbbab"→4("bbbb") | ⚡len(s) ≤ 1000নোট · ফাঁকা