|
| 1 | +class Solution { |
| 2 | + // 0: 'a', 1: 'e', 2: 'i', 3: 'o', 4: 'u' |
| 3 | + |
| 4 | + private static int MOD = 1_000_000_000 + 7; |
| 5 | + |
| 6 | + private int getSum(long[] arr) { |
| 7 | + long sum = 0; |
| 8 | + for(long x: arr) { |
| 9 | + sum = sum + x; |
| 10 | + sum = sum % MOD; |
| 11 | + } |
| 12 | + return (int) sum; |
| 13 | + } |
| 14 | + |
| 15 | + private long[] getBaseCounts() { |
| 16 | + return new long[]{1, 1, 1, 1, 1}; |
| 17 | + } |
| 18 | + |
| 19 | + private Map<Integer, List<Integer>> getNextCountMapping() { |
| 20 | + Map<Integer, List<Integer>> map = new HashMap<>(); |
| 21 | + |
| 22 | + /* 0 1 2 3 4 |
| 23 | + a e i o u |
| 24 | + |
| 25 | + Reverse mapping i.e. "depends on" |
| 26 | + {a: [e, i, u]}, {e: [a, i]}, {i: [e, o]}, |
| 27 | + {o: [i]}, {u: [i, o]} |
| 28 | + */ |
| 29 | + |
| 30 | + map.put(0, new ArrayList<>(List.of(1, 2, 4))); |
| 31 | + map.put(1, new ArrayList<>(List.of(0, 2))); |
| 32 | + map.put(2, new ArrayList<>(List.of(1, 3))); |
| 33 | + map.put(3, new ArrayList<>(List.of(2))); |
| 34 | + map.put(4, new ArrayList<>(List.of(2, 3))); |
| 35 | + |
| 36 | + return map; |
| 37 | + } |
| 38 | + |
| 39 | + private long[] getNextCounts( |
| 40 | + long[] currentCounts, |
| 41 | + Map<Integer, List<Integer>> mapNextCounting |
| 42 | + ) { |
| 43 | + long[] nextCounts = new long[5]; |
| 44 | + Arrays.fill(nextCounts, 0); |
| 45 | + |
| 46 | + // Mapping conversion |
| 47 | + for(int key: mapNextCounting.keySet()) { |
| 48 | + for(int val: mapNextCounting.get(key)) { |
| 49 | + nextCounts[val] += (long) currentCounts[key]; |
| 50 | + nextCounts[val] %= MOD; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return nextCounts; |
| 55 | + } |
| 56 | + |
| 57 | + public int countVowelPermutation(int n) { |
| 58 | + long[] counts = getBaseCounts(); |
| 59 | + if(n == 1) { |
| 60 | + return getSum(counts); |
| 61 | + } |
| 62 | + |
| 63 | + Map<Integer, List<Integer>> mapNextCounting; |
| 64 | + mapNextCounting = getNextCountMapping(); |
| 65 | + |
| 66 | + for(int i=1; i<n; i++) { |
| 67 | + counts = getNextCounts(counts, mapNextCounting); |
| 68 | + } |
| 69 | + |
| 70 | + return getSum(counts); |
| 71 | + } |
| 72 | +} |
0 commit comments