I am trying to run the following code:
function LCS(s1, s2) {
let m = s1.length;
let n = s2.length;
let table = [];
for (let i = 0; i <= m; i++) {
table.push([]);
for (let j = 0; j <= n; j++) {
if (i === 0 || j === 0) {
table[i][j] = 0;
} else if (s1[i - 1] === s2[j - 1]) {
// Both s1 and s2 have the same element on the previous index
// so increase the length of common subsequence by 1 here
table[i][j] = table[i - 1][j - 1] + 1;
} else {
table[i][j] = max(table[i - 1][j], table[i][j - 1]);
}
}
// We've found the length here.
let index = table[m][n];
console.log(`The length of LCS between "${s1}" and "${s2}" is ${index}`);
// Now to get the sequence we need to backtrack from the m, n th index back to start.
let i = m;
let j = n;
let commonSubSeq = "";
while (i > 0 && j > 0) {
// If current character in both strings is same, then it is part of LCS.
if (s1[i - 1] === s2[j - 1]) {
commonSubSeq += s1[i - 1];
i--;
j--;
} else if (table[i - 1][j] > table[i][j - 1]) {
i--;
} else {
j--;
}
}
return commonSubSeq
.split("")
.reverse()
.join("");
}
}
console.log(LCS("AGGTAB", "GXTXAYB"));
I'm getting the following error:
if (i === 0 || j === 0) {
^
ReferenceError: i is not defined
at LCS (C:\Users\LCS-new.js:9:7)
I'm not able to understand why would this variable not be available in the nested scope?