Skip to main content
Back to problems
#1456
Medium Algorithms

Maximum number of vowels in a substring of given length

String Sliding Window
61.6% acceptance
Feb 25, 2026
3917
152
Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_vowels(s: String, k: i32) -> i32 {
    let k = k as usize;
    let is_vowel = |c: u8| matches!(c, b'a' | b'e' | b'i' | b'o' | b'u');
    let bytes = s.as_bytes();
    let mut count = bytes[..k].iter().filter(|&&c| is_vowel(c)).count() as i32;
    let mut max = count;
    for i in k..bytes.len() {
      if is_vowel(bytes[i]) { count += 1; }
      if is_vowel(bytes[i - k]) { count -= 1; }
      if count > max { max = count; }
    }
    max
  }
}