Count all possible N-length vowel permutations that can be generated based on the given conditions

Given an integer N, the task is to count the number of N-length strings consisting of lowercase vowels that can be generated based the following conditions:
- Each ‘a’ may only be followed by an ‘e’.
- Each ‘e’ may only be followed by an ‘a’ or an ‘i’.
- Each ‘i’ may not be followed by another ‘i’.
- Each ‘o’ may only be followed by an ‘i’ or a ‘u’.
- Each ‘u’ may only be followed by an ‘a’.
Examples:
Input: N = 1
Output: 5
Explanation: All strings that can be formed are: “a”, “e”, “i”, “o” and “u”.Input: N = 2
Output: 10
Explanation: All strings that can be formed are: “ae”, “ea”, “ei”, “ia”, “ie”, “io”, “iu”, “oi”, “ou” and “ua”.
Approach: The idea to solve this problem is to visualize this as a Graph Problem. From the given rules a directed graph can be constructed, where an edge from u to v means that v can be immediately written after u in the resultant strings. The problem reduces to finding the number of N-length paths in the constructed directed graph. Follow the steps below to solve the problem:
- Let the vowels a, e, i, o, u be numbered as 0, 1, 2, 3, 4 respectively, and using the dependencies shown in the given graph, convert the graph into an adjacency list relation where the index signifies the vowel and the list at that index signifies an edge from that index to the characters given in the list.
- Initialize a 2D array dp[N + 1][5] where dp[N][char] denotes the number of directed paths of length N which end at a particular vertex char.
- Initialize dp[i][char] for all the characters as 1, since a string of length 1 will only consist of one vowel in the string.
- For all possible lengths, say i, traverse over the directed edges using variable u and perform the following steps:
- Update the value of dp[i + 1][u] as 0.
- Traverse the adjacency list of the node u and increment the value of dp[i][u] by dp[i][v], that stores the sum of all the values such that there is a directed edge from node u to node v.
 
- After completing the above steps, the sum of all the values dp[N][i], where i belongs to the range [0, 5), will give the total number of vowel permutations.
Below is the implementation of the above approach:
C++
| // C++ program for the above approach #include <bits/stdc++.h>usingnamespacestd;// Function to find the number of // vowel permutations possible intcountVowelPermutation(intn){        // To avoid the large output value    intMOD = (int)(1e9 + 7);    // Initialize 2D dp array    longdp[n + 1][5];        // Initialize dp[1][i] as 1 since    // string of length 1 will consist    // of only one vowel in the string    for(inti = 0; i < 5; i++)    {        dp[1][i] = 1;    }        // Directed graph using the    // adjacency matrix    vector<vector<int>> relation = {        { 1 }, { 0, 2 },        { 0, 1, 3, 4 },        { 2, 4 }, { 0 }    };    // Iterate over the range [1, N]    for(inti = 1; i < n; i++)     {                // Traverse the directed graph        for(intu = 0; u < 5; u++)        {            dp[i + 1][u] = 0;            // Traversing the list            for(intv : relation[u])            {                                // Update dp[i + 1][u]                dp[i + 1][u] += dp[i][v] % MOD;            }        }    }    // Stores total count of permutations    longans = 0;    for(inti = 0; i < 5; i++)     {        ans = (ans + dp[n][i]) % MOD;    }    // Return count of permutations    return(int)ans;}// Driver codeintmain(){    intN = 2;        cout << countVowelPermutation(N);}// This code is contributed by Mohit kumar 29 | 
Java
| // Java program for the above approachimportjava.io.*;importjava.util.*;classGFG {    // Function to find the number of    // vowel permutations possible    publicstaticint    countVowelPermutation(intn)    {        // To avoid the large output value        intMOD = (int)(1e9 + 7);        // Initialize 2D dp array        long[][] dp = newlong[n + 1][5];        // Initialize dp[1][i] as 1 since        // string of length 1 will consist        // of only one vowel in the string        for(inti = 0; i < 5; i++) {            dp[1][i] = 1;        }        // Directed graph using the        // adjacency matrix        int[][] relation = newint[][] {            { 1}, { 0, 2},             { 0, 1, 3, 4},             { 2, 4}, { 0}        };        // Iterate over the range [1, N]        for(inti = 1; i < n; i++) {            // Traverse the directed graph            for(intu = 0; u < 5; u++) {                dp[i + 1][u] = 0;                // Traversing the list                for(intv : relation[u]) {                    // Update dp[i + 1][u]                    dp[i + 1][u] += dp[i][v] % MOD;                }            }        }        // Stores total count of permutations        longans = 0;        for(inti = 0; i < 5; i++) {            ans = (ans + dp[n][i]) % MOD;        }        // Return count of permutations        return(int)ans;    }    // Driver Code    publicstaticvoidmain(String[] args)    {        intN = 2;        System.out.println(            countVowelPermutation(N));    }} | 
Python3
| # Python 3 program for the above approach # Function to find the number of # vowel permutations possible defcountVowelPermutation(n):      # To avoid the large output value    MOD =1e9+7    # Initialize 2D dp array    dp =[[0fori inrange(5)] forj inrange(n +1)]        # Initialize dp[1][i] as 1 since    # string of length 1 will consist    # of only one vowel in the string    fori inrange(5):        dp[1][i] =1        # Directed graph using the    # adjacency matrix    relation =[[1],[0, 2], [0, 1, 3, 4], [2, 4],[0]]    # Iterate over the range [1, N]    fori inrange(1, n, 1):              # Traverse the directed graph        foru inrange(5):            dp[i +1][u] =0            # Traversing the list            forv inrelation[u]:                              # Update dp[i + 1][u]                dp[i +1][u] +=dp[i][v] %MOD    # Stores total count of permutations    ans =0    fori inrange(5):        ans =(ans +dp[n][i]) %MOD    # Return count of permutations    returnint(ans)# Driver codeif__name__ =='__main__':    N =2    print(countVowelPermutation(N))        # This code is contributed by bgangwar59. | 
C#
| // C# program to find absolute difference // between the sum of all odd frequency and // even frequent elements in an array usingSystem;usingSystem.Collections.Generic; classGFG {        // Function to find the number of    // vowel permutations possible    staticintcountVowelPermutation(intn)    {              // To avoid the large output value        intMOD = (int)(1e9 + 7);         // Initialize 2D dp array        long[,] dp = newlong[n + 1, 5];         // Initialize dp[1][i] as 1 since        // string of length 1 will consist        // of only one vowel in the string        for(inti = 0; i < 5; i++) {            dp[1, i] = 1;        }         // Directed graph using the        // adjacency matrix        List<List<int>> relation = newList<List<int>>();        relation.Add(newList<int> { 1 });        relation.Add(newList<int> { 0, 2 });        relation.Add(newList<int> { 0, 1, 3, 4 });        relation.Add(newList<int> { 2, 4 });        relation.Add(newList<int> { 0 });         // Iterate over the range [1, N]        for(inti = 1; i < n; i++)         {             // Traverse the directed graph            for(intu = 0; u < 5; u++)            {                dp[i + 1, u] = 0;                 // Traversing the list                foreach(intv inrelation[u])                 {                     // Update dp[i + 1][u]                    dp[i + 1, u] += dp[i, v] % MOD;                }            }        }         // Stores total count of permutations        longans = 0;         for(inti = 0; i < 5; i++)        {            ans = (ans + dp[n, i]) % MOD;        }         // Return count of permutations        return(int)ans;    }   // Driver code  staticvoidMain() {    intN = 2;    Console.WriteLine(countVowelPermutation(N));  }}// This code is contributed by divyesh072019. | 
Javascript
| <script>// JavaScript program to implement// the above approach    // Function to find the number of    // vowel permutations possible    function    countVowelPermutation(n)    {        // To avoid the large output value        let MOD = (1e9 + 7);         // Initialize 2D dp array        let dp = newArray(n + 1);                // Loop to create 2D array using 1D array        for(vari = 0; i < dp.length; i++) {            dp[i] = newArray(2);        }         // Initialize dp[1][i] as 1 since        // string of length 1 will consist        // of only one vowel in the string        for(let i = 0; i < 5; i++) {            dp[1][i] = 1;        }         // Directed graph using the        // adjacency matrix        let relation = [            [ 1 ], [ 0, 2 ],            [ 0, 1, 3, 4 ],            [ 2, 4 ], [ 0 ]        ];         // Iterate over the range [1, N]        for(let i = 1; i < n; i++) {             // Traverse the directed graph            for(let u = 0; u < 5; u++) {                dp[i + 1][u] = 0;                 // Traversing the list                for(let v inrelation[u]) {                     // Update dp[i + 1][u]                    dp[i + 1][u] += dp[i][v] % MOD;                }            }        }         // Stores total count of permutations        let ans = 0;         for(let i = 0; i < 5; i++) {            ans = (ans + dp[n][i]) % MOD;        }         // Return count of permutations        returnans;    }     // Driver code            let N = 2;    document.write(            countVowelPermutation(N));</script> | 
10
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
 
				 
					



