Sponsored
Sponsored
This approach uses the sliding window technique to efficiently find the maximum number of vowels in any substring of length k.
We first calculate the number of vowels in the initial window of length k. Then, for each subsequent character, we slide the window by one character to the right: we remove the character that goes out of the window and add the one that comes into the window, updating our vowel count accordingly.
This ensures that we examine each character in the string only once, leading to an O(n) time complexity.
Time Complexity: O(n), where n is the length of the string. We iterate through the string with a constant number of operations for each character.
Space Complexity: O(1), as we use a fixed amount of extra space.
1function maxVowels(s, k) {
2 const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
3
JavaScript uses a Set for vowels for constant-time membership checking. An initial loop calculates the count of vowels in the first k-long window. As we proceed through the string, the vowel count is adjusted for every sliding position by adding one for new vowel additions to the window and subtracting one for vowel exits, while the maxCount variable maintains the highest count obtained.
Another way to tackle this problem is to use a combination of prefix sums and binary search to precompute regions of vowels.
First, we establish a prefix sum array that accumulates the number of vowels encountered at each character index in the string. Then, we use a binary search within this prefix sum to efficiently find the maximum number of vowels in any moving window of length k.
This approach is more complex and is generally less optimal than the sliding window approach but provides an alternative methodology.
Time Complexity: O(n), for prefix sum construction and analysis.
Space Complexity: O(n), for the prefix sum array.
1#include <iostream>
2#include <vector>
3#include <string>
4using namespace std;
5
6bool isVowel(char ch) {
7 return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
8}
9
10int maxVowels(const string &s, int k) {
11 int n = s.size();
12 vector<int> prefix(n + 1, 0);
13
14 for (int i = 0; i < n; ++i) {
15 prefix[i + 1] = prefix[i] + isVowel(s[i]);
16 }
17
18 int maxCount = 0;
19 for (int i = k; i <= n; ++i) {
20 maxCount = max(maxCount, prefix[i] - prefix[i - k]);
21 }
22
23 return maxCount;
24}
25
26int main() {
27 cout << maxVowels("abciiidef", 3) << endl;
28 return 0;
29}
The C++ version constructs a prefix sum array that records cumulative vowel counts. With this array, the maximum number of vowels in any substring of length k is the largest difference between prefix sums spaced by k indices, allowing for efficient lookups.