Count Vowels Permutation — LeetCode 1220 Python Solution
- Problem
- #1220
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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'.
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) % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(C) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1220. Count Vowels Permutation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1220. Count Vowels Permutation?
- LeetCode 1220. Count Vowels Permutation is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1220. Count Vowels Permutation?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1220. Count Vowels Permutation?
- The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 1220. Count Vowels Permutation cover?
- LeetCode 1220. Count Vowels Permutation is tagged Dynamic Programming on LeetCode.