Maximum Number of Vowels in a Substring of Given Length LeetCode solution in JavaScript

1
var maxVowels = function (s, k) {
2
let vowels = ["a", "e", "i", "o", "u"];
3
let maxCount = 0;
4
let start = 0; // the left edge of the window
5
let count = 0; // count of vowels for current substring
6
// expanding the right edge of the window one character at a time
7
for (let end = 0; end < s.length; end++) {
8
// increment count of vowels for current substring if the current character is present in vowels array
9
if (vowels.includes(s[end])) {
10
count += 1;
11
}
12
// if substring is longer than K, let's shrink the window by moving left edge
13
if (end - start + 1 > k) {
14
// reduce the current count by one if the character on the left edge is vowel
15
if (vowels.includes(s[start])) {
16
count -= 1;
17
}
18
//shrinking the left edge of the window
19
start += 1;
20
}
21
// checking if current count is larger than current maximum count
22
maxCount = Math.max(maxCount, count);
23
// if maxCount is equal to K, no need to check further, it is the max possible count
24
if (maxCount == k) return maxCount;
25
}
26
return maxCount;
27
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0