Given a string str consisting of N letters, the task is to find the total number of strings that can be generated by replacing each consonant with the vowel closest to it in the English alphabet.
Input: str = “code”
Explanation: Str = “code” has two consonant c and d.
Closest vowel to d is e and closest to c are a and e.
The possible strings are “aoee” and “eoee“
Input: str = “geeks”
Approach: The problem can be solved based on the following observation:
There are total 21 consonant in which ‘c’, ‘g’, ‘l’ and ‘r’ are consonant which is closest to two vowels.
So only these consonants have 2 choices and the reamining have one choices each.
Therefore, the total number of possible strings = the product of the number of choices for each consonant.
Follow the steps mentioned below to implement the observation:
- Initialize a variable (say res = 1) to store the number of possible strings.
- Iterate through the string from i = 0 to N:
- If the character is one of the four special consonants mentioned above then they have two choices. So multiply 2 with res.
- Otherwise, multiply 1 with the value of res.
- The final value of res is the required answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)