← Questions

Count substrings that use only vowels and contain all five

0
SnowflakeCoding

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:

  1. Every character of the substring is a vowel (a, e, i, o, u).
  2. 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
  • s contains 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 y a vowel? (No: only a, 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 k distinct 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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding