Python 1641.py
class Solution:
def countVowelStrings(self, n: int) -> int:
# 0 = "a", 1 = "e", 2 = "i", 3 = "o", 4 = "u"
last = [ 1, 0, 0, 0, 0 ]
for i in range(n):
next = [ 0, 0, 0, 0, 0 ]
for i, l in enumerate(last):
for j in range(i, 5):
next[j] += l
last = next
return sum(last)
Difficulty
and has an acceptance rate of about 79% (200k+ submissions).
Typical patterns to solve this problem:
- Combinatorics
- Dynamic Programming
- Math
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation computes the number of possible strings of length n that can be formed using the five English vowels (a, e, i, o, u) where the vowels must appear in non-decreasing alphabetical order. It employs a compact dynamic programming approach that iteratively builds the count for each vowel position while preserving the ordering constraint.
Core Logic
The algorithm maintains a one-dimensional array, last, where each entry represents the number of valid strings that end with a particular vowel. The index mapping is explicit in the comment:
# 0 = "a", 1 = "e", 2 = "i", 3 = "o", 4 = "u"
last = [1, 0, 0, 0, 0]
The initial state reflects that a string of length 1 consisting solely of 'a' is the only valid string ending with 'a'; all other vowels have zero possibilities at this point.
Iterative Transition
For each position in the target string (executed n times), a new array next is constructed. The nested loops propagate counts from last to next while respecting the non-decreasing order:
for i in range(n):
next = [0, 0, 0, 0, 0]
for i, l in enumerate(last):
for j in range(i, 5):
next[j] += l
last = next
The outer loop iterates over the string length. Inside, enumerate(last) yields the current vowel index i and its associated count l. The inner loop runs from the current index i up to the last vowel index 4. By adding l to every next[j] where j >= i, the code accumulates all ways to extend existing strings with any vowel that does not violate the ordering rule. After processing all indices, last is replaced with next, ready for the next iteration.
Final Aggregation
Once all positions have been processed, the total number of valid strings is obtained by summing the entries of last:
return sum(last)
Each entry now holds the count of strings of length n ending with the corresponding vowel, and their sum yields the overall count.
Edge Cases Handled
When n equals zero, the outer loop does not execute, leaving last unchanged as [1, 0, 0, 0, 0]. The final sum(last) returns 1, which correctly represents the empty string as a single valid combination under the problem’s combinatorial interpretation.
The algorithm also gracefully handles very large values of n. Python’s arbitrary-precision integers ensure that intermediate sums do not overflow, and the fixed-size inner loops keep the computation bounded regardless of n.
Performance Optimizations
The implementation leverages several implicit optimizations:
- The state vector
lasthas a constant length of five, eliminating the need for dynamic data structures that grow withn. This keeps memory usage minimal and predictable. - By reusing the
nextlist on each iteration rather than creating new lists for every inner loop, the code reduces allocation overhead. - The inner accumulation loop iterates only over the suffix of the vowel list (
range(i, 5)), avoiding unnecessary additions for indices that would violate the ordering constraint. This targeted update pattern reduces the number of arithmetic operations per iteration. - The final aggregation uses Python’s built-in
sum, which is implemented in C and therefore faster than a manual accumulation loop.
These choices collectively ensure that the algorithm runs efficiently even for large input sizes while maintaining clear and concise logic.
ELI5 - Simplified Explanation
Imagine you have five different magic treasure boxes labeled a, e, i, o, and u. This code is like a game where you want to fill these boxes with special string patterns.
At the very start, you have one invisible token in the first box when nothing has been built yet. The code uses a loop to look at the boxes over and over again, up to a certain number of steps. Every time the loop runs, it looks at how many tokens are in each box and moves them into new boxes. The rule for this game is that tokens can only stay in their current box or move into a box that comes after their current one.
Inside the loop, the code creates a fresh set of boxes and fills them based on the ones from the previous step. It carefully adds up the possibilities so that by the end, you know exactly how many different ways those tokens could have been placed into the boxes. It is just like counting how many paths you can take through a maze where you can only walk forward.
Code Quality
Complexity Analysis
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
Other Solutions
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++ | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | ||||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1829: Maximum XOR for Each Query
- problem 1833: Maximum Ice Cream Bars
- problem 1910: Remove All Occurrences of a Substring
- problem 2079: Watering Plants
- problem 2120: Execution of All Suffix Instructions Staying in a Grid
- problem 2161: Partition Array According to Given Pivot
- problem 2221: Find Triangular Sum of an Array
- problem 2545: Sort the Students by Their Kth Score
- problem 2640: Find the Score of All Prefixes of an Array
Extra
- 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