Skip to content

Commit f81c8c5

Browse files
authored
Add longest common subsequence (thuva4#879)
* add js factorial * fix tests * add string partial sort * add LongestCommonSubsequence in JS Co-authored-by: Thuvarakan Tharmarajasingam <thuva4.dev@gmail.com>
1 parent 523843a commit f81c8c5

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const {lcs} = require('../index');
2+
3+
describe("LongestCommonSubsequence", () => {
4+
5+
it("should return 0 if length is 0", () => {
6+
expect(lcs("", "A")).toEqual(0);
7+
});
8+
9+
it("should return 0 if the string is undefined", () => {
10+
expect(lcs("A")).toEqual(0);
11+
});
12+
13+
it("should return 0 if the string is undefined", () => {
14+
expect(lcs("A", null)).toEqual(0);
15+
});
16+
17+
it("should return correct value for valid strings", () => {
18+
expect(lcs("AGGTAB", "GXTXAYB")).toEqual(4);
19+
});
20+
});
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const lcs = (string1, string2) => {
2+
3+
if (!string1 || !string2) return 0;
4+
5+
const string1Array = string1.split('');
6+
const string2Array = string2.split('');
7+
8+
const dpArray = [];
9+
10+
string1Array.forEach(() => {
11+
dpArray.push([]);
12+
});
13+
14+
for (let i = 0; i< string1Array.length; i += 1) {
15+
for (let j = 0; j< string2Array.length; j += 1) {
16+
if (string1Array[i] === string2Array[j]) {
17+
dpArray[i][j] = 1 + (dpArray[i-1]?.[j-1] ? dpArray[i-1][j-1] : 0)
18+
} else {
19+
dpArray[i][j] = Math.max(dpArray[i-1]?.[j] ? dpArray[i-1][j] : 0 , dpArray[i]?.[j-1] ? dpArray[i][j-1] : 0)
20+
}
21+
}
22+
}
23+
return dpArray[string1Array.length-1][string2Array.length-1]
24+
}
25+
26+
module.exports = {lcs};

0 commit comments

Comments
 (0)