Given a string S of length N containing lowercase alphabets. Two players A and B play a game optimally in turns, starting with player A. In each move, either of the following operations can be performed:
- Remove a consonant from the string.
- If any character is a vowel, then convert it into any other alphabet.
A player loses the game if there is an even number of consonants and no vowels left in the string. The task is to determine the winner of the game. In case of a draw, print D.
Input: S = “abcd”
Output: Player A
Player A can win by performing the following moves:
Move 1: A changes a to f. Therefore, S = “fbcd”
Move 2: B removes f. Therefore, S = “bcd”.
Move 3: A removes b. Therefore, S = “cd”.
Move 4: B removes c. Therefore, S = “d”.
Move 5: A removes d. Therefore, S = “”.
Now in B’s turn, S have no vowels and an even number of consonants i.e., 0.
Input: S = “abcde”
Approach: To solve the problem, observe the following cases:
- If no vowels and an even number of consonants are present in the string then the player who starts the game loses the game, i.e. player B wins.
- If no vowels and an odd number of consonants are present in the string then the player who starts the game wins the game, i.e. player A win.
- If a single vowel and an odd number of consonants are present in the given string player A can win.
- If more than one vowels are present in the string, it’s a draw.
Follow the below steps to solve the problem:
- Count the number of consonants in the given string S and store it in a variable, say X.
- Therefore, the count of vowels in the given string S is equal to N – X.
- Print D if the N – X is greater than 1.
- Print player B if the N – X is 0 and X is even.
- Else print player A.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.