Given a string s and an integer k, the objective is to determine the highest possible count of vowel letters within any contiguous substring of length k. Vowel letters are defined as 'a', 'e', 'i', 'o', 'u'.
A sliding window approach provides an efficient solution. The algorithm first calculates the vowel count in the initial window of size k. Subsequently, it slides the window across the string, updating the count by eavluating the character entering the window and the character leaving it.
Sliding Window Implementation:
function maxVowelsInSubstring(str, windowSize) {
const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
let currentVowelCount = 0;
let maxVowelCount = 0;
const strLength = str.length;
// Initialize the count for the first window
for (let i = 0; i < windowSize; i++) {
if (vowels.has(str[i])) {
currentVowelCount++;
}
}
maxVowelCount = currentVowelCount;
if (maxVowelCount === windowSize) return windowSize;
// Slide the window across the string
for (let right = windowSize; right < strLength; right++) {
const left = right - windowSize;
if (vowels.has(str[right])) currentVowelCount++;
if (vowels.has(str[left])) currentVowelCount--;
maxVowelCount = Math.max(maxVowelCount, currentVowelCount);
if (maxVowelCount === windowSize) break;
}
return maxVowelCount;
}
Explanation:
- A
Setis used for O(1) vowel lookup. - The first loop establishes the vowel count for the initial window.
- The main loop slides the window: the new character at index
rightis added to the count if it's a vowel, and the character at indexleft(exiting the window) is subtracted if it's a vowel. - The maximum count is tracked and returned.
Complexity Analysis:
- Time Complexity: O(n), where n is the length of the string, as each chaarcter is processed at most twice.
- Space Complexity: O(1), using only a few auxiliary variables.
Alternative Prefix Sum Approach:
A prefix sum array can also be used, where prefix[i] stores the total vowel count from the start of the string up to index i-1. The vowel count for any substring s[i : i+k] is then prefix[i+k] - prefix[i]. While this approach also runs in O(n) time, it requires O(n) extra space for the prefix array.
Handling Edge Cases:
- If the string length equals
k, the function returns the vowel count of the entire string. - If no vowels are present, the function correctly returns 0.