Maximum Vowels In Substring Length K
In Maximum Vowels In Substring Length K, you are given a lowercase string s and an integer k. Your job is to find the largest number of vowels in any contiguous substring of length k. Think of it like sliding a fixed window across the string and tracking the best vowel count you ever see.
The efficient solution is a classic fixed-size sliding window. Start by counting vowels in the first window, then move one character at a time: add one when the incoming character is a vowel, subtract one when the outgoing character is a vowel, and update the maximum. This gives linear performance and matches judge expectations for mixed strings, all-vowel strings, and strings with zero vowels.
The judge includes edge behavior such as very short inputs and windows where counts change quickly between positions. Your function should return one integer, not a substring. The result is purely the maximum vowel count found among all valid windows of size k.
Examples
Substring "iii" contains 3 vowels.
Any length-2 window has 2 vowels.
Best window has 2 vowels.
Algorithm Flow

Best Answers
class Solution {
private boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
public int maximum_vowels_in_substring_length_k(String s, int k) {
int n = s.length();
if (k <= 0 || k > n) return 0;
int window = 0;
for (int i = 0; i < k; i++) if (isVowel(s.charAt(i))) window++;
int best = window;
for (int i = k; i < n; i++) {
if (isVowel(s.charAt(i))) window++;
if (isVowel(s.charAt(i-k))) window--;
if (window > best) best = window;
}
return best;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
