Maximum Number of Vowels in a Substring of Given Length
Given a string sksk
Vowel letters in English are 'a''e''i''o''u'
Example 1
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
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.
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.
Example 3
Input: s = "cscode", k = 3
Output: 2
Explanation: "ode" contain 2 vowels.
Output: 2
Explanation: "ode" contain 2 vowels.
Constraints:
1 <= s.length <= 105 consists of lowercase English letters.s1 <= k <= s.length
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 leftrightkk
Implementation steps:
-
First, create four variables
,left that we will use to adjust the window,right to store total number of vowels found in current window, andvowels to hold the maximum vowels found so far in all substrings of lengthmaxVowels .k -
Next, run a
loop untilwhile pointer reaches end of stringright , and do the following:s-
Take the current character, and if that is a vowel, i.e. if the character is
,'a' ,'e' ,'i' , or'o' , then increment the count of'u' by 1.vowels -
Next, check if we are going out of bounds of maximum substring length allowed
, that isk then adjust the sliding window. Take the character atright - left +1 > k pointer and incrementleft pointer, and if that is a vowel, then decrement the count ofleft by 1,vowels -
Next, update the
with maximum value betweenmaxVowels count in current window and the currentvowels .maxVowels -
At the end of while loop increment
pointer to move to the next element in stringright .s
-
Take the current character, and if that is a vowel, i.e. if the character is
-
Finally, return
.maxVowels
Java
public class MaximumNumberOfVowelsInSubstringOfGivenLength {
static int maxVowels(String s, int k) {
int left = 0;
int right =0;
int vowels = 0;
int maxVowels = 0;
while(right < s.length()) {
char current = s.charAt(right);
if(isVowel(current)) {
vowels++;
}
while(right-left+1>k){
char leftChar = s.charAt(left);
if(isVowel(leftChar)) {
vowels--;
}
left++;
}
maxVowels = Math.max(maxVowels, vowels);
right++;
}
return maxVowels;
}
static boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
public static void main(String[] args) {
System.out.println(maxVowels("abciiidef", 3));
System.out.println(maxVowels("aeiou", 2));
System.out.println(maxVowels("cscode", 3));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time, where ns
Space complexity: O(1).
Above implementations source code can be found at