Maximum Number of Vowels in a Substring of Length K

Problem

Find the maximum number of vowels in any substring of a given fixed length k.

Input:  s = "abciiidef", k = 3
Output: 3   ("iii")

Python Solution

def max_vowels(s, k):
    vowels = set("aeiou")
    count = sum(1 for ch in s[:k] if ch in vowels)
    best = count
    for i in range(k, len(s)):
        if s[i] in vowels:
            count += 1
        if s[i - k] in vowels:
            count -= 1
        best = max(best, count)
    return best

C++ Solution

int maxVowels(string s, int k) {
    auto isVowel = [](char c) { return c=='a'||c=='e'||c=='i'||c=='o'||c=='u'; };
    int count = 0;
    for (int i = 0; i < k; i++) count += isVowel(s[i]);
    int best = count;
    for (int i = k; i < s.size(); i++) {
        count += isVowel(s[i]);
        count -= isVowel(s[i - k]);
        best = max(best, count);
    }
    return best;
}

Java Solution

class Solution {
    private boolean isVowel(char c) {
        return c=='a'||c=='e'||c=='i'||c=='o'||c=='u';
    }

    public int maxVowels(String s, int k) {
        int count = 0;
        for (int i = 0; i < k; i++) if (isVowel(s.charAt(i))) count++;
        int best = count;
        for (int i = k; i < s.length(); i++) {
            if (isVowel(s.charAt(i))) count++;
            if (isVowel(s.charAt(i - k))) count--;
            best = Math.max(best, count);
        }
        return best;
    }
}

Complexity

Time: O(n) — each character is checked once when entering and once when leaving the window. Space: O(1) — a fixed vowel check, no extra structure.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.