3306. Count of Substrings Containing Every Vowel and K Consonants II
Explanation:
To solve this problem, we can use a sliding window approach. We will maintain a window of size at most 5 to ensure that all vowels are present in the window. We will then iterate through the string and keep track of the number of consonants inside the window. If the number of consonants is equal to k
, we can calculate the number of substrings that satisfy the conditions and increment our count.
Algorithm:
- Initialize variables
count
andconsonants
to 0. - Iterate through the input string using a sliding window approach.
- For each character:
- If it is a vowel, mark it as present in a boolean array.
- If it is a consonant, increment the
consonants
count. - If the size of the window is greater than 5, remove the first character from the window.
- If the number of consonants in the window is greater than
k
, move the window start to the right until the number of consonants is less than or equal tok
. - If all vowels are present in the window and the number of consonants is equal to
k
, increment thecount
by the size of the window.
- Return the final
count
.
Time Complexity:
The time complexity of this approach is O(n), where n is the length of the input string.
Space Complexity:
The space complexity is O(1) since we are using a constant amount of extra space.
:
class Solution {
public int countSubstrings(String word, int k) {
boolean[] vowels = new boolean[26];
vowels['a' - 'a'] = true;
vowels['e' - 'a'] = true;
vowels['i' - 'a'] = true;
vowels['o' - 'a'] = true;
vowels['u' - 'a'] = true;
int count = 0, consonants = 0;
int[] cnt = new int[word.length()+1];
int left = 0;
for (int right = 0; right < word.length(); right++) {
char c = word.charAt(right);
if (vowels[c - 'a']) {
cnt[right+1] = cnt[right];
} else {
consonants++;
cnt[right+1] = cnt[right] + 1;
}
while (consonants > k) {
if (!vowels[word.charAt(left) - 'a']) {
consonants--;
}
left++;
}
if (consonants == k) {
count += right - left + 1;
}
}
return count;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.