Forming the longest word in JavaScript


Problem

We are required to write a JavaScript function that takes in a random English alphabet string, str, as the first argument and an array of strings, arr, as the second argument.

The task of our function is to try deleting some characters from the string str and check which longest word can be formed that exists in the array arr as well. Our function should return the longest possible string.

If there exists no such string, we should return an empty string.

For example, if the input to the function is −

const str = 'sdgfdfghdjh';
const arr = ['sdf', 'fghj', 'gfdfg', 'absc', 'a', 'hasl'];

Then the output should be −

const output = 'gfdfg';

Output Explanation:

Although the first and second element of the array can be formed by deleting characters from the string but ‘gfdfg’ is the longest string (5) which we can form from string str.

Example

The code for this will be −

 Live Demo

const str = 'sdgfdfghdjh';
const arr = ['sdf', 'fghj', 'gfdfg', 'absc', 'a', 'hasl'];
const findLongestWord = (str = '', arr = []) => {
   arr.sort((a, b) => {
      if (a.length !== b.length) {
         return b.length - a.length;
      };
      return a.localeCompare(b);
   });
   for(const word of arr){
      let index = -1;
      for(const char of word){
         index = str.indexOf(char, index + 1);
         if(index < 0){
            break;
         };
      };
      if (index >= 0){
         return word;
      };
   };
   return '';
};
console.log(findLongestWord(str, arr));

Code Explanation:

The steps we went through are −

  • Sort array arr by length first then lexical ordering.

  • Loop through each word in arr, if every char of word isn't in string str then we simply return.

  • And if every word matches, then we return the word.

And since we already sorted our dictionary, we can guarantee that the first match is our answer.

Output

The output in the console will be −

gfdfg

Updated on: 03-Mar-2021

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements