To solve this problem, we'll use a sliding window approach. Since we need to find all substrings that contain all the vowels at least once and exactly k consonants, we'll iterate over each possible starting index and expand the window to the right until the conditions are met or the number of consonants exceeds k.
We use a bitmask to efficiently check if all vowels have been encountered in the current window. Each vowel is assigned a unique bit in the bitmask:
- 'a' ->
0b00001
- 'e' ->
0b00010
- 'i' ->
0b00100
- 'o' ->
0b01000
- 'u' ->
0b10000
When the bitmask equals 0b11111 (or 31 in decimal), it indicates that all vowels have been seen at least once in the current window.
Here's the step-by-step algorithm:
- Initialize a counter
ans to 0 to keep track of valid substrings.
- Iterate over the string with a starting index
i from 0 to N - 1.
- For each starting index
i, initialize:
vowel_mask to 0 (no vowels seen yet).
consonant_count to 0 (no consonants counted yet).
- Expand the window to the right by moving an ending index
j from i to N - 1:
- If
word[j] is a vowel, update vowel_mask by setting the corresponding bit.
- If
word[j] is a consonant, increment consonant_count by 1.
- If
consonant_count exceeds k, break out of the inner loop as further expansion will only increase the consonant count.
- If
vowel_mask equals 0b11111 (all vowels seen) and consonant_count equals k, increment ans by 1.
- Return
ans as the total number of valid substrings.
This algorithm has a time complexity of O(N * (k + 5)), where N is the length of the string, k is the given integer, and 5 corresponds to the number of vowels. Since the inner loop runs at most k + 5 times for each starting index, this solution is efficient for reasonable values of k.
Here's the implementation in Python:
def count_substrings_with_all_vowels_and_k_consonants(word, k):
vowel_bits = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}
N = len(word)
ans = 0
for i in range(N):
consonant_count = 0
vowel_mask = 0
for j in range(i, N):
c = word[j]
if c in vowel_bits:
vowel_mask |= vowel_bits[c]
else:
consonant_count += 1
if consonant_count > k:
break # Can't have more than k consonants
if vowel_mask == 31 and consonant_count == k:
ans += 1
return ans
# Example usage:
word = "ieaouqqieaouqq"
k = 1
print(count_substrings_with_all_vowels_and_k_consonants(word, k)) # Output: 3