Finding the longest common consecutive substring between two strings in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two strings. Let’s call them str1 and str2. The function should then find out the longest consecutive string that is common to both the input strings and return that common string.

For example −

If the input strings are −

const str1 = 'ABABC';
const str2 = 'BABCA';

Then the output string should be −

const output = 'BABC';

Example

Following is the code −

const str1 = 'ABABC';
const str2 = 'BABCA';
const findCommon = (str1 = '', str2 = '') => {
   const s1 = [...str1];
   const s2 = [...str2];
   const arr = Array(s2.length + 1).fill(null).map(() => {
      return Array(s1.length + 1).fill(null);
   });
   for (let j = 0; j <= s1.length; j += 1) {
      arr[0][j] = 0;
   }
   for (let i = 0; i <= s2.length; i += 1) {
      arr[i][0] = 0;
   }
   let len = 0;
   let col = 0;
   let row = 0;
   for (let i = 1; i <= s2.length; i += 1) {
      for (let j = 1; j <= s1.length; j += 1) {
         if (s1[j - 1] === s2[i - 1]) {
            arr[i][j] = arr[i - 1][j - 1] + 1;
         }
         else {
            arr[i][j] = 0;
         }
         if (arr[i][j] > len) {
            len = arr[i][j];
            col = j;
            row = i;
         }
      }
   }
   if (len === 0) {
      return '';
   }
   let res = '';
   while (arr[row][col] > 0) {
      res = s1[col - 1] + res;
      row -= 1;
      col -= 1;
   }
   return res;
};
console.log(findCommon(str1, str2));

Output

Following is the output on console −

BABC
raja
Published on 11-Dec-2020 09:13:50
Advertisements