Skip to content

Commit b109436

Browse files
authored
feat: Added Longest Common Subsequence (TheAlgorithms#173)
1 parent d64e4fb commit b109436

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

dynamic_programming/lcs.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Find the Longest Common Subsequence (LCS) of two strings.
3+
* @param text1 - The first input string.
4+
* @param text2 - The second input string.
5+
* @returns The longest common subsequence as a string.
6+
*/
7+
8+
export const longestCommonSubsequence = (text1: string, text2: string): string => {
9+
const m = text1.length;
10+
const n = text2.length;
11+
12+
// Create a 2D array to store the lengths of LCS
13+
const dp: number[][] = Array.from({ length: m + 1 }, () =>
14+
Array(n + 1).fill(0)
15+
);
16+
17+
// Fill in the DP table
18+
for (let i = 1; i <= m; i++) {
19+
for (let j = 1; j <= n; j++) {
20+
if (text1[i - 1] === text2[j - 1]) {
21+
dp[i][j] = dp[i - 1][j - 1] + 1;
22+
} else {
23+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
24+
}
25+
}
26+
}
27+
28+
// Reconstruct the LCS from the DP table
29+
let i = m;
30+
let j = n;
31+
const lcs: string[] = [];
32+
while (i > 0 && j > 0) {
33+
if (text1[i - 1] === text2[j - 1]) {
34+
lcs.unshift(text1[i - 1]);
35+
i--;
36+
j--;
37+
} else if (dp[i - 1][j] > dp[i][j - 1]) {
38+
i--;
39+
} else {
40+
j--;
41+
}
42+
}
43+
44+
return lcs.join('');
45+
}
46+

dynamic_programming/test/lcs.test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { longestCommonSubsequence } from "../lcs";
2+
3+
describe("longestCommonSubsequence", () => {
4+
it("should return the longest common subsequence", () => {
5+
expect(longestCommonSubsequence("ABCD", "ACDF")).toBe("ACD");
6+
7+
expect(longestCommonSubsequence("AGGTAB", "GXTXAYB")).toBe("GTAB");
8+
9+
expect(longestCommonSubsequence("abcdef", "xyz")).toBe("");
10+
11+
expect(longestCommonSubsequence("", "")).toBe("");
12+
});
13+
14+
it("should handle cases with spaces and special characters", () => {
15+
expect(longestCommonSubsequence("A B C D", "A C D E")).toBe("A C D");
16+
17+
expect(longestCommonSubsequence("1234$%^", "!@#$%^")).toBe("$%^");
18+
});
19+
20+
it("should handle cases with longer input strings", () => {
21+
expect(
22+
longestCommonSubsequence(
23+
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
24+
"Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
25+
)
26+
).toBe("e iumoor it t oeetr ag li.");
27+
});
28+
});

0 commit comments

Comments
 (0)