Minimum characters to be replaced to make frequency of all characters same

Given a string S consisting of alphabets [‘A’ – ‘Z’], the task is to find the minimum number of operations required to make frequency of every character equal. In one operation any character of the string can be chosen and replaced with another valid character.

Examples:

Input: S = “ABCB”
Output: 1
Explanation:
In the given string character ‘C’ can be replaced by ‘A’, such that occurrence of every character becomes equal to 2.
Updated String = “ABAB”

Input: S = “BBC”
Output : 1
Explanation:
In the given string character ‘C’ can be replaced by ‘B’, such that occurrence of every character becomes equal to 3.
Updated string = “BBB”

Approach: The idea is to find the frequency of every character in the string and then sort the characters according to their frequencies in descending order. Finally, we can check for each character of string which yields the minimum number of characters to be changed and print this minimum number of characters to be changed.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the
// Minimum characters to be replaced
// to make frequency of all characters same
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the
// Minimum operations to convert
// given string to another with
// equal frequencies of characters
int minOperations(string s)
{
    // Frequency of characters
    int freq[26] = { 0 };
    int n = s.length();
  
    // Loop to find the Frequency
    // of each character
    for (int i = 0; i < n; i++) {
        freq[s[i] - 'A']++;
    }
  
    // Sort in decreasing order
    // based on frequency
    sort(freq, freq + 26, greater<int>());
  
    // Maximum possible answer
    int answer = n;
  
    // Loop to find the minimum operations
    // required such that frequency of
    // every character is equal
    for (int i = 1; i <= 26; i++) {
        if (n % i == 0) {
            int x = n / i;
            int y = 0;
            for (int j = 0; j < i; j++) {
                y += min(freq[j], x);
            }
            answer = min(answer, n - y);
        }
    }
    return answer;
}
  
// Driver Code
int main()
{
    string s = "BBC";
    cout << minOperations(s);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the
// Minimum characters to be replaced
// to make frequency of all characters same
   
  
import java.util.*;
  
class GFG{
   
// Function to find the
// Minimum operations to convert
// given String to another with
// equal frequencies of characters
static int minOperations(String s)
{
    // Frequency of characters
    Integer freq[] = new Integer[26];
    Arrays.fill(freq, 0);
    int n = s.length();
   
    // Loop to find the Frequency
    // of each character
    for (int i = 0; i < n; i++) {
        freq[s.charAt(i) - 'A']++;
    }
   
    // Sort in decreasing order
    // based on frequency
    Arrays.sort(freq, Collections.reverseOrder());
   
    // Maximum possible answer
    int answer = n;
   
    // Loop to find the minimum operations
    // required such that frequency of
    // every character is equal
    for (int i = 1; i <= 26; i++) {
        if (n % i == 0) {
            int x = n / i;
            int y = 0;
            for (int j = 0; j < i; j++) {
                y += Math.min(freq[j], x);
            }
            answer = Math.min(answer, n - y);
        }
    }
    return answer;
}
   
// Driver Code
public static void main(String[] args)
{
    String s = "BBC";
    System.out.print(minOperations(s));
   
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find the
# minimum characters to be replaced
# to make frequency of all characters same
  
# Function to find the minimum 
# operations to convert given 
# string to another with equal 
# frequencies of characters
def minOperations(s):
  
    # Frequency of characters
    freq = [0] * 26
    n = len(s)
  
    # Loop to find the Frequency
    # of each character
    for i in range(n):
        freq[ord(s[i]) - ord('A')] += 1
      
    # Sort in decreasing order
    # based on frequency
    freq.sort(reverse = True)
  
    # Maximum possible answer
    answer = n
  
    # Loop to find the minimum operations
    # required such that frequency of
    # every character is equal
    for i in range(1, 27):
        if (n % i == 0):
            x = n // i
            y = 0
              
            for j in range(i):
                y += min(freq[j], x)
              
            answer = min(answer, n - y)
              
    return answer
  
# Driver Code
if __name__ == "__main__":
  
    s = "BBC"
      
    print (minOperations(s))
  
# This code is contributed by chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find the minimum
// characters to be replaced to make 
// frequency of all characters same
using System;
  
class GFG{
  
// Function to find the minimum
// operations to convert given
// string to another with equal
// frequencies of characters
static int minOperations(String s)
{
      
    // Frequency of characters
    int []freq = new int[26];
    int n = s.Length;
  
    // Loop to find the frequency
    // of each character
    for(int i = 0; i < n; i++)
    {
       freq[s[i] - 'A']++;
    }
  
    // Sort in decreasing order
    // based on frequency
    Array.Sort(freq);
    Array.Reverse(freq);
      
    // Maximum possible answer
    int answer = n;
  
    // Loop to find the minimum operations
    // required such that frequency of
    // every character is equal
    for(int i = 1; i <= 26; i++)
    {
       if (n % i == 0) 
       {
           int x = n / i;
           int y = 0;
             
           for(int j = 0; j < i; j++) 
           {
              y += Math.Min(freq[j], x);
           }
           answer = Math.Min(answer, n - y);
       }
    }
    return answer;
}
  
// Driver Code
public static void Main(String[] args)
{
    String s = "BBC";
      
    Console.Write(minOperations(s));
  
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

1

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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.