Problem Description
Given an integer n, count the number of strings of length n that can be formed using only lowercase vowels ('a', 'e', 'i', 'o', 'u') under the following transition rules:
- 'a' may only be followed by 'e'.
- 'e' may only be followed by 'a' or 'i'.
- 'i' may not be followed by another 'i' (but can be followed by any other vowel).
- 'o' may only be followed by 'i' or 'u'.
- 'u' may only be followed by 'a'. Return the count of such strings modulo 10^9 + 7.
Key Insights
- Use dynamic programming to count valid strings ending with each vowel.
- Transitions are based on the allowed following vowels:
- a -> e
- e -> a, i
- i -> a, e, o, u (excluding i)
- o -> i, u
- u -> a
- Instead of moving forward using these rules, we reverse the thinking:
- For each vowel ending, determine which vowels from the previous step could have transitioned to it.
- Only a constant amount of memory is needed to track counts for each vowel, leading to an O(1) space solution.
- The iterative process runs in O(n) time.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), since only five counters for the vowels are maintained.
Solution
We use a dynamic programming approach that maintains counts for strings ending with each vowel at each length. Let:
- count_a, count_e, count_i, count_o, count_u be the current counts for strings ending with 'a', 'e', 'i', 'o', and 'u', respectively. For n = 1, each vowel has a count of 1. For each subsequent position (from 2 to n), we update the counts based on reverse allowed transitions:
- New count for 'a' = (previous count for 'e' + previous count for 'i' + previous count for 'u') because 'a' can follow e, i, or u.
- New count for 'e' = (previous count for 'a' + previous count for 'i') because 'e' can follow a or i.
- New count for 'i' = (previous count for 'e' + previous count for 'o') because 'i' can follow e or o (note: i cannot follow itself).
- New count for 'o' = (previous count for 'i') because 'o' can only follow i.
- New count for 'u' = (previous count for 'i' + previous count for 'o') because 'u' can follow i or o. After updating for all positions, the answer is the sum of counts for all vowels modulo 10^9+7.