Problem Description
Given a string word and a non-negative integer k, count the total number of substrings of word that contain every vowel ('a', 'e', 'i', 'o', and 'u') at least once and exactly k consonants.
Key Insights
- We need to check every possible substring.
- For each substring, count vowels and consonants.
- The substring is valid if it contains all vowels (each at least once) and exactly k consonants.
- Since the maximum word length is small (at most 250), an O(n²) solution is acceptable.
- Early termination is possible during the inner loop when the consonant count exceeds k.
Space and Time Complexity
Time Complexity: O(n²) in the worst case, where n is the length of the string. Space Complexity: O(1) extra space, since we only use a fixed-size frequency counter for vowels and a counter for consonants.
Solution
We can use a brute-force approach using two nested loops. The outer loop selects the starting index of a substring, and the inner loop extends the substring one character at a time. During the inner loop, we maintain a frequency counter for vowels and a count for consonants. If the consonant count exceeds k, we break out of the loop because further extension will only add more consonants. Whenever the consonant count equals k, we check if every vowel has appeared at least once. If so, we increment our result counter.
Data Structures Used:
- A fixed size dictionary (or array) to keep the count of vowels.
- Simple integer counter for consonants.
Algorithmic Approach:
- Iterate with two pointers for all possible substrings.
- For each character, update the vowel frequency if it is a vowel; otherwise, update the consonant count.
- If the number of consonants exceeds k, break out of the current inner loop.
- When exactly k consonants are reached, check if all five vowels have been seen at least once. If yes, count the substring.
- Continue until all substrings are examined.