Forming the longest word in JavaScript

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.

Problem Example

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:

'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.

Solution Approach

The algorithm works by:

  • Sorting the array by length (descending) to check longest words first
  • For each word, checking if it can be formed as a subsequence of the input string
  • Returning the first valid word found (which will be the longest due to sorting)

Complete Implementation

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

const findLongestWord = (str = '', arr = []) => {
    // Sort array by length (descending) then lexically
    arr.sort((a, b) => {
        if (a.length !== b.length) {
            return b.length - a.length;
        }
        return a.localeCompare(b);
    });
    
    // Check each word to see if it can be formed from str
    for (const word of arr) {
        let index = -1;
        
        // Check if word is a subsequence of str
        for (const char of word) {
            index = str.indexOf(char, index + 1);
            if (index < 0) {
                break; // Character not found
            }
        }
        
        // If all characters were found in order, return this word
        if (index >= 0) {
            return word;
        }
    }
    
    return ''; // No valid word found
};

console.log(findLongestWord(str, arr));
gfdfg

How the Algorithm Works

The function uses a subsequence matching approach:

  1. Sort the array: Words are sorted by length (longest first) to ensure we find the longest valid word
  2. Subsequence check: For each word, we check if it can be formed by selecting characters from the input string in order
  3. Character matching: We use indexOf() with a starting position to ensure characters are found in the correct sequence
  4. Return first match: Since the array is sorted by length, the first valid word is automatically the longest

Alternative Example

const testStr = 'programming';
const testArr = ['prog', 'ram', 'program', 'gaming', 'ramp'];

console.log(findLongestWord(testStr, testArr));
program

Conclusion

This solution efficiently finds the longest word that can be formed as a subsequence of the input string. The sorting strategy ensures optimal performance by checking longer words first.

Updated on: 2026-03-15T23:19:00+05:30

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements