Length of longest string chain in JavaScript


Word Chain

Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac".

A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.

Problem

We are required to write a JavaScript function that takes in an array of strings, arr, as the first and the only argument.

Each string in the array arr consists of English lowercase letters. Our function should return the longest possible length of a word chain with words chosen from the given array, arr.

For example, if the input to the function is −

const arr = ["a","b","ba","bca","bda","bdca"];

Then the output should be −

const output = 4;

Output Explanation:

One of the longest word chains is "a","ba","bda","bdca".

Example

The code for this will be −

const arr = ["a","b","ba","bca","bda","bdca"];
const longestStrChain = (arr) => {
   arr.sort((a, b) => a.length - b.length);
   const isPredecessor = (word1 = '', word2 = '') => {
      if(Math.abs(word1.length - word2.length) !== 1){
         return false;
      };
      for(let i = 0; i < word2.length; i++){
         const word = word2.slice(0, i) + word2.slice(i + 1);
         if(word === word1){
            return true;
         };
      };
      return false;
   };
   const array = [];
   let max = 0;
   for(let i = arr.length - 1; i >= 0; i--){
      array[i] = 1;
      for(let j = arr.length - 1; j > i; j--){
         if(isPredecessor(arr[i], arr[j])){
            array[i] = Math.max(
               array[i],
               1 + array[j],
            );
         };
      };
      max = Math.max(max, array[i]);
   };
   return max;
};
console.log(longestStrChain(arr));

Output

And the output in the console will be −

4

Updated on: 07-Apr-2021

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements