Find the longest run of letters two strings share in order by filling a prefix-by-prefix grid — O(m·n).
The longest common subsequence (LCS) of two strings is the longest sequence of characters that appears in both, in the same order, but not necessarily next to each other. For ABCBDAB and BDCAB the answer is BCAB (length 4). Note the difference from a *substring*: a subsequence may have gaps. LCS is the engine behind diff, version-control merges, and DNA alignment.
Build a table dp[i][j] = the LCS length using the first `i` letters of string `X` and the first `j` letters of string `Y`. Row 0 and column 0 are all zeros (an empty prefix shares nothing). Then fill the grid top-to-bottom, left-to-right, where each cell looks only at three already-solved neighbours: the one above, the one to the left, and the one diagonally up-left.
X[i] === Y[j]): extend the diagonal run — dp[i][j] = dp[i-1][j-1] + 1.dp[i][j] = max(dp[i-1][j], dp[i][j-1]).dp[m][n] holds the final LCS length.X = AGCAT Y = GAC dp grid (rows X, cols Y)
"" G A C
"" 0 0 0 0
A 0 0 1 1
G 0 1 1 1
C 0 1 1 2
A 0 1 2 2
T 0 1 2 2 <- LCS length = 2 ("AC" or "GA")function lcs(X, Y) {
const m = X.length, n = Y.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 (X[i - 1] === Y[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];
}