Count ways to create string of size N with given restrictions
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).
Input: N = 1
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
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] 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:
Time Complexity: O(N)
Auxiliary Space: O(N)
- Introduction to Dynamic Programming – Data Structures and Algorithms Tutorials
- Bitmasking and Dynamic Programming
Please Login to comment...