Skip to content
Problem 1456 · LeetCode 1456(opens in a new tab)

Maximum Number of Vowels in a Substring of Given Length

MediumSliding windows

You get a string s of lowercase letters and a whole number k. Look at every block of k letters in a row inside s.

Return the largest number of vowels any one of those blocks holds. The vowels are a, e, i, o and u.

Example 1

Input:  s = "bxoaeyu", k = 3
Output: 3
Why:    the block "oae" is all vowels
2 more examples and the constraints

Example 2

Input:  s = "rhythm", k = 2
Output: 0
Why:    there are no vowels at all

Example 3

Input:  s = "quiet", k = 4
Output: 3
Why:    "quie" and "uiet" each hold 3 vowels

Constraints

  • 1 ≤ length of s ≤ 100,000
  • s has only lowercase English letters
  • 1 ≤ k ≤ length of s

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count every windowO(n · k)
  2. Sliding window countO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 letters, k = 50,000Verdict
Count every windowO(n · k)
Too slow for long strings
Sliding window countO(n)
Best; two checks per letter

n = length of s, k = window length.

Edge cases to test

  • No vowels. "rhythm" gives 0 for any k.
  • k equals the length. There is one window: the whole string.
  • k is 1. The answer is 1 if the string has any vowel, else 0.
  • All vowels. Every window is full of vowels, so the answer is k.

Common mistakes

  • Removing s[i − k + 1] instead of s[i − k], so the window shrinks to k − 1.
  • Subtracting the leaving letter before the window has k letters, which drives the count negative.
  • Counting y as a vowel; only a, e, i, o and u count here.

How to talk through it

  1. 1Clarify. Only lowercase letters? Is y a vowel? (No.) Can k equal the length?
  2. 2Give the brute force. Count each of the n − k + 1 windows from scratch: O(n · k).
  3. 3Spot the overlap. Neighbouring windows differ by one letter in and one letter out.
  4. 4Code the window. One loop: add the new letter, drop s[i − k] once i ≥ k, update best.
  5. 5Test out loud. Run no vowels, k = 1 and k equal to the length.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?