Count Vowel Substrings

35 min · countVowelSubstrings()

A consonant acts like a wall: no vowel-only stretch can pass through it. Between those walls, though, one long run may hide many overlapping answers.

Given a lowercase string word, count its vowel substrings. A vowel substring is a non-empty, contiguous slice that uses only a, e, i, o, and u, while containing all five of them at least once.

A few ground rules:

  • Different start and end positions count as different substrings, even when their text happens to match.
  • Repeated vowels are allowed. Each of the five vowel types only needs to appear once.
  • Any consonant ends the current vowel-only run; a valid substring can't cross it.

Constraints

  • 1 <= word.length <= 100_000
  • word contains only lowercase English letters.
  • The answer fits in a signed 32-bit integer.

Hints

Treat consonants as walls

Split your reasoning into uninterrupted vowel-only runs. Every valid answer lives entirely inside one run, so a consonant can reset all your state.

Write the honest version first

Start at each position and extend right until you hit a consonant. Track which vowel types you've seen, and count every endpoint after all five are present.

Count several starts at once

Inside one vowel run, keep a window containing all five types. Remove duplicate vowels from its left edge. Once it is as tight as possible, every start from the run's beginning through that left edge forms a valid substring ending here.

Follow-up

Can you count every answer in one left-to-right pass while storing only five small counters?

Visible cases

Examples

Example 1

ready
Input
word = "aeiouu"
Expected
2
Why
both 'aeiou' and 'aeiouu' contain every vowel

Example 2

ready
Input
word = "aeioubcaeiou"
Expected
2
Why
the consonants split two independent five-vowel runs

Example 3

ready
Input
word = "rhythm"
Expected
0
Why
no vowel-only slice can contain all five vowel types

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite