LeetCode: Maximum Number of Vowels in a Substring of Given Length

Find maximum number of vowels in any substring of given length k.

Posted on LeetCode Python

Solution

Calculate the number of vowels in the first k elements.

Use a sliding window approach to iterate through the array starting from index k. For each new element added to the window, add to the vowel count if the i-th element is a vowel, and subtract from the vowel count if the i - k-th element is a vowel. Update the maximum vowel count found so far.

Runtime

47 ms | Beats 95.01%

class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = {"a", "e", "i", "o", "u"}
count_vowels = 0
for i in range(k):
if s[i] in vowels:
count_vowels += 1
max_vowels = count_vowels
for i in range(k, len(s)):
if s[i] in vowels:
count_vowels += 1
if s[i - k] in vowels:
count_vowels -= 1
if count_vowels > max_vowels:
max_vowels = count_vowels
return max_vowels