Minimize changes to make all characters equal by changing vowel to consonant and vice versa
Given a string str of lower-case characters, the task is to make all characters of the string equal in the minimum number of operations such that in each operation either chooses a vowel and changes it to a consonant or vice-versa.
Input: str = “geeksforgeeks”
Explanation: To make all the characters equal, make the following changes –
- Change ‘o’ to a consonant(let’s say) ‘z’ and then to ‘e’
- Change every other consonant(‘g’, ‘k’, ‘s’, ‘ f’, ‘r’, ) to ‘e’
This results in the string str = “eeeeeeeeeeeee” and the total number of operations performed is 10.
Input: str = “coding”
Approach: It can be deduced from the problem that in order to change a consonant to a vowel, 1 operation is required and in order to change a vowel to a vowel or a consonant to a consonant, 2 steps are required as it is needed to change a vowel to a consonant and then again back to a vowel in case of changing a vowel to a vowel or changing a consonant to a vowel and then again back to a consonant in case of changing a consonant to a consonant. The idea would be to maintain two variables –
- Cv = the cost of changing all the characters to the maximum occurring vowel = no. of consonants + ( total number of vowels – frequency of maximum occurring vowel ) * 2
- Cc = the cost of changing all the characters to the maximum occurring consonant = no. of vowels + (total number of consonants – frequency of maximum occurring consonant) * 2
Now the minimum of these 2 i.e., min(Cv, Cc) will give the required minimum number of steps in which we can transform the string. Follow the steps below to solve the problem:
- Initialize the variable ans, vowels and consonants as 0 to store the answer, number of vowels and the number of consonants.
- Initialize 2 variables max_vowels and max_consonants as INT_MIN to find the maximum occuring vowel and maximum occuring consonant in the given string.
- Initialize 2 unordered_map<char, int> freq_vowels and freq_consonant to store the frequency of vowels and consonants.
- Iterate over the range [0, N) using the variable i and perform the following steps:
- If the current character is a vowel, then increase the count of vowels by 1 and it’s frequency in the map by 1 otherwise do it for the consonant.
- Traverse both the unordered_maps and find the maximum occuring vowel and consonant.
- Using the above formula, calculate the ans.
- After performing the above steps, print the value of ans as the answer.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.