Maximum number of vowels in a substring of given length

May 5, 2023

array-and-hashmap

Problem URL: Maximum number of vowels in a substring of given length

We will first count the number of vowels in the whole string. Then we will use a sliding window to find the maximum number of vowels in a substring of given length. We will return the result.

class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        vowels = {'a', 'e', 'i', 'o', 'u'}

        count = 0
        for i in range(k):
            count += int(s[i] in vowels)

        res = count
        for i in range(k, len(s)):
            count += int(s[i] in vowels)
            count -= int(s[i - k] in vowels)
            res = max(res, count)

        return res

Time complexity: O(n)
Space complexity: O(1)