#1456
Maximum Number of Vowels in a Substring of Given Length
MediumStringSliding WindowSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a sliding window approach to maintain a window of size k. As we move the window, we efficiently update the count of vowels without recounting them from scratch.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to count vowels in the first window of size k.
- 2Step 2: Slide the window one character at a time, adding the next character and removing the first character of the previous window.
- 3Step 3: Update the maximum count of vowels found during the sliding process.
solution.py13 lines
1def maxVowels(s, k):
2 vowels = 'aeiou'
3 max_count = 0
4 current_count = 0
5 for i in range(len(s)):
6 if s[i] in vowels:
7 current_count += 1
8 if i >= k:
9 if s[i - k] in vowels:
10 current_count -= 1
11 if i >= k - 1:
12 max_count = max(max_count, current_count)
13 return max_countℹ
Complexity note: The time complexity is O(n) because we only traverse the string once. The space complexity is O(1) as we are using a fixed number of variables for counting.
- 1Using a sliding window allows us to efficiently manage the count of vowels without re-evaluating the entire substring.
- 2The problem can be solved in linear time, which is crucial for handling larger inputs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.