Learn 2D dynamic programming grid modeling for Longest Common Subsequence (LCS), string alignments, and edit distance.
Learn how dynamic arrays achieve O(1) amortized insertion, contiguous memory layout, and geometric doubling strategies.
"bcd" in "abcdef")."ace" is a subsequence of "abcde").Let dp[i][j] be the LCS length of text1[0...i-1] and text2[0...j-1]:
text1[i - 1] === text2[j - 1]):
$$ ext[i][j] = 1 + ext[i - 1][j - 1]$$function longestCommonSubsequence(text1, text2) {
const m = text1.length;
const n = text2.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++) {
if (text1[i - 1] === text2[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1]; // Diagonal + 1
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // Max of top and left
}
}
}
return dp[m][n];
}
console.log(longestCommonSubsequence("abcde", "ace")); // Output: 3 ("ace")
console.log(longestCommonSubsequence("abc", "abc")); // Output: 3
console.log(longestCommonSubsequence("abc", "def")); // Output: 0
"" a c e
"" [ 0, 0, 0, 0 ]
a [ 0, 1, 1, 1 ]
b [ 0, 1, 1, 1 ]
c [ 0, 1, 2, 2 ]
d [ 0, 1, 2, 2 ]
e [ 0, 1, 2, 3 ] ◄── dp[5][3] = 3
dp[i][j] corresponds to 0-indexed string characters text1[i - 1] and text2[j - 1].Use 2D DP for string transformation and grid path problems. Next, let's explore the Intervals Pattern!