BudiBadu Logo

Maximum Vowels In Substring Length K

Sliding Window Easy 12 views
Like0

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

Example 1
Input
s = "abciiidef", k = 3
Output
3
Explanation

Substring "iii" contains 3 vowels.

Example 2
Input
s = "aeiou", k = 2
Output
2
Explanation

Any length-2 window has 2 vowels.

Example 3
Input
s = "leetcode", k = 3
Output
2
Explanation

Best window has 2 vowels.

Algorithm Flow

Recommendation Algorithm Flow for Maximum Vowels In Substring Length K - Budibadu
Recommendation Algorithm Flow for Maximum Vowels In Substring Length K - Budibadu

Best Answers

java
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;
    }
}