InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Maximum Number of Vowels in a Substring of Given Length

medium Original ↗ 00:00

Problem

Given a lowercase string s and an integer k, look at every contiguous substring of s of length exactly k and return the largest number of vowels (a, e, i, o, u) any of them contains.

The answer is a count, not the substring itself. If s contains no vowels at all, the answer is 0.

Examples

  • s = "abciiidef", k = 33 — the window "iii" is all vowels.
  • s = "aeiou", k = 22 — every length-2 window ("ae", "ei", …) is two vowels.
  • s = "rhythm", k = 40 — no vowels anywhere, so every window scores zero.

Constraints

  • 1 <= len(s) <= 10^5
  • 1 <= k <= len(s)
  • s consists of lowercase English letters only.

Counting vowels from scratch in each of the n - k + 1 windows costs O(n·k) — up to ~10^910^10 checks. The expected solution updates the count in O(1) per slide.

Think about it first

Hint 1 The windows all have the same length and adjacent ones overlap in k - 1 characters. Do you really need to recount the shared part?
Hint 2 When the window slides one step, exactly one character enters on the right and one leaves on the left. How does each affect the vowel count?
Hint 3 Count vowels in the first k characters. Then for each slide: add 1 if the entering character is a vowel, subtract 1 if the leaving one is. Track the maximum; a set of the five vowels makes each test O(1). Optional early exit: once the count reaches k, no window can beat it.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug