Minimize count of repositioning of characters to make all given Strings equal

• Difficulty Level : Medium
• Last Updated : 07 Dec, 2021

Given an array S of strings of size N, the task is to check if it is possible to make all strings equal in any number of operations. In one operation, any character can be removed from the string and inserted at any arbitrary position in the same or different string. If the strings can be made equal, return the minimum number of operations required along with “Yes“, else return “No“.

Examples:

Input: N = 3, S = {aaa, bbb, ccc}
Output: Yes 6
Explanation: All three strings can be made equal to string abc, in minimum 6 operations

• {aaa, bbb, ccc} -> {aa, abbb, ccc}
• {aa, abbb, ccc} -> {a, abbb, accc}
• {a, abbb, accc} -> {ab, abb, accc}
• {ab, abb, accc} -> {ab, ab, abccc}
• {ab, ab, abccc} -> {abc, ab, abcc}
• {abc, ab, abccc} -> {abc, abc, abc}

Input: N = 3, S = {aba, bbb, cda}
Output: No

Approach: The idea to make all the strings equal, can be achieved if the letters should be distributed equally in all the strings. i.e. the frequency of every character should be divisible by N. Follow the steps below to solve the given problem:

Below is the implementation of the above approach:

C++

 // C++ program for the above approach#include using namespace std; // Function to check if strings// can be formed equal or notvoid solve(string S[], int N){    // Vector to store the frequency    // of characters    vector freq(26, 0);     // Traversing the array of strings    for (int i = 0; i < N; i++) {         // Traversing characters of the        // string        for (auto x : S[i]) {             // Updating the frequency            freq[x - 'a']++;        }    }     // Checking for each character of    // alphabet    for (int i = 0; i < 26; i++) {         // If frequency is not multiple        // of N        if (freq[i] % N != 0) {            cout << "No\n";            return;        }    }     // Divide frequency of each character    // with N    for (int i = 0; i < 26; i++)        freq[i] /= N;     // Store the count of minimum    // operations    int ans = 0;     for (int i = 0; i < N; i++) {         // Store frequencies of characters        // in the original string        vector vis(26, 0);        for (char c : S[i])            vis++;         // Get the count of extra characters        for (int i = 0; i < 26; i++) {            if (freq[i] > 0 && vis[i] > 0) {                ans += abs(freq[i] - vis[i]);            }        }    }     cout << "Yes " << ans << endl;    return;} // Driver functionint main(){    int N = 3;    string S[N] = { "aaa", "bbb", "ccc" };     solve(S, N);     return 0;}

Java

 // Java program for the above approachimport java.util.*; class GFG{ // Function to check if Strings// can be formed equal or notstatic void solve(String S[], int N){       // Vector to store the frequency    // of characters    int []freq = new int;     // Traversing the array of Strings    for (int i = 0; i < N; i++) {         // Traversing characters of the        // String        for (int x : S[i].toCharArray()) {             // Updating the frequency            freq[x - 'a']++;        }    }     // Checking for each character of    // alphabet    for (int i = 0; i < 26; i++) {         // If frequency is not multiple        // of N        if (freq[i] % N != 0) {            System.out.print("No\n");            return;        }    }     // Divide frequency of each character    // with N    for (int i = 0; i < 26; i++)        freq[i] /= N;     // Store the count of minimum    // operations    int ans = 0;     for (int s = 0; s < N; s++) {         // Store frequencies of characters        // in the original String        int []vis = new int;         for (char c : S[s].toCharArray())            vis++;         // Get the count of extra characters        for (int i = 0; i < 26; i++) {            if (freq[i] > 0 && vis[i] > 0) {                ans += Math.abs(freq[i] - vis[i]);            }        }    }     System.out.print("Yes " +  ans +"\n");    return;} // Driver functionpublic static void main(String[] args){    int N = 3;    String S[] = { "aaa", "bbb", "ccc" };     solve(S, N);}} // This code is contributed by shikhasingrajput

Python3

 # python program for the above approach # Function to check if strings# can be formed equal or notdef solve(S, N):     # Vector to store the frequency    # of characters    freq = [0 for _ in range(26)]     # Traversing the array of strings    for i in range(0, N):         # Traversing characters of the        # string        for x in S[i]:             # Updating the frequency            freq[ord(x) - ord('a')] += 1     # Checking for each character of    # alphabet    for i in range(0, 26):         # If frequency is not multiple        # of N        if (freq[i] % N != 0):            print("No")            return     # Divide frequency of each character    # with N    for i in range(0, 26):        freq[i] //= N     # Store the count of minimum    # operations    ans = 0     for i in range(0, N):         # Store frequencies of characters        # in the original string        vis = [0 for _ in range(26)]        for c in S[i]:            vis[ord(c) - ord('a')] += 1         # Get the count of extra characters        for i in range(0, 26):            if (freq[i] > 0 and vis[i] > 0):                ans += abs(freq[i] - vis[i])     print(f"Yes {ans}")    return # Driver functionif __name__ == "__main__":     N = 3    S = ["aaa", "bbb", "ccc"]     solve(S, N) # This code is contributed by rakeshsahni

C#

 // C# program for the above approachusing System; class GFG{ // Function to check if Strings// can be formed equal or notstatic void solve(String []S, int N){         // List to store the frequency    // of characters    int []freq = new int;     // Traversing the array of Strings    for(int i = 0; i < N; i++)    {                 // Traversing characters of the        // String        foreach (int x in S[i].ToCharArray())        {                         // Updating the frequency            freq[x - 'a']++;        }    }     // Checking for each character of    // alphabet    for(int i = 0; i < 26; i++)    {                 // If frequency is not multiple        // of N        if (freq[i] % N != 0)        {            Console.Write("No\n");            return;        }    }     // Divide frequency of each character    // with N    for(int i = 0; i < 26; i++)        freq[i] /= N;     // Store the count of minimum    // operations    int ans = 0;     for(int s = 0; s < N; s++)    {                 // Store frequencies of characters        // in the original String        int []vis = new int;         foreach (char c in S[s].ToCharArray())            vis++;         // Get the count of extra characters        for(int i = 0; i < 26; i++)        {            if (freq[i] > 0 && vis[i] > 0)            {                ans += Math.Abs(freq[i] - vis[i]);            }        }    }     Console.Write("Yes " +  ans + "\n");    return;} // Driver codepublic static void Main(String[] args){    int N = 3;    String []S = { "aaa", "bbb", "ccc" };     solve(S, N);}} // This code is contributed by shikhasingrajput

Javascript


Output
Yes 6

Time Complexity: O(N*26)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up