Maximum Number of Vowels in a Substring of Given Length

Updated on 12 June, 2025
Maximum Number of Vowels in a Substring of Given Length header image

Problem Statement

The challenge requires the determination of the maximum number of vowels in any potential substring of a given string s with a fixed length k. Vowels in this context refer to the characters 'a', 'e', 'i', 'o', and 'u'. This task effectively combines aspects of string manipulation and sliding window techniques to efficiently count vowels in substrings of a specified length within a larger string.

Examples

Example 1

Input:

s = "abciiidef", k = 3

Output:

3

Explanation:

The substring "iii" contains 3 vowel letters.

Example 2

Input:

s = "aeiou", k = 2

Output:

2

Explanation:

Any substring of length 2 contains 2 vowels.

Example 3

Input:

s = "vultrcode", k = 3

Output:

2

Explanation:

"vul", "ultr", "trc", "rco", and "ode" — the substring "ode" contains 2 vowels.

Constraints

  • 1 <= s.length <= 10⁵
  • s consists of lowercase English letters.
  • 1 <= k <= s.length

Approach and Intuition

To solve this problem, we'll leverage the sliding window technique, which is well-suited for problems where we need to examine a substring or a segment of a list/array:

  1. Initialize a counter to keep track of the number of vowels in the current window of size k.

  2. Slide this window across the string from the beginning to the end, adjusting the count of vowels as the window moves:

    • Increase the count when a vowel enters the window.
    • Decrease the count when a vowel exits the window.
  3. Keep track of the maximum number of vowels counted in any window throughout the traversal.

Using the sliding window technique ensures that each character in the string is checked a minimal number of times, thus enhancing efficiency.

Step-by-step breakdown:

  1. Identify and mark the vowels in the string.

  2. Traverse the string while maintaining a window of size k.

  3. Use two pointers (or indices), say start and end, to represent the current window's boundaries.

  4. As end pointer increases to include new characters in the window:

    • Check if the new character is a vowel.
    • Update your current count of vowels.
  5. Compare and update a separate variable if the current window's vowel count exceeds the previously recorded maximum.

  6. Move the start pointer to the right (narrow the window from the left) and adjust the count of vowels.

  7. Continue this process until end has traversed the entire string.

  8. The maintained maximum count through this process will be the required maximum number of vowels in any window of size k in the string s.

This method is particularly effective as it keeps the operation within linear time complexity, optimally fitting within the constraints given.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int maximumVowels(string str, int windowSize) {
        unordered_set<char> vowelSet{'a', 'e', 'i', 'o', 'u'};
        
        // Initial population of the sliding window of size windowSize
        int currentVowelCount = 0;
        for (int i = 0; i < windowSize; i++) {
            currentVowelCount += vowelSet.count(str[i]);
        } 
        int maxVowels = currentVowelCount;
        
        // Sliding window technique to check every possible substrings of size windowSize
        for (int i = windowSize; i < str.length(); i++) {
            currentVowelCount += vowelSet.count(str[i]) - vowelSet.count(str[i - windowSize]);
            maxVowels = max(maxVowels, currentVowelCount);
        }
        
        return maxVowels;
    }
};

The provided C++ solution aims to find the maximum number of vowels in any substring of a given length from a provided string. The approach uses a sliding window technique and a set to efficiently check for vowels in the substring. Here's a breakdown of how the code achieves this:

  • A set named vowelSet contains all vowel characters ('a', 'e', 'i', 'o', 'u') for quick lookup.
  • The function maximumVowels starts by initializing the count of vowels (currentVowelCount) in the first substring, which is of the specified windowSize.
  • The initial count is obtained by iterating through the first windowSize characters of the string and checking if each character is a vowel using the vowelSet.
  • The variable maxVowels is set to the value of currentVowelCount after the initial population of the sliding window.
  • The function then iterates through the string starting from the index windowSize. In each iteration, the window slides one character to the right:
    • It subtracts the count of the character that is sliding out of the window (the one at the beginning of the previous window),
    • Adds the count of the new character that has entered the window (at the end of the current window).
  • After updating currentVowelCount, the code compares it with maxVowels to store the maximum value found so far.
  • Once the loop completes, the function returns maxVowels, which is the maximum count of vowels found in any substring of length windowSize within the input string.

This method efficiently finds the solution by maintaining a dynamic count of vowels as the window slides through the string, rather than recalculating the count for each new substring. This reduces the computational complexity and makes the method suitable for large inputs.

java
class Solution {
    public int findMaxVowels(String str, int length) {
        Set<Character> vowelSet = Set.of('a', 'e', 'i', 'o', 'u');
        
        int currentCount = 0;
        for (int j = 0; j < length; j++) {
            currentCount += vowelSet.contains(str.charAt(j)) ? 1 : 0;
        }
        int maxCount = currentCount;
        
        for (int j = length; j < str.length(); j++) {
            currentCount += vowelSet.contains(str.charAt(j)) ? 1 : 0;
            currentCount -= vowelSet.contains(str.charAt(j - length)) ? 1 : 0;
            maxCount = Math.max(maxCount, currentCount);
        }
        
        return maxCount;
    }
}

To tackle the problem of finding the maximum number of vowels in a substring of a specified length within a given string using Java, follow this structured approach:

  • Initialize a set of characters to represent the vowels: 'a', 'e', 'i', 'o', 'u'. This set aids in efficaciously checking if a character is a vowel.

  • Use a sliding window technique:

    • First, calculate the number of vowels in the initial window of the given length. Track this using currentCount.
    • Slide the window across the string by one character at a time from the start position equal to the length of the substring to the end of the string:
      • Increment the vowel count if the new character entering the window on the right is a vowel.
      • Decrement the vowel count if the character that leaves the window on the left is a vowel.
    • Maintain a variable maxCount to record the maximum number of vowels found during any window position.
  • Update and compare the maximum count efficiently using Math.max() function. This function proves useful in reducing if-else constructs and ensuring the maximum count is updated in a single line.

By the end of the implementation, the method will return the maximum count of vowels found in any substring of the specified length. This solution leverages efficient data structures and algorithms such as sets for fast lookup and a dynamic sliding window technique for optimal computation.

python
class Solution:
    def maximumVowels(self, string: str, length: int) -> int:
        vowel_set = {'a', 'e', 'i', 'o', 'u'}
        
        # Initialize vowel count in the initial window of length 'length'
        vowel_count = 0
        for idx in range(length):
            vowel_count += string[idx] in vowel_set
        max_vowels = vowel_count
        
        # Move the window one character at a time
        for idx in range(length, len(string)):
            vowel_count += string[idx] in vowel_set
            vowel_count -= string[idx - length] in vowel_set
            max_vowels = max(max_vowels, vowel_count)
        
        return max_vowels

This solution finds the maximum number of vowels in a substring of the specified length within the given string. Written in Python, the approach revolves around a sliding window technique. Here's a concise summary of how the solution operates:

  • Start by preparing a set of vowels to use for easy lookup.
  • Compute the number of vowels in the first substring (the initial window) of the given length.
  • Use a sliding window technique to examine the rest of the string:
    1. For each new character in the window, check if it's a vowel and update the current vowel count accordingly.
    2. Simultaneously, remove the count of the vowel that is sliding out of the current window.
    3. Continuously update the maximum vowel count encountered.
  • Return the maximum count found during the sliding window execution.

This method is efficient as it avoids recalculating the vowel count for every new window, reducing redundancy and improving performance.

Comments

No comments yet.