Open In App

Minimize changes to make all characters equal by changing vowel to consonant and vice versa

Last Updated : 17 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 choose a vowel and change it to a consonant or vice-versa.

Examples:

Input: str[] = “geeksforgeeks”
Output: 10
Explanation: To make all the characters equal, make the following changes – 

  1. Change ‘o’ to a consonant(let’s say) ‘z’ and then to ‘e’
  2. 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”
Output: 6

Approach: It can be deduced from the problem statement that in order to change a consonant to a vowel or vice versa, 1 operation is required. In order to change a vowel to a vowel or a consonant to a consonant, 2 operations are required. Because for changing vowel to vowel, first we need to change vowel -> consonant and then consonant -> vowel. Similarly, for changing consonant to consonant, first we need to change consonant -> vowel and then vowel -> consonant . The idea would be to maintain two variables in parallel :-

  • 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 occurring vowel and maximum occurring 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 occurring 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:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number
// of steps to make all characters equal
int operations(string s)
{
 
    // Initializing the variables
    int ans = 0;
    int vowels = 0, consonants = 0;
    int max_vowels = INT_MIN;
    int max_consonants = INT_MIN;
 
    // Store the frequency
    unordered_map<char, int> freq_consonants;
    unordered_map<char, int> freq_vowels;
 
    // Iterate over the string
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == 'a' or s[i] == 'e' or s[i] == 'i'
            or s[i] == 'o' or s[i] == 'u') {
 
            // Calculate the total
            // number of vowels
            vowels += 1;
 
            // Storing frequency of
            // each vowel
            freq_vowels[s[i]] += 1;
        }
        else {
 
            // Count the consonants
            consonants += 1;
 
            // Storing the frequency of
            // each consonant
            freq_consonants[s[i]] += 1;
        }
    }
 
    // Iterate over the 2 maps
    for (auto it = freq_consonants.begin();
         it != freq_consonants.end(); it++) {
 
        // Maximum frequency of consonant
        max_consonants = max(
            max_consonants,
            it->second);
    }
    for (auto it = freq_vowels.begin();
         it != freq_vowels.end(); it++) {
 
        // Maximum frequency of vowel
        max_vowels
            = max(max_vowels,
                  it->second);
    }
 
    // Find the result
    ans = min((2 * (vowels - max_vowels)
               + consonants),
              (2 * (consonants - max_vowels)
               + consonants));
 
    return ans;
}
 
// Driver Code
int main()
{
    string S = "geeksforgeeks";
    cout << operations(S);
 
    return 0;
}


Java




// Java program to implement the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Function to find the minimum number of steps to make
  // all characters equal
  static int operations(String s)
  {
 
    // Initializign the variables
    int ans = 0;
    int vowels = 0, consonants = 0;
    int max_vowels = Integer.MIN_VALUE;
    int max_consonants = Integer.MIN_VALUE;
 
    // Store the frequency
    HashMap<Character, Integer> freq_consonants
      = new HashMap<>();
    HashMap<Character, Integer> freq_vowels
      = new HashMap<>();
 
    // Iterate over the string
    for (int i = 0; i < s.length(); i++) {
      if (s.charAt(i) == 'a' || s.charAt(i) == 'e'
          || s.charAt(i) == 'i' || s.charAt(i) == 'o'
          || s.charAt(i) == 'u') {
 
        // Calculate the total
        // number of vowels
        vowels += 1;
 
        // Storing frequency of
        // each vowel
        freq_vowels.put(
          s.charAt(i),
          freq_vowels.getOrDefault(s.charAt(i), 0)
          + 1);
      }
      else {
 
        // Count the consonants
        consonants += 1;
 
        // Storing the frequency of
        // each consonant
        freq_consonants.put(
          s.charAt(i),
          freq_consonants.getOrDefault(
            s.charAt(i), 0)
          + 1);
      }
    }
 
    // Iterate over the 2 maps
    for (Map.Entry<Character, Integer> it :
         freq_consonants.entrySet()) {
 
      // Maximum frequency of consonant
      max_consonants
        = Math.max(max_consonants, it.getValue());
    }
 
    for (Map.Entry<Character, Integer> it :
         freq_vowels.entrySet()) {
 
      // Maximum frequency of vowel
      max_vowels
        = Math.max(max_vowels, it.getValue());
    }
 
    // Find the result
    ans = Math.min(
      (2 * (vowels - max_vowels) + consonants),
      (2 * (consonants - max_vowels) + consonants));
 
    return ans;
  }
 
  public static void main(String[] args)
  {
    String S = "geeksforgeeks";
    System.out.print(operations(S));
  }
}
 
// This code is contributed by lokeshmvs21.


Python3




# Python 3 program for the above approach
import sys
from collections import defaultdict
 
# Function to find the minimum number
# of steps to make all characters equal
def operations(s):
 
    # Initializing the variables
    ans = 0
    vowels = 0
    consonants = 0
    max_vowels = -sys.maxsize-1
    max_consonants = -sys.maxsize-1
 
    # Store the frequency
    freq_consonants = defaultdict(int)
    freq_vowels = defaultdict(int)
 
    # Iterate over the string
    for i in range(len(s)):
        if (s[i] == 'a' or s[i] == 'e' or s[i] == 'i'
                or s[i] == 'o' or s[i] == 'u'):
 
            # Calculate the total
            # number of vowels
            vowels += 1
 
            # Storing frequency of
            # each vowel
            freq_vowels[s[i]] += 1
 
        else:
 
            # Count the consonants
            consonants += 1
 
            # Storing the frequency of
            # each consonant
            freq_consonants[s[i]] += 1
 
    # Iterate over the 2 maps
    for it in freq_consonants:
 
        # Maximum frequency of consonant
        max_consonants = max(
            max_consonants,
            freq_consonants[it])
 
    for it in freq_vowels:
 
        # Maximum frequency of vowel
        max_vowels = max(max_vowels,
                         freq_vowels[it])
 
    # Find the result
    ans = min((2 * (vowels - max_vowels)
               + consonants),
              (2 * (consonants - max_vowels)
               + consonants))
 
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    S = "geeksforgeeks"
    print(operations(S))
 
    # This code is contributed by ukasp.


Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
        // Function to find the minimum number
        // of steps to make all characters equal
        function operations(s) {
 
            // Initializing the variables
            let ans = 0;
            let vowels = 0, consonants = 0;
            let max_vowels = Number.MIN_VALUE;
            let max_consonants = Number.MIN_VALUE;
 
            // Store the frequency
            let freq_consonants = new Map();
            let freq_vowels = new Map();
 
            // Iterate over the string
            for (let i = 0; i < s.length; i++)
            {
                if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i'
                    || s.charAt(i) == 'o' || s.charAt(i) == 'u') {
 
                    // Calculate the total
                    // number of vowels
                    vowels += 1;
 
                    // Storing frequency of
                    // each vowel
                    if (freq_vowels.has(s.charAt(i))) {
                        freq_vowels.set(s.charAt(i), freq_vowels.get(s.charAt(i)) + 1)
                    }
                    else {
                        freq_vowels.set(s.charAt(i), 1);
                    }
 
                }
                else {
 
                    // Count the consonants
                    consonants += 1;
 
                    // Storing the frequency of
                    // each consonant
                    if (freq_consonants.has(s.charAt(i))) {
                        freq_consonants.set(s.charAt(i), freq_consonants.get(s.charAt(i)) + 1)
                    }
                    else {
                        freq_consonants.set(s.charAt(i), 1);
                    }
 
                }
            }
 
            // Iterate over the 2 maps
            for (let [key, value] of freq_consonants) {
 
                // Maximum frequency of consonant
                max_consonants = Math.max(
                    max_consonants,
                    value);
            }
            for (let [key1, value1] of freq_vowels) {
 
                // Maximum frequency of vowel
                max_vowels
                    = Math.max(max_vowels,
                        value1);
            }
 
            // Find the result
            ans = Math.min((2 * (vowels - max_vowels)
                + consonants),
                (2 * (consonants - max_vowels)
                    + consonants));
 
            return ans;
        }
 
        // Driver Code
        let S = "geeksforgeeks";
        document.write(operations(S));
 
     // This code is contributed by Potta Lokesh
    </script>


C#




using System;
using System.Collections.Generic;
 
class Program {
    // Function to find the minimum number
    // of steps to make all characters equal
    static int Operations(string s)
    {
        // Initializing the variables
        int ans = 0;
        int vowels = 0, consonants = 0;
        int maxVowels = int.MinValue;
        int maxConsonants = int.MinValue;
 
        // Store the frequency
        var freqConsonants = new Dictionary<char, int>();
        var freqVowels = new Dictionary<char, int>();
 
        // Iterate over the string
        for (int i = 0; i < s.Length; i++) {
            if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i'
                || s[i] == 'o' || s[i] == 'u') {
                // Calculate the total
                // number of vowels
                vowels += 1;
 
                // Storing frequency of
                // each vowel
                if (!freqVowels.ContainsKey(s[i])) {
                    freqVowels[s[i]] = 1;
                }
                else {
                    freqVowels[s[i]] += 1;
                }
            }
            else {
                // Count the consonants
                consonants += 1;
 
                // Storing the frequency of
                // each consonant
                if (!freqConsonants.ContainsKey(s[i])) {
                    freqConsonants[s[i]] = 1;
                }
                else {
                    freqConsonants[s[i]] += 1;
                }
            }
        }
 
        // Iterate over the 2 dictionaries
        foreach(var pair in freqConsonants)
        {
            // Maximum frequency of consonant
            maxConsonants
                = Math.Max(maxConsonants, pair.Value);
        }
        foreach(var pair in freqVowels)
        {
            // Maximum frequency of vowel
            maxVowels = Math.Max(maxVowels, pair.Value);
        }
 
        // Find the result
        ans = Math.Min(
            (2 * (vowels - maxVowels) + consonants),
            (2 * (consonants - maxVowels) + consonants));
 
        return ans;
    }
 
    // Driver Code
    static void Main()
    {
        string S = "geeksforgeeks";
        Console.WriteLine(Operations(S));
    }
}


Output: 

10

 

Time Complexity: O(N)
Auxiliary Space: O(1) as it is using constant space for variables and map to store the frequency of characters



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads