|
| 1 | +/** |
| 2 | + * 1220. Count Vowels Permutation |
| 3 | + * https://leetcode.com/problems/count-vowels-permutation/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an integer n, your task is to count how many strings of length n can be formed under |
| 7 | + * the following rules: |
| 8 | + * - Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u') |
| 9 | + * - Each vowel 'a' may only be followed by an 'e'. |
| 10 | + * - Each vowel 'e' may only be followed by an 'a' or an 'i'. |
| 11 | + * - Each vowel 'i' may not be followed by another 'i'. |
| 12 | + * - Each vowel 'o' may only be followed by an 'i' or a 'u'. |
| 13 | + * - Each vowel 'u' may only be followed by an 'a'. |
| 14 | + * |
| 15 | + * Since the answer may be too large, return it modulo 10^9 + 7. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number} n |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var countVowelPermutation = function(n) { |
| 23 | + const MOD = 1000000007n; |
| 24 | + let aCount = 1n; |
| 25 | + let eCount = 1n; |
| 26 | + let iCount = 1n; |
| 27 | + let oCount = 1n; |
| 28 | + let uCount = 1n; |
| 29 | + |
| 30 | + for (let length = 2; length <= n; length++) { |
| 31 | + const prevACount = aCount; |
| 32 | + const prevECount = eCount; |
| 33 | + const prevICount = iCount; |
| 34 | + const prevOCount = oCount; |
| 35 | + const prevUCount = uCount; |
| 36 | + |
| 37 | + aCount = (prevECount + prevICount + prevUCount) % MOD; |
| 38 | + eCount = (prevACount + prevICount) % MOD; |
| 39 | + iCount = (prevECount + prevOCount) % MOD; |
| 40 | + oCount = (prevICount) % MOD; |
| 41 | + uCount = (prevICount + prevOCount) % MOD; |
| 42 | + } |
| 43 | + |
| 44 | + const total = aCount + eCount + iCount + oCount + uCount; |
| 45 | + |
| 46 | + return Number(total % MOD); |
| 47 | +}; |
0 commit comments