1+ # max_vowels.py
2+
3+ """
4+ Problem:
5+ Find the maximum number of vowels in any substring of length k.
6+
7+ This file includes:
8+ 1. Brute Force Approach (for understanding)
9+ 2. Sliding Window Approach (optimal)
10+
11+ Author: Your Name
12+ """
13+
14+ class Solution :
15+
16+ # ------------------------------------------------------------
17+ # 🔴 Method 1: Brute Force Approach (O(n * k))
18+ # ------------------------------------------------------------
19+ def maxVowels_bruteforce (self , s : str , k : int ) -> int :
20+ """
21+ Logic:
22+ - Check every substring of size k
23+ - Count vowels in each substring
24+ - Keep track of maximum
25+
26+ Time Complexity: O(n * k)
27+ Space Complexity: O(1)
28+ """
29+
30+ vowels = {'a' , 'e' , 'i' , 'o' , 'u' }
31+ max_count = 0
32+
33+ # Loop through all possible starting indices
34+ for i in range (len (s ) - k + 1 ):
35+ count = 0
36+
37+ # Check substring of length k
38+ for j in range (i , i + k ):
39+ if s [j ] in vowels :
40+ count += 1
41+
42+ # Update maximum vowels found
43+ max_count = max (max_count , count )
44+
45+ return max_count
46+
47+
48+ # ------------------------------------------------------------
49+ # 🟢 Method 2: Sliding Window Approach (O(n)) ✅ Optimal
50+ # ------------------------------------------------------------
51+ def maxVowels (self , s : str , k : int ) -> int :
52+ """
53+ Logic:
54+ - Maintain a window of size k
55+ - Add right character (r)
56+ - Remove left character (l) when window exceeds size k
57+ - Track vowel count dynamically
58+
59+ Time Complexity: O(n)
60+ Space Complexity: O(1)
61+ """
62+
63+ vowels = {'a' , 'e' , 'i' , 'o' , 'u' }
64+ count = 0 # current number of vowels in window
65+ max_count = 0 # result
66+ l = 0 # left pointer
67+
68+ # Iterate through string using right pointer
69+ for r in range (len (s )):
70+
71+ # Step 1: Add current character to window
72+ if s [r ] in vowels :
73+ count += 1
74+
75+ # Step 2: If window size exceeds k, shrink from left
76+ if r - l + 1 > k :
77+ if s [l ] in vowels :
78+ count -= 1
79+ l += 1
80+
81+ # Step 3: If window size is exactly k, update answer
82+ if r - l + 1 == k :
83+ max_count = max (max_count , count )
84+
85+ return max_count
86+
87+
88+ # ------------------------------------------------------------
89+ # 🧪 Test the implementation
90+ # ------------------------------------------------------------
91+ if __name__ == "__main__" :
92+ sol = Solution ()
93+
94+ s = "abciiidef"
95+ k = 3
96+
97+ print ("Input:" , s , "k =" , k )
98+ print ("Brute Force Output:" , sol .maxVowels_bruteforce (s , k ))
99+ print ("Sliding Window Output:" , sol .maxVowels (s , k ))
0 commit comments