#1220

Count Vowels Permutation

Hard
Dynamic ProgrammingDynamic ProgrammingState Transition
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using dynamic programming, we can build the solution iteratively by counting how many strings of length i can end with each vowel. This approach avoids generating all combinations and directly computes the count based on previous results.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a dp array where dp[i][j] represents the number of valid strings of length i ending with the j-th vowel.
  2. 2Step 2: Set base cases for strings of length 1 for each vowel.
  3. 3Step 3: For each length from 2 to n, calculate the number of valid strings based on the rules.
  4. 4Step 4: Sum the counts from the last row of the dp array to get the final result.
solution.py14 lines
1# Full working Python code
2def count_vowel_permutations(n):
3    MOD = 10**9 + 7
4    dp = [[0] * 5 for _ in range(n + 1)]
5    for j in range(5):
6        dp[1][j] = 1
7    for i in range(2, n + 1):
8        dp[i][0] = dp[i - 1][1] % MOD  # 'a' can only follow 'e'
9        dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD  # 'e' can follow 'a' or 'i'
10        dp[i][2] = (dp[i - 1][0] + dp[i - 1][1] + dp[i - 1][3] + dp[i - 1][4]) % MOD  # 'i' can follow any except 'i'
11        dp[i][3] = (dp[i - 1][2]) % MOD  # 'o' can only follow 'i'
12        dp[i][4] = (dp[i - 1][0]) % MOD  # 'u' can only follow 'a'
13    return sum(dp[n]) % MOD
14

Complexity note: This complexity is efficient because we only need to calculate the counts iteratively based on the previous counts, leading to a linear growth in time with respect to n.

  • 1Dynamic programming allows us to build solutions incrementally, leveraging previously computed results.
  • 2Understanding the constraints of the problem helps in defining the state transitions effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.