#3306
Count of Substrings Containing Every Vowel and K Consonants II
MediumHash TableStringSliding Window
Approaches
💡
Intuition
Time Space
The brute force approach involves generating all possible substrings of the given string and checking each one to see if it contains all vowels and exactly k consonants. This method is straightforward but inefficient for larger strings.
⚙️
Algorithm
3 steps- 1Step 1: Generate all possible substrings of the input string.
- 2Step 2: For each substring, count the number of vowels and consonants.
- 3Step 3: Check if the substring contains all vowels and exactly k consonants. If it does, increment the count.
solution.py17 lines
1# Full working Python code
2
3def countSubstrings(word, k):
4 vowels = set('aeiou')
5 count = 0
6 n = len(word)
7 for i in range(n):
8 for j in range(i + 1, n + 1):
9 substring = word[i:j]
10 vowel_count = sum(1 for char in substring if char in vowels)
11 consonant_count = sum(1 for char in substring if char.isalpha() and char not in vowels)
12 if vowel_count == 5 and consonant_count == k:
13 count += 1
14 return count
15
16# Example usage
17print(countSubstrings('aeioqq', 1)) # Output: 0Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.