Leetcode #1220: Count Vowels Permutation
In this guide, we solve Leetcode #1220 Count Vowels Permutation in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an integer n, your task is to count how many strings of length n can be formed under the following rules: Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u') Each vowel 'a' may only be followed by an 'e'. Each vowel 'e' may only be followed by an 'a' or an 'i'.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: n = 1
Output: 5
Explanation: All possible strings are: "a", "e", "i" , "o" and "u".
Python Solution
class Solution:
def countVowelPermutation(self, n: int) -> int:
f = [1] * 5
mod = 10**9 + 7
for _ in range(n - 1):
g = [0] * 5
g[0] = (f[1] + f[2] + f[4]) % mod
g[1] = (f[0] + f[2]) % mod
g[2] = (f[1] + f[3]) % mod
g[3] = f[2]
g[4] = (f[2] + f[3]) % mod
f = g
return sum(f) % mod
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.