Skip to content

Commit e768008

Browse files
Merge pull request akshitagit#98 from yash0412/LCS-yash
Added LCS in dynamic programming
2 parents d58763b + 20eba9c commit e768008

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
3+
Longest Common Subsequence is a classical example of how to use dynamic programming with memorization
4+
to solve a complex problem in a much easier and faster way.
5+
6+
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them.
7+
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
8+
For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”.
9+
10+
The brute force method requires to find all possible subsequences of the given sequences and finding the longest common subsequence.
11+
This approach has exponential time complexity.
12+
13+
LCS with Dynamic Programming approach requires only O(mn) time, where m and n are the lengths of the given sequences.
14+
15+
*/
16+
17+
function lcs(p, q, m, n, dp) {
18+
var result = 0;
19+
if (m === 0 || n === 0) {
20+
result = 0;
21+
} else if (dp[m - 1][n - 1] !== null) {
22+
//If LCS value is already calcualted for this substring
23+
result = dp[m - 1][n - 1];
24+
} else if (p[m - 1] === q[n - 1]) {
25+
//If last character in substrings are the same
26+
result = 1 + lcs(p, q, m - 1, n - 1, dp);
27+
dp[m - 1][n - 1] = result;
28+
} else {
29+
//If last character in substrings are different
30+
31+
//find LCS by removing last character from string 1
32+
var temp1 = lcs(p, q, m - 1, n, dp);
33+
34+
//find LCS by removing last character from string 2
35+
var temp2 = lcs(p, q, m, n - 1, dp);
36+
37+
//take min of both results
38+
result = temp1 > temp2 ? temp1 : temp2;
39+
40+
//set the value in Matrix
41+
dp[m - 1][n - 1] = result;
42+
}
43+
return result;
44+
}
45+
46+
//input strings of size m and n
47+
var str1 = "nematode_knowledge";
48+
var str2 = "empty_bottle";
49+
50+
//Matrix of size mXn to store calculated values
51+
var dp = [];
52+
53+
//Prefill the matrix with null
54+
for (var i = 0; i < str1.length; i++) {
55+
dp[i] = [];
56+
for (var j = 0; j < str2.length; j++) {
57+
dp[i].push(null);
58+
}
59+
}
60+
61+
console.log(lcs(str1, str2, str1.length, str2.length, dp));

0 commit comments

Comments
 (0)