Count Vowels Permutation - 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'
  • Each vowel 'i' may not be followed by another 'i'
  • 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 may be too large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Small Input
$ Input: n = 1
Output: 5
💡 Note: For length 1, all vowels are valid: 'a', 'e', 'i', 'o', 'u'. Total = 5 strings.
Example 2 — Medium Input
$ Input: n = 2
Output: 10
💡 Note: Valid strings: 'ae', 'ea', 'ei', 'ia', 'ie', 'io', 'iu', 'oi', 'ou', 'ua'. Total = 10 strings.
Example 3 — Larger Input
$ Input: n = 5
Output: 68
💡 Note: Following the transition rules through 5 levels, we get 68 valid vowel permutation strings.

Constraints

  • 1 ≤ n ≤ 2 × 104

Visualization

Tap to expand
Count Vowels Permutation INPUT n = 1 Vowel Transition Rules: a e i o u a-->e, e-->a|i, i-->all except i o-->i|u, u-->a ALGORITHM STEPS 1 Initialize DP dp[v] = 1 for each vowel a:1 e:1 i:1 o:1 u:1 2 Build Transitions Count incoming edges new_a = e + i + u new_e = a + i new_i = e + o 3 Iterate n-1 times For n=1, skip iteration 4 Sum All States result = sum(dp) mod 10^9+7 1+1+1+1+1 = 5 FINAL RESULT Valid strings of length 1: a e i o u Output: 5 OK 5 vowels = 5 valid strings of length 1 Key Insight: Use Dynamic Programming with states for each vowel. Track count of strings ending with each vowel. Transitions are based on which vowels can follow each other. For n=1, each vowel forms one valid string. Time: O(n), Space: O(1) - only need to track 5 vowel counts at each step. TutorialsPoint - Count Vowels Permutation | Optimal Solution (Dynamic Programming)
Asked in
Google 12 Facebook 8 Amazon 6
32.0K Views
Medium Frequency
~25 min Avg. Time
892 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