From 651d95c437eddbc8e0daa3780ca4cfab03d7b66a Mon Sep 17 00:00:00 2001 From: Nick Cordova Date: Sat, 1 Jun 2019 15:39:12 -0500 Subject: [PATCH] longestCommonSubsequence optimization The lcsMatrix creation can be optimized. --- .../longestCommonSubsequence.js | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/algorithms/sets/longest-common-subsequence/longestCommonSubsequence.js b/src/algorithms/sets/longest-common-subsequence/longestCommonSubsequence.js index 41248273..946c0aad 100644 --- a/src/algorithms/sets/longest-common-subsequence/longestCommonSubsequence.js +++ b/src/algorithms/sets/longest-common-subsequence/longestCommonSubsequence.js @@ -5,18 +5,8 @@ */ export default function longestCommonSubsequence(set1, set2) { // Init LCS matrix. - const lcsMatrix = Array(set2.length + 1).fill(null).map(() => Array(set1.length + 1).fill(null)); - - // Fill first row with zeros. - for (let columnIndex = 0; columnIndex <= set1.length; columnIndex += 1) { - lcsMatrix[0][columnIndex] = 0; - } - - // Fill first column with zeros. - for (let rowIndex = 0; rowIndex <= set2.length; rowIndex += 1) { - lcsMatrix[rowIndex][0] = 0; - } - + const lcsMatrix = Array(set2.length + 1).fill().map(() => Array(set1.length + 1).fill().map(() => 0)); + // Fill rest of the column that correspond to each of two strings. for (let rowIndex = 1; rowIndex <= set2.length; rowIndex += 1) { for (let columnIndex = 1; columnIndex <= set1.length; columnIndex += 1) {