Finding the length of longest vowel substring in a string using JavaScript

Problem

We are required to write a JavaScript function that takes in a string. Our function should return the length of the longest contiguous substring that contains only vowels.

Approach

The solution uses a sliding window approach to track consecutive vowels. We maintain two variables: cur for the current vowel sequence length and max for the longest sequence found so far.

Example

Following is the code −

const str = 'schooeal';
const findLongestVowel = (str = '') => {
    let cur = 0;
    let max = 0;
    for (let i = 0; i  max) {
                max = cur;
            }
        } else {
            cur = 0;
        }
    }
    return max;
};
console.log(findLongestVowel(str));

Output

4

How It Works

The algorithm iterates through each character:

  • If the character is a vowel (a, e, i, o, u), increment the current count
  • Update the maximum if current count exceeds it
  • If a consonant is found, reset the current count to 0

Testing with Different Examples

console.log(findLongestVowel('beautiful'));  // 'eau' = 3
console.log(findLongestVowel('programming')); // 'a' = 1
console.log(findLongestVowel('aeiou'));       // 'aeiou' = 5
console.log(findLongestVowel('bcdfg'));       // No vowels = 0
3
1
5
0

Conclusion

This sliding window approach efficiently finds the longest vowel substring in O(n) time complexity. The algorithm resets the counter when encountering consonants and tracks the maximum length throughout the iteration.

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

572 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements