Count substrings that use only vowels and contain all five
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Snowflake. It tests strings, sliding window and counting.
Given a string s of lowercase English letters, return the number of contiguous substrings that satisfy both rules:
- Every character of the substring is a vowel (
a,e,i,o,u). - The substring contains each of the five vowels at least once.
Substrings are counted by position: two equal substrings that start at different indices both count.
Implement:
def count_vowel_substrings(s: str) -> int: ...
Constraints
0 <= len(s) <= 10^5-
scontains only lowercase English letters. - The answer can exceed 32 bits.
Start with a working solution, then aim for linear time.
Example 1
Input: s = "aaeiou"
Output: 2
The valid substrings are "aaeiou" and "aeiou".
Example 2
Input: s = "aeioxuaei"
Output: 0
The x splits the vowels into "aeio" and "uaei", and neither part contains all five vowels.
Clarifying questions
- Is
ya vowel? (No: onlya,e,i,o,u.) - Can the string contain uppercase letters? (No, by the constraints.)
- Should an empty string or a string shorter than five return 0?
What a strong answer covers
- Splits the string at consonants into maximal vowel-only runs. A valid substring never crosses a consonant, so each run is counted on its own.
- Inside a run, for each end index, keeps the last position of each of the five vowels. Once all five have appeared, every start from the run's start up to the smallest of those positions gives a valid substring, so it adds that many. O(n) time and O(1) space.
- Or uses the "at most" trick: substrings with all five equal the count with at most five distinct vowels minus the count with at most four. Either is fine if explained.
- Starts from a brute force over all substrings to check correctness, then moves to linear time.
- Edge cases: a run with only four of the vowels, consonants splitting the vowels (Example 2), and a long run of vowels where the answer is close to n²/2.
- Tests the examples,
"aeiou"(1),"aeiouu"(2), and random strings against the brute force.
Follow-ups
- Count substrings that contain exactly
kdistinct vowels. - Return the shortest such substring.
- Allow at most one consonant inside the substring.
Where it's asked
What it tests
strings · sliding window · counting
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
