Count Vowels Permutation - Problem
Count Vowels Permutation

Imagine you're creating a special language where vowels follow strict pronunciation rules! Given an integer n, you need to count how many valid strings of length n can be formed using only lowercase vowels ('a', 'e', 'i', 'o', 'u') following these pronunciation transition rules:

• Each vowel 'a' may only be followed by an 'e'
• Each vowel 'e' may only be followed by an 'a' or an 'i'
• Each vowel 'i' may not be followed by another 'i' (can be followed by 'a', 'e', 'o', 'u')
• Each vowel 'o' may only be followed by an 'i' or a 'u'
• Each vowel 'u' may only be followed by an 'a'

Since the answer can be extremely large, return it modulo 109 + 7.

Example: For n = 1, we can form 5 strings: "a", "e", "i", "o", "u". For n = 2, we can form 10 valid strings like "ae", "ea", "ei", "ia", "ie", "io", "oi", "ou", "ua", "ue".

Input & Output

example_1.py — Basic Case
$ Input: n = 1
Output: 5
💡 Note: For length 1, each vowel can form a valid string by itself: "a", "e", "i", "o", "u". Total = 5 strings.
example_2.py — Length 2
$ Input: n = 2
Output: 10
💡 Note: Valid 2-character strings following the rules: "ae" (a→e), "ea" (e→a), "ei" (e→i), "ia" (i→a), "ie" (i→e), "io" (i→o), "iu" (i→u), "oi" (o→i), "ou" (o→u), "ua" (u→a). Total = 10 strings.
example_3.py — Larger Input
$ Input: n = 5
Output: 68
💡 Note: For length 5, applying the DP transitions through all levels gives us 68 valid strings that follow all the vowel transition rules.

Constraints

  • 1 ≤ n ≤ 2 × 104
  • Return result modulo 109 + 7
  • Each character must be a lowercase vowel ('a', 'e', 'i', 'o', 'u')

Visualization

Tap to expand
Vowel Transition State Machineaeioua → ee → a,ii → a,e,o,uo → i,uu → aDynamic Programming Approach1. Start with count=1 for each vowel at length 12. For each new length, apply transition rules to redistribute counts3. Sum all counts to get total valid strings of target length
Understanding the Visualization
1
Model as Graph
Create a directed graph where vowels are nodes and edges represent allowed transitions
2
Count Paths
Use DP to count all paths of length n through this transition graph
3
Apply Rules
At each step, distribute current counts to next valid vowels based on transition rules
4
Sum Results
Final answer is sum of all valid strings ending with any vowel
Key Takeaway
🎯 Key Insight: Transform the string generation problem into a state transition counting problem. By tracking counts instead of generating actual strings, we achieve optimal O(n) time complexity.
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
89.4K Views
Medium-High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen