forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Completion of LCS implementation in JS issue#2252 (jainaman224#2313)
- Loading branch information
1 parent
14c168d
commit 30c0c0a
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/* | ||
Problem Statement - Given two sequences, find the length of longest subsequence present in | ||
both of them.A subsequence is a sequence that can be derived from another sequence by | ||
deleting some or no elements without changing the order of the remaining elements. | ||
*/ | ||
|
||
const Longest_Common_Subsequence = (arr1, arr2) => { | ||
|
||
let LCS_def = Array.from({ length: arr1.length + 1 }, | ||
() => Array.from({ length: arr2.length + 1 }, | ||
() => 0)); | ||
|
||
for (let i = 0; i < arr1.length + 1; i++){ | ||
for (let j = 0; j < arr2.length+1; j++){ | ||
|
||
if (i == 0 || j == 0) { | ||
LCS_def[i][j] = 0; | ||
} | ||
|
||
// when the last character of both match, increase length of lcs by 1 | ||
else if (arr1[i - 1] == arr2[j - 1]) { | ||
LCS_def[i][j] = LCS_def[i - 1][j - 1] + 1; | ||
} | ||
|
||
/* | ||
when the last character is not same, take maximum obtained by adding | ||
one character to one of the subsequences. | ||
*/ | ||
else { | ||
LCS_def[i][j] = Math.max(LCS_def[i - 1][j], LCS_def[i][j - 1]) | ||
} | ||
} | ||
} | ||
|
||
return `The length of longest subsequence is: ${LCS_def[arr1.length][arr2.length]}`; | ||
|
||
} | ||
|
||
|
||
// I/P and O/P Examples | ||
|
||
const inputSet1 = [10, 15, 20, 25, 30, 35, 40]; | ||
const inputSet2 = [10, 12, 23, 25, 28, 30, 32, 40]; | ||
const result = Longest_Common_Subsequence(inputSet1, inputSet2); | ||
|
||
// The length of longest subsequence is: 4 | ||
console.log(result); |