InterviewPrepKit

Home / Coding / Sliding Window

Maximum Number of Vowels in a Substring of Given Length

medium Original β†—
Solving tips
  • This is a pure fixed-size window: count vowels in the first k chars, then slide updating by +1 if the entering char is a vowel and -1 if the leaving one is.
  • Use a set/frozenset of 'aeiou' for O(1) vowel tests; the window length never changes so there is no shrink loop.
  • Target O(n) time and O(1) space; optional early exit once the count reaches k since no window can beat it.
  • Common pitfall: the leaving index is s[right-k] (not right-k+1), and do not recount the whole slice each step or you silently reintroduce O(n*k).

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 = 3 β†’ 3 β€” the window "iii" is all vowels.
  • s = "aeiou", k = 2 β†’ 2 β€” every length-2 window ("ae", "ei", …) is two vowels.
  • s = "rhythm", k = 4 β†’ 0 β€” 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^9–10^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). (Nice micro-exit: if the count ever reaches k, no window can beat it.)
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.