Python 1220.py
class Solution:
def countVowelPermutation(self, n: int) -> int:
count = {}
count["a"] = 1
count["e"] = 1
count["i"] = 1
count["o"] = 1
count["u"] = 1
for _ in range(1, n):
next = {}
next["a"] = count["e"] + count["i"] + count["u"]
next["e"] = count["a"] + count["i"]
next["i"] = count["e"] + count["o"]
next["o"] = count["i"]
next["u"] = count["i"] + count["o"]
count = next
return sum(count.values()) % 1_000_000_007
Difficulty
and has an acceptance rate of about 61% (300k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
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 strings of length n that can be formed using the vowels a, e, i, o, u while respecting specific transition rules between consecutive characters. The algorithm builds the count iteratively, maintaining a mapping from each vowel to the number of valid strings that end with that vowel at the current length. After processing all positions, it aggregates the counts and applies a large prime modulus to keep the result within integer limits.
Initialization
At the start, a dictionary named count is created with each vowel as a key and the value 1. This represents the base case where strings of length 1 consist of a single vowel, and there is exactly one way to end with each vowel.
count = {}
count["a"] = 1
count["e"] = 1
count["i"] = 1
count["o"] = 1
count["u"] = 1
Iterative Transition
The core of the algorithm is a loop that runs n-1 times, extending the strings by one character at each iteration. Inside the loop a new dictionary next is populated according to the allowed predecessor-successor relationships:
- a can follow e, i, or u.
- e can follow a or i.
- i can follow e or o.
- o can follow i only.
- u can follow i or o.
The code directly translates these rules into arithmetic expressions that sum the counts of permissible preceding vowels.
for _ in range(1, n):
next = {}
next["a"] = count["e"] + count["i"] + count["u"]
next["e"] = count["a"] + count["i"]
next["i"] = count["e"] + count["o"]
next["o"] = count["i"]
next["u"] = count["i"] + count["o"]
count = next
Each iteration replaces count with next, so the dictionary always reflects the state for the current string length.
Final Aggregation
After the loop finishes, the values in count represent the number of valid strings of length n ending with each vowel. Summing these values yields the total number of permissible strings. The result is reduced modulo 1_000_000_007 to avoid overflow and to conform to typical problem constraints.
return sum(count.values()) % 1_000_000_007
Edge Cases Handled
When n equals 1, the loop body is never executed because the range range(1, 1) is empty. The function therefore returns the sum of the initial dictionary, which is 5, correctly reflecting the five single-character strings. The algorithm also gracefully handles very large values of n because the intermediate counts are kept within Python’s arbitrary-precision integers, and the final modulo operation ensures the output fits within standard 32-bit integer ranges.
Performance Optimizations
The implementation avoids allocating large data structures; it reuses two small dictionaries of fixed size (five entries) throughout the computation. By updating the dictionary in place and discarding the previous one, memory usage stays constant regardless of n. The transition calculations are performed with simple integer additions, and the modulo operation is deferred until the final step, reducing the number of expensive modulus operations. The use of sum(count.values()) leverages Python’s built-in aggregation, which is highly optimized in C. These choices collectively keep the runtime low and the memory footprint minimal for the problem size.
ELI5 - Simplified Explanation
Imagine all the vowels are friends who like to stand in a line to form a secret code. Each vowel has specific friends it likes to stand next to. The letter a only follows e, i, or u. The letter e likes to hang out after a or i. The letter i loves to be next to e or o. The letter o is strictly joined to i, and the letter u follows i or o.
This code starts by saying there is one way to have a line of just one vowel. Then, it uses a loop to build longer lines one step at a time. During each step, it looks at how many ways each vowel could have reached its current spot based on the previous vowel. It keeps track of these combinations in a dictionary, which is just like a basket where the code stores the count for each letter. By the time the loop finishes building the line to the length wanted, the code adds up all the different possibilities found in the basket to show the total number of ways the vowels can form their secret code.
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 | Java | C++ | Python | TS | |||||
| WalkCCC | Python | |||||||||
| leetcode.ca | Java | C++ | Python | JS | Bash | Go | TS | |||
| Progiez | Java | C++ | Python | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | Python | |||||||||
| leetcode.ca | Bash, C++, Go, Java, JavaScript, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java |
Videos
Similar Problems
Solved On The Same Day
- problem 1227: Airplane Seat Assignment Probability
- problem 1315: Sum of Nodes with Even-Valued Grandparent
- problem 1325: Delete Leaves With a Given Value
- problem 1333: Filter Restaurants by Vegan-Friendly, Price and Distance
- problem 1344: Angle Between Hands of a Clock
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