BudiBadu Logo

Maximum Vowels In Substring Length K

Sliding Window Easy 4 views
Like0

You are given a lowercase string s and an integer k. Among all substrings of length k, return the maximum number of vowels found in any one substring.

This is a fixed-size sliding window counting problem. Start by counting vowels in the first k characters. Then move the window one character at a time: add 1 if the incoming character is a vowel, subtract 1 if the outgoing character is a vowel, and track the best count seen so far.

Because each character is processed a constant number of times, the solution runs in O(n) time.

Example 1:

Input: s = "abciiidef", k = 3

Output: 3

Explanation: Substring "iii" has 3 vowels, which is the maximum.

Example 2:

Input: s = "aeiou", k = 2

Output: 2

Explanation: Every window of size 2 contains exactly 2 vowels.

Example 3:

Input: s = "leetcode", k = 3

Output: 2

Explanation: Best windows like "lee" or "eet" contain 2 vowels.

Constraints: 1 <= s.length <= 10^5, 1 <= k <= s.length

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