![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
24 625
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Articles: