Count of Substrings Containing Every Vowel and K Consonants II - Problem

You are given a string word and a non-negative integer k.

Return the total number of substrings of word that contain every vowel ('a', 'e', 'i', 'o', and 'u') at least once and exactly k consonants.

Input & Output

Example 1 — Basic Case
$ Input: word = "aeioubcdfghiju", k = 1
Output: 0
💡 Note: No substring contains all vowels and exactly 1 consonant. Need at least 5 characters for all vowels, but with 1 consonant we'd need 6 total characters minimum.
Example 2 — All Vowels Present
$ Input: word = "aeiou", k = 0
Output: 1
💡 Note: The substring "aeiou" contains all 5 vowels and exactly 0 consonants, so count is 1.
Example 3 — Multiple Valid Substrings
$ Input: word = "aeioubcd", k = 3
Output: 1
💡 Note: The substring "aeioubcd" contains all vowels (a,e,i,o,u) and exactly 3 consonants (b,c,d).

Constraints

  • 1 ≤ word.length ≤ 105
  • word consists of only lowercase English letters
  • 0 ≤ k ≤ word.length

Visualization

Tap to expand
Vowel Substrings with K Consonants INPUT word = "aeioubcdfghiju" a e i o u b c d f g h i j u Vowel Consonant k = 1 (exactly 1 consonant) Required: a, e, i, o, u (all 5 vowels at least once) Length: 14 characters Vowels: 7 | Consonants: 7 ALGORITHM STEPS 1 Sliding Window Use two pointers to track valid substring range 2 Count Transformation f(k) = count with at least k Answer = f(k) - f(k+1) 3 Track State vowelCount map for a,e,i,o,u consonantCount for total 4 Analyze Substrings Check each valid window for all vowels + k consonants Analysis for k=1: "aeioub" has 5 vowels + 1 cons Missing: second 'u' needed? No valid substring found with exactly 1 consonant + all vowels FINAL RESULT Output: 0 No Valid Substrings Found Why 0? Shortest substring with all 5 vowels: "aeioub" (6 chars) This has 1 consonant but expanding adds more consonants No way to get exactly k=1 VERIFIED Result: 0 substrings Key Insight: Transform "exactly k" into "at least k" using: count(exactly k) = count(at least k) - count(at least k+1). Use sliding window to maintain vowel frequencies and consonant count. When all 5 vowels present and consonants >= k, count valid substrings by tracking left boundary positions. Time: O(n), Space: O(1). TutorialsPoint - Count of Substrings Containing Every Vowel and K Consonants II | Optimal Solution
Asked in
Google 25 Microsoft 20 Amazon 15 Meta 10
28.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen