Practice › Sliding Window
Maximum Vowels in a Window
Easy · Sliding Window · Asked at Amazon, Google, TCS, Infosys
Print the largest number of vowels (a e i o u) in any substring of s of length exactly k.
Input
First line: s (lowercase letters). Second line: k.
Output
The maximum number of vowels.
Constraints
- 1 ≤ k ≤ |s| ≤ 10^5
Count the vowels in the first window, then slide: add 1 if the entering letter is a vowel, subtract 1 if the leaving letter is.
Example 1
Input
abciiidef 3
Output
3
Example 2
Input
leetcode 3
Output
2
Hints
- Every window has the same length, so slide it one step at a time.
- Only the letter entering and the letter leaving change the vowel count.
Approach
Walk i over the string: add 1 if s[i] is a vowel; once i ≥ k, subtract 1 if s[i − k] (the letter leaving) is a vowel. From i = k − 1 on, every step is a full window — track the maximum count.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
bool vowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; }
int main() {
string s;
int k;
cin >> s >> k;
int cur = 0, best = 0;
for (int i = 0; i < (int) s.size(); i++) {
cur += vowel(s[i]);
if (i >= k) cur -= vowel(s[i - k]);
if (i >= k - 1) best = max(best, cur);
}
cout << best << "\n";
return 0;
}Python solution
import sys
s, k = sys.stdin.read().split()[:2]
k = int(k)
V = set("aeiou")
cur = best = 0
for i, c in enumerate(s):
cur += c in V
if i >= k:
cur -= s[i - k] in V
if i >= k - 1 and cur > best:
best = cur
print(best)Java solution
import java.io.*;
public class Main {
static boolean vowel(char c) {
return "aeiou".indexOf(c) >= 0;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine().trim();
int k = Integer.parseInt(br.readLine().trim());
int cur = 0, best = 0;
for (int i = 0; i < s.length(); i++) {
if (vowel(s.charAt(i))) cur++;
if (i >= k && vowel(s.charAt(i - k))) cur--;
if (i >= k - 1) best = Math.max(best, cur);
}
System.out.println(best);
}
}Solve Maximum Vowels in a Window online · All practice problems