MediumStringSliding Window

Maximum Number of Vowels in a Substring of Given Length

1 approach, code in every language

Problem description

You are given a string s made of lowercase English letters and an integer k. A vowel is any of the characters 'a', 'e', 'i', 'o', or 'u'.

Consider every contiguous substring of s whose length is exactly k. Your task is to return the greatest number of vowels that appear in any single one of those substrings.

If no substring of length k exists, there is nothing to evaluate, but the constraints guarantee that k never exceeds the length of s.

Example 1

Input: s = "abciiidef", k = 3

Output: 3

The substring "iii" spans three positions and every character is a vowel, giving the maximum count of 3.

Example 2

Input: s = "aeiou", k = 2

Output: 2

Every window of length 2 is composed entirely of vowels, so the best any window can reach is 2.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.
  • 1 <= k <= s.length

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free