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

Given a string word and a non-negative integer k, you need to find the total number of substrings that satisfy two conditions:

  1. The substring contains every vowel ('a', 'e', 'i', 'o', and 'u') at least once
  2. The substring contains exactly k consonants

A substring is a contiguous sequence of characters within a string. Vowels are the letters 'a', 'e', 'i', 'o', and 'u'. All other lowercase English letters are consonants.

Example: For word = "aeiouk" and k = 1, the substring "aeiouk" contains all vowels and exactly 1 consonant ('k'), so it counts toward our answer.

Input & Output

example_1.py โ€” Basic Case
$ Input: word = "aeioqq", k = 1
โ€บ Output: 0
๐Ÿ’ก Note: No substring contains all vowels (a,e,i,o,u) and exactly 1 consonant. The string is missing 'u' vowel.
example_2.py โ€” Valid Substring
$ Input: word = "aeiouqq", k = 1
โ€บ Output: 1
๐Ÿ’ก Note: The substring "aeiouq" (indices 0-5) contains all vowels and exactly 1 consonant 'q'.
example_3.py โ€” Multiple Valid Substrings
$ Input: word = "aeioubac", k = 2
โ€บ Output: 1
๐Ÿ’ก Note: The substring "aeioubac" contains all vowels (a,e,i,o,u) and exactly 2 consonants (b,c).

Constraints

  • 5 โ‰ค word.length โ‰ค 5 ร— 104
  • word consists only of lowercase English letters
  • 0 โ‰ค k โ‰ค word.length - 5
  • Note: Since we need all 5 vowels, minimum substring length is 5

Visualization

Tap to expand
String Analysis with Sliding WindowaeioubcleftrightWindow Analysisโ— Vowels in window: a, e, i, o, u (5/5 โœ“)โ— Consonants in window: b, c (2 total)Target consonants (k): 2โœ“ Valid: All vowels + exactly k consonantsSubstrings from this window: 1Algorithm Steps:1. Expand right pointer โ†’ count chars2. If consonants > k โ†’ shrink left3. Count valid substrings in current windowLegendVowels (a, e, i, o, u)ConsonantsSliding Window
Understanding the Visualization
1
Initialize Window
Start with an empty window at the beginning of the string
2
Expand Right
Extend the window to the right, counting vowels and consonants
3
Check Consonants
If consonants exceed k, shrink window from the left
4
Count Valid
When we have all vowels and โ‰คk consonants, count valid substrings
5
Use Difference
Use 'at most k' - 'at most k-1' to get exactly k consonants
Key Takeaway
๐ŸŽฏ Key Insight: Using the mathematical relationship (exactly k) = (at most k) - (at most k-1) allows us to solve this efficiently with sliding window technique in O(n) time.
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
47.2K Views
Medium-High Frequency
~25 min Avg. Time
1.7K 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