Given a string
Vowel letters in English are
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.
Output: 2
Explanation: "ode" contain 2 vowels.
Constraints:
1 <= s.length <= 105 s consists of lowercase English letters.1 <= k <= s.length
Contents
Solution 1 - Using sliding window technique, keep track of maximum number of vowels found in a substring of length K
In this approach, we are going to apply sliding window technique using two pointers
Implementation steps:
-
First, create four variables
left ,right that we will use to adjust the window,vowels to store total number of vowels found in current window, andmaxVowels to hold the maximum vowels found so far in all substrings of lengthk . -
Next, run a
while loop untilright pointer reaches end of strings , and do the following:-
Take the current character, and if that is a vowel, i.e. if the character is
'a' ,'e' ,'i' ,'o' , or'u' , then increment the count ofvowels by 1. -
Next, check if we are going out of bounds of maximum substring length allowed
k , that isright - left +1 > k then adjust the sliding window. Take the character atleft pointer and incrementleft pointer, and if that is a vowel, then decrement the count ofvowels by 1, -
Next, update the
maxVowels with maximum value betweenvowels count in current window and the currentmaxVowels . -
At the end of while loop increment
right pointer to move to the next element in strings .
-
Take the current character, and if that is a vowel, i.e. if the character is
-
Finally, return
maxVowels .
Complexity Analysis:
Time complexity: Above code runs in O(n) time, where
Space complexity: O(1).
Above implementations source code can be found at