Skip to content

Commit 06c5914

Browse files
Merge pull request #57 from shivam7147/main
LCS Visualizer
2 parents 4aa1db2 + b031757 commit 06c5914

File tree

6 files changed

+398
-0
lines changed

6 files changed

+398
-0
lines changed

package-lock.json

Lines changed: 106 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
"tailwind-merge": "^3.3.1"
3232
},
3333
"devDependencies": {
34+
"@commitlint/config-conventional": "^20.0.0",
3435
"@eslint/js": "^9.36.0",
3536
"@types/node": "^24.7.1",
3637
"@types/react": "^19.1.16",
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
export function longestCommonSubsequenceSteps(a = "", b = "") {
2+
const m = a.length;
3+
const n = b.length;
4+
5+
// ✅ initialize DP table
6+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
7+
const steps = [];
8+
9+
const snapshot = () => dp.map(row => [...row]);
10+
11+
// ✅ filling dp table
12+
for (let i = 1; i <= m; i++) {
13+
for (let j = 1; j <= n; j++) {
14+
if (a[i - 1] === b[j - 1]) {
15+
dp[i][j] = dp[i - 1][j - 1] + 1;
16+
steps.push({
17+
dp: snapshot(),
18+
active: { i, j },
19+
match: { i, j },
20+
message: `Characters match '${a[i - 1]}' at A[${i - 1}] & B[${j - 1}] → dp[${i}][${j}] = dp[${i - 1}][${j - 1}] + 1 = ${dp[i][j]}`
21+
});
22+
} else {
23+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
24+
steps.push({
25+
dp: snapshot(),
26+
active: { i, j },
27+
message: `No match. dp[${i}][${j}] = max(dp[${i - 1}][${j}] = ${dp[i - 1][j]}, dp[${i}][${j - 1}] = ${dp[i][j - 1]}) = ${dp[i][j]}`
28+
});
29+
}
30+
}
31+
}
32+
33+
// ✅ traceback to get sequence
34+
let i = m, j = n;
35+
let lcsChars = [];
36+
const path = [];
37+
38+
while (i > 0 && j > 0) {
39+
if (a[i - 1] === b[j - 1]) {
40+
lcsChars.push(a[i - 1]);
41+
path.push({ i, j });
42+
i--;
43+
j--;
44+
} else if (dp[i - 1][j] >= dp[i][j - 1]) i--;
45+
else j--;
46+
}
47+
48+
const finalPath = path.reverse();
49+
steps.push({
50+
dp: snapshot(),
51+
finalPath,
52+
message: `Final LCS sequence = '${lcsChars.reverse().join('')}'`,
53+
sequence: lcsChars.join('')
54+
});
55+
56+
return steps;
57+
}

0 commit comments

Comments
 (0)