Problem 2062

Abstract / Summary

Count the number of substrings made only of vowels in a given string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2062.py

class Solution:
    def countVowelSubstrings(self, word: str) -> int:
        result = 0
        for i in range(len(word)):
            have = set()
            for j in range(i, len(word)):
                if word[j] not in "aeiuo":
                    break
                have.add(word[j])
                if len(have) == 5:
                    result += 1
        return result
12 lines | 395 bytes | submitted January 1, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (100k+ submissions).

Typical patterns to solve this problem:
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method countVowelSubstrings that receives a single string word and returns the number of contiguous substrings composed exclusively of the five English vowels (a, e, i, o, u) and that contain each vowel at least once. The algorithm iterates over all possible starting positions in the input string and expands each candidate substring until a non-vowel character is encountered. Whenever the expanding window has accumulated all five distinct vowels, the result counter is incremented.

Key Steps

The outer loop selects each possible start index of a substring. The loop variable i runs from the first character to the last character of word.

for i in range(len(word)):

For each start index a fresh set named have is created to record which vowels have been seen in the current expanding window.

have = set()

The inner loop extends the substring one character at a time, using the index j that begins at the current start index i and moves forward toward the end of the string.

for j in range(i, len(word)):

Inside the inner loop the character at position j is examined. If the character is not one of the five vowels, the inner loop terminates early because any further extension would still contain the non-vowel character, making the substring invalid.

if word[j] not in "aeiuo":
    break

When the character is a vowel, it is added to the have set, which automatically tracks distinct vowel occurrences.

have.add(word[j])

After updating the set, the algorithm checks whether all five vowels have been observed. If the size of have equals five, the current substring (from i to j, inclusive) satisfies the required condition, and the global counter result is increased by one.

if len(have) == 5:
    result += 1

When the inner loop finishes-either by reaching the end of the string or by encountering a non-vowel-the outer loop proceeds to the next start index. After all start positions have been processed, the method returns the accumulated count.

return result

Edge Cases Handled

The implementation gracefully handles an empty input string because the outer loop range becomes zero, leaving result at its initial value of zero. Strings that contain no vowels or only a subset of the vowel set also result in a zero count, as the inner loop will either break immediately on the first non-vowel character or never reach a set size of five. Repeated occurrences of the same vowel do not affect the correctness because the set data structure inherently stores each vowel only once; thus, substrings with duplicate vowels still contribute to the count only when all five distinct vowels are present. Additionally, substrings that end exactly at the string’s last character are correctly considered, since the inner loop’s range includes the final index.

Performance Optimizations

A notable optimization is the early termination of the inner loop upon encountering a character that is not a vowel. This prevents unnecessary scanning of substrings that are already invalid, reducing the number of iterations dramatically for inputs containing many consonants. The use of a set to track distinct vowels provides constant-time membership checks and avoids the overhead of counting each vowel individually. By updating the result counter immediately when the set reaches a size of five, the algorithm avoids a secondary pass or additional data structures to verify the vowel completeness of each substring. These choices collectively keep the execution focused on only those substrings that have the potential to satisfy the problem’s constraints.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long train of colorful alphabet blocks. This computer program takes that train and looks at every single possible smaller section of it. It starts at the first block and stretches a window out to look at more and more blocks one by one. As it looks at each new block, it checks if that block is a special vowel like a, e, i, o, or u. If it sees a letter that is not a vowel, it stops looking at that specific stretch because the rule is broken. Every time it finds a stretch that contains all five different vowels at least once, it puts a little gold coin into a jar. After checking every single starting spot and every possible length, the jar is full of all the ways to find those special vowel teams.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.70 | σ = 1.38

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
25 links | 14 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

5 solutions   January 1, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality