Open In App

Count ways to create string of size N with given restrictions

Last Updated : 21 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number N, the task is to count the number of ways to create a string of size N (only with capital alphabets) such that no vowel is between two consonants and the string does not start with the letter ‘A’ and does not end with the letter ‘Z’. (Print the answer modulo 109 + 7).

Examples:

Input: N = 1
Output: 24
Explanation: There are 24 ways of filling 1 sized string by every character of the alphabet apart from the letter ‘A’ because it cannot be the first letter of the required string and the letter ‘Z’ because it cannot be the last letter of required string and for 1 sized string first and last positions are same.

Input: N = 2
Output: 625
Explanation: The first position can be filled in 25 ways(because letter A cannot be on that position as it is the first position so one less than 26) and the second position can be filled in 25 ways(because letter Z cannot be on that position as it is the last position so one less than 26), Therefore, Total ways = 25 * 25 = 625

Naive approach: The basic way to solve the problem is as follows:

The basic way to solve this problem is to generate all possible combinations by using a recursive approach.

Time Complexity: O(6N)
Auxiliary Space: O(1)

Efficient Approach:  The above approach can be optimized based on the following idea:

Bitmask Dynamic programming can be used to solve this problem

  • Bitmask of the last two characters is maintained in order to avoid choosing a vowel in between two consonants.
  • dp[i][j] represents the number of ways of creating a string of size i  and j is the bitmask for the last two characters.

It can be observed that the recursive function is called exponential times. That means that some states are called repeatedly. So the idea is to store the value of each state. This can be done using by the store the value of a state and whenever the function is called, returning the stored value without computing again.

Follow the steps below to solve the problem:

  • Create a recursive function that takes two parameters representing the ith position to be filled and j representing the bitmask of the last two characters.
  • Call the recursive function for choosing all characters from 1 to 26.
  • Base case if all positions filled return 1.
  • Create a 2d array of dp[N][6] initially filled with -1.
  • If the answer for a particular state is computed then save it in dp[i][j].
  • If the answer for a particular state is already computed then just return dp[i][j].

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
const int MOD = 1e9 + 7;
 
// DP table initialized with -1
int dp[1000001][6];
 
// Recursive Function to count ways to
// create string of size N with no vowel
// is between two consonants and string
// does not start with A and does not
// end with Z.
int recur(int i, int j, int N, int id[])
{
 
    // Base case
    if (i == N) {
        return 1;
    }
 
    // If answer for current state is
    // already calculated then just
    // return dp[i][j]
    if (dp[i][j] != -1)
        return dp[i][j];
 
    int ans = 0;
 
    // Traversing for all characters
    for (int k = 1; k <= 26; k++) {
 
        // First position cannot be A
        if (i == 0 and k == 1)
            continue;
 
        // Last position cannot be Z
        if (i == N - 1 and k == 26)
            continue;
 
        // Let 1 represents vowel 0
        // represents consonant trouble
        // is 01 avoid 0 after that its
        // fine to have 00, 10, and 11
        // in our bitmask j
        if (i <= 1) {
 
            // Recursive call for vowel
            if (id[k])
                ans += recur(i + 1, (2 * j) | 1, N, id);
 
            // Recursive call for consonant
            else
                ans += recur(i + 1, 2 * j, N, id);
        }
        else {
 
            // Recursive call for taking vowel
            ans += recur(i + 1, (2 * j) | 1, N, id);
 
            // If last two are 01 that is
            // consonant after vowel then
            // avoid taking 0 that is
            // consonant for current
            // position for current
            // recursive call
            if (j != 1)
                ans += recur(i + 1, 2 * j, N, id);
        }
    }
 
    // Save and return dp value
    return dp[i][j] = ans;
}
 
// Function to count ways to create
// string of size N with no vowel is
// between two consonants and string
// does not start with A and does not
// end with Z.
int countWaysTo(int N)
{
 
    // Initializing dp array with - 1
    memset(dp, -1, sizeof(dp));
 
    // Id to identify given characters
    // whether they are vowel or consonant
    int id[27];
 
    // Indicator id that indicates whether
    // given character is vowel or consonant
    for (int i = 1; i <= 26; i++) {
 
        // If it is equal to a, e, i, o or
        // u then it is a vowel else
        // consonant
        if (i == 1 | i == 5 | i == 9 | i == 15 | i == 21)
            id[i] = 1;
        else
            id[i] = 2;
    }
 
    return recur(0, 0, N, id);
}
 
// Driver Code
int main()
{
    // Input 1
    int N = 1;
 
    // Function Call
    cout << countWaysTo(N) << endl;
 
    // Input 2
    int N1 = 2;
 
    // Function Call
    cout << countWaysTo(N1) << endl;
    return 0;
}


Java




// Java code to implement the approach
import java.io.*;
import java.util.*;
 
class GFG {
 
  static final int MOD = (int)1e9 + 7;
  static int[][] dp = new int[1000001][6];
 
  // Recursive Function to count ways to
  // create string of size N with no vowel
  // is between two consonants and string
  // does not start with A and does not
  // end with Z.
  static int recur(int i, int j, int N, int[] id)
  {
    // Base case
    if (i == N) {
      return 1;
    }
 
    // If answer for current state is
    // already calculated then just
    // return dp[i][j]
    if (dp[i][j] != -1)
      return dp[i][j];
 
    int ans = 0;
 
    // Traversing for all characters
    for (int k = 1; k <= 26; k++) {
 
      // First position cannot be A
      if (i == 0 && k == 1)
        continue;
 
      // Last position cannot be Z
      if (i == N - 1 && k == 26)
        continue;
 
      // Let 1 represents vowel 0
      // represents consonant trouble
      // is 01 avoid 0 after that its
      // fine to have 00, 10, and 11
      // in our bitmask j
      if (i <= 1) {
 
        // Recursive call for vowel
        if (id[k] == 1)
          ans += recur(i + 1, (2 * j) | 1, N, id);
 
        // Recursive call for consonant
        else
          ans += recur(i + 1, 2 * j, N, id);
      }
      else {
 
        // Recursive call for taking vowel
        ans += recur(i + 1, (2 * j) | 1, N, id);
 
        // If last two are 01 that is
        // consonant after vowel then
        // avoid taking 0 that is
        // consonant for current
        // position for current
        // recursive call
        if (j != 1)
          ans += recur(i + 1, 2 * j, N, id);
      }
    }
 
    // Save and return dp value
    return dp[i][j] = ans;
  }
 
  // Function to count ways to create
  // string of size N with no vowel is
  // between two consonants and string
  // does not start with A and does not
  // end with Z.
  static int countWaysTo(int N)
  {
    // Initializing dp array with - 1
    for (int[] row : dp) {
      Arrays.fill(row, -1);
    }
 
    // Id to identify given characters
    // whether they are vowel or consonant
    int[] id = new int[27];
 
    // Indicator id that indicates whether
    // given character is vowel or consonant
    for (int i = 1; i <= 26; i++) {
 
      // If it is equal to a, e, i, o or
      // u then it is a vowel else
      // consonant
      if (i == 1 || i == 5 || i == 9 || i == 15
          || i == 21)
        id[i] = 1;
      else
        id[i] = 2;
    }
 
    return recur(0, 0, N, id);
  }
 
  public static void main(String[] args)
  {
    // Input 1
    int N = 1;
 
    // Function Call
    System.out.println(countWaysTo(N));
 
    // Input 2
    int N1 = 2;
 
    // Function Call
    System.out.println(countWaysTo(N1));
  }
}
 
// This code is contributed by lokeshmvs21.


Python3




MOD = int(1e9 + 7)
 
# DP table initialized with -1
dp = [[-1 for j in range(6)] for i in range(1000001)]
 
# Recursive Function to count ways to
# create string of size N with no vowel
# is between two consonants and string
# does not start with A and does not
# end with Z.
def recur(i, j, N, id):
    # Base case
    if i == N:
        return 1
 
    # If answer for current state is
    # already calculated then just
    # return dp[i][j]
    if dp[i][j] != -1:
        return dp[i][j]
 
    ans = 0
 
    # Traversing for all characters
    for k in range(1, 27):
 
        # First position cannot be A
        if i == 0 and k == 1:
            continue
 
        # Last position cannot be Z
        if i == N - 1 and k == 26:
            continue
 
        # Let 1 represents vowel 0
        # represents consonant trouble
        # is 01 avoid 0 after that its
        # fine to have 00, 10, and 11
        # in our bitmask j
        if i <= 1:
 
            # Recursive call for vowel
            if id[k] == 1:
                ans += recur(i + 1, (2 * j) | 1, N, id)
 
            # Recursive call for consonant
            else:
                ans += recur(i + 1, 2 * j, N, id)
        else:
 
            # Recursive call for taking vowel
            ans += recur(i + 1, (2 * j) | 1, N, id)
 
            # If last two are 01 that is
            # consonant after vowel then
            # avoid taking 0 that is
            # consonant for current
            # position for current
            # recursive call
            if j != 1:
                ans += recur(i + 1, 2 * j, N, id)
 
    # Save and return dp value
    dp[i][j] = ans
    return ans
 
# Function to count ways to create
# string of size N with no vowel is
# between two consonants and string
# does not start with A and does not
# end with Z.
def countWaysTo(N):
    # Initializing dp array with - 1
 
    # Id to identify given characters
    # whether they are vowel or consonant
    id = [0 for i in range(27)]
 
    # Indicator id that indicates whether
    # given character is vowel or consonant
    for i in range(1, 27):
 
        # If it is equal to a, e, i, o or
        # u then it is a vowel else
        # consonant
        if i in [1, 5, 9, 15, 21]:
            id[i] = 1
        else:
            id[i] = 2
 
    return recur(0, 0, N, id)
 
# Driver Code
if __name__ == '__main__':
    # Input 1
    N = 1
 
    # Function Call
    print(countWaysTo(N))
 
    # Input 2
    N1 = 2
 
   # Function Call
    print(countWaysTo(N1))


C#




class Program
{
    static int MOD = (int)1e9 + 7;
    static int[][] dp = new int[1000001][];
 
    // Recursive Function to count ways to
    // create string of size N with no vowel
    // is between two consonants and string
    // does not start with A and does not
    // end with Z.
    static int recur(int i, int j, int N, int[] id)
    {
        // Base case
        if (i == N)
        {
            return 1;
        }
 
        // If answer for current state is
        // already calculated then just
        // return dp[i][j]
        if (dp[i][j] != -1)
            return dp[i][j];
 
        int ans = 0;
 
        // Traversing for all characters
        for (int k = 1; k <= 26; k++)
        {
            // First position cannot be A
            if (i == 0 && k == 1)
                continue;
 
            // Last position cannot be Z
            if (i == N - 1 && k == 26)
                continue;
 
            // Let 1 represents vowel 0
            // represents consonant trouble
            // is 01 avoid 0 after that its
            // fine to have 00, 10, and 11
            // in our bitmask j
            if (i <= 1)
            {
                // Recursive call for vowel
                if (id[k] == 1)
                    ans += recur(i + 1, (2 * j) | 1, N, id);
 
                // Recursive call for consonant
                else
                    ans += recur(i + 1, 2 * j, N, id);
            }
            else
            {
                // Recursive call for taking vowel
                ans += recur(i + 1, (2 * j) | 1, N, id);
 
                // If last two are 01 that is
                // consonant after vowel then
                // avoid taking 0 that is
                // consonant for current
                // position for current
                // recursive call
                if (j != 1)
                    ans += recur(i + 1, 2 * j, N, id);
            }
        }
 
        // Save and return dp value
        dp[i][j] = ans;
        return ans;
    }
 
    // Function to count ways to create
    // string of size N with no vowel is
    // between two consonants and string
    // does not start with A and does not
    // end with Z.
    static int countWaysTo(int N)
    {
        // Initializing dp array with - 1
        for (int i = 0; i < dp.Length; i++)
        {
            dp[i] = new int[6];
            for (int j = 0; j < 6; j++)
            {
                dp[i][j] = -1;
            }
        }
 
        // Id to identify given characters
        // whether they are vowel or consonant
        int[] id = new int
        [27];
 
        // Indicator id that indicates whether
        // given character is vowel or consonant
        for (int i = 1; i <= 26; i++)
        {
 
            // If it is equal to a, e, i, o or
            // u then it is a vowel else
            // consonant
            if (i == 1 || i == 5 || i == 9 || i == 15 || i == 21)
                id[i] = 1;
            else
                id[i] = 2;
        }
 
        return recur(0, 0, N, id);
    }
 
    static void Main(string[] args)
    {
        // Input 1
        int N = 1;
 
        // Function Call
        Console.WriteLine(countWaysTo(N));
 
        // Input 2
        int N1 = 2;
 
        // Function Call
        Console.WriteLine(countWaysTo(N1));
    }
}


Javascript




// Javascript code to implement the approach
const MOD = 1e9 + 7;
 
// DP table initialized with -1
let dp = new Array(1000001);
for(let i = 0; i < 1000001; i++)
    dp[i] = new Array(6).fill(-1);
 
// Recursive Function to count ways to
// create string of size N with no vowel
// is between two consonants and string
// does not start with A and does not
// end with Z.
function recur(i, j, N, id)
{
 
    // Base case
    if (i == N) {
        return 1;
    }
 
    // If answer for current state is
    // already calculated then just
    // return dp[i][j]
    if (dp[i][j] != -1)
        return dp[i][j];
 
    let ans = 0;
 
    // Traversing for all characters
    for (let k = 1; k <= 26; k++) {
 
        // First position cannot be A
        if (i == 0 && k == 1)
            continue;
 
        // Last position cannot be Z
        if (i == N - 1 && k == 26)
            continue;
 
        // Let 1 represents vowel 0
        // represents consonant trouble
        // is 01 avoid 0 after that its
        // fine to have 00, 10, and 11
        // in our bitmask j
        if (i <= 1) {
 
            // Recursive call for vowel
            if (id[k])
                ans += recur(i + 1, (2 * j) | 1, N, id);
 
            // Recursive call for consonant
            else
                ans += recur(i + 1, 2 * j, N, id);
        }
        else {
 
            // Recursive call for taking vowel
            ans += recur(i + 1, (2 * j) | 1, N, id);
 
            // If last two are 01 that is
            // consonant after vowel then
            // avoid taking 0 that is
            // consonant for current
            // position for current
            // recursive call
            if (j != 1)
                ans += recur(i + 1, 2 * j, N, id);
        }
    }
 
    // Save and return dp value
    return dp[i][j] = ans;
}
 
// Function to count ways to create
// string of size N with no vowel is
// between two consonants and string
// does not start with A and does not
// end with Z.
function countWaysTo(N)
{
    // Initializing dp array with - 1
    for(let i=0; i<1000001; i++)
    {
        for(let j=0; j<6; j++)
            dp[i][j]=-1;
    }
 
    // Id to identify given characters
    // whether they are vowel or consonant
    let id = new Array(27);
 
    // Indicator id that indicates whether
    // given character is vowel or consonant
    for (let i = 1; i <= 26; i++) {
 
        // If it is equal to a, e, i, o or
        // u then it is a vowel else
        // consonant
        if (i == 1 | i == 5 | i == 9 | i == 15 | i == 21)
            id[i] = 1;
        else
            id[i] = 2;
    }
 
    return recur(0, 0, N, id);
}
 
// Driver Code
// Input 1
let N = 1;
 
// Function Call
console.log(countWaysTo(N));
 
// Input 2
let N1 = 2;
 
// Function Call
console.log(countWaysTo(N1));
 
// This code is contributed by poojaagarwal2.


Output

24
625

Time Complexity: O(N)  
Auxiliary Space: O(N)

Related Articles:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads