Skip to content

Commit

Permalink
Completion of LCS implementation in JS issue#2252 (jainaman224#2313)
Browse files Browse the repository at this point in the history
  • Loading branch information
abhushanaj authored and Amitsharma45 committed May 31, 2020
1 parent 14c168d commit 30c0c0a
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Longest_Common_Subsequence/Longest_Common_Subsequence.js
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);

0 comments on commit 30c0c0a

Please sign in to comment.