function lcsLength(s1, s2) {
const m = s1.length, n = s2.length;
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (s1[i - 1] === s2[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];
}
console.log(lcsLength("AGGTAB", "GXTXAYB"));The longest common subsequence between "AGGTAB" and "GXTXAYB" is "GTAB" which has length 4.
The code uses a standard dynamic programming table to compute the LCS length and returns 4.
function lcsSequence(s1, s2) {
const m = s1.length, n = s2.length;
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (s1[i - 1] === s2[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]);
}
}
}
let i = m, j = n;
let lcs = [];
while (i > 0 && j > 0) {
if (s1[i - 1] === s2[j - 1]) {
lcs.push(s1[i - 1]);
i--;
j--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
i--;
} else {
j--;
}
}
return lcs.reverse().join('');
}
console.log(lcsSequence("ABCBDAB", "BDCABA"));The longest common subsequence between "ABCBDAB" and "BDCABA" is "BDAB".
The code reconstructs this sequence by moving backwards through the dp table.
The dynamic programming solution uses a 2D table of size m by n and fills each cell once.
Thus, the time complexity is O(m * n).
function lcsLength(s1, s2) {
const m = s1.length, n = s2.length;
const dp = Array(m).fill(Array(n).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (s1[i - 1] === s2[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 - 1][n - 1];
}
console.log(lcsLength("ABC", "AC"));The dp array is initialized with Array(m).fill(Array(n).fill(0)) which creates multiple references to the same inner array.
When the code tries to assign dp[i][j], it tries to modify a shared inner array, leading to unexpected behavior or TypeError when i or j is out of bounds.
The maximum LCS length is 4 for these strings.
The distinct LCS sequences are "BCAB", "BDAB", and "BCBA".
Thus, there are 3 distinct LCS sequences.
