Open In App

Check if Strings can be made equal by interchanging Characters

Last Updated : 19 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of N strings, the task is to find if it is possible to make all the strings equal by performing the following operations:

  • Remove a character from ith string and insert it in an arbitrary position in jth string. (i and j can be the same)
  • You may perform this operation any number of times.

Examples:

Input: N = 2, S[] = {“caa”, “cbb”}
Output: YES 
Explanation: It is possible to exchange the ‘a’ of first string with ‘b’ in the second string to make both strings equal.
The strings can be made “cab”and “cab” or “cba” and “cba”.

Input: N = 3, S[] = {“cba”, “cba”, “cbb”} 
Output: NO
Explanation: It is impossible to make all strings equal.

 

Approach: The idea to solve the problem is as follows:

Due to the operations, any string can be arranged in any way. So to make the strings equal all the strings should have all the characters equal number of times. 
So they can be made equal if the frequency of each character in all the strings must be a multiple of N.

Follow the steps mentioned below to implement the problem:

  • Traverse through the array of strings and for each string do the following:
    • Traverse through that string.
    • Count the frequency of each character.
  • If the frequencies of all the characters of all the strings are multiple of N then only they can be made equal.
  • Otherwise, return that it is impossible.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach:
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if all the strings can be made equal
bool sameString(int N, string s[])
{
    // Vector of 26 to store the frequency
    // of each alphabet(characters).
    vector<int> cnt(26);
 
    for (int i = 0; i < N; ++i) {
        for (char ch : s[i]) {
 
            // Incrementing the frequency of
            // alphabet (subtracting and
            // finding the index, then
            // incrementing index by one.)
            ++cnt[ch - 'a'];
        }
    }
 
    bool ans = true;
    for (int i = 0; i < 26; ++i) {
 
        // Checking if divisible by N or not
        if (cnt[i] % N != 0) {
 
            // If not divisible at any time,
            // then its not possible to
            // divide equally.
            ans = false;
            break;
        }
    }
 
    // Return the final result to print
    // yes or no.
    return ans;
}
 
// Drivers code
int main()
{
 
    // Number of strings in the given input.
    int N = 3;
    string S[] = { "cba", "cba", "cbb" };
    bool ans;
 
    // Function call
    ans = sameString(N, S);
    cout << (ans ? "YES" : "NO");
    return 0;
}


Java




// Java code to implement the approach:
import java.util.*;
 
class GFG{
 
// Function to check if all the Strings can be made equal
static boolean sameString(int N, String s[])
{
    // Vector of 26 to store the frequency
    // of each alphabet(characters).
    int[] cnt = new int[26];
 
    for (int i = 0; i < N; ++i) {
        String st = s[i];
        for (int j = 0;j<st.length();j++) {
 
            // Incrementing the frequency of
            // alphabet (subtracting and
            // finding the index, then
            // incrementing index by one.)
            ++cnt[st.charAt(j) - 'a'];
        }
    }
 
    boolean ans = true;
    for (int i = 0; i < 26; ++i) {
 
        // Checking if divisible by N or not
        if (cnt[i] % N != 0) {
 
            // If not divisible at any time,
            // then its not possible to
            // divide equally.
            ans = false;
            break;
        }
    }
 
    // Return the final result to print
    // yes or no.
    return ans;
}
 
// Drivers code
public static void main(String[] args)
{
 
    // Number of Strings in the given input.
    int N = 3;
    String S[] = { "cba", "cba", "cbb" };
    boolean ans;
 
    // Function call
    ans = sameString(N, S);
    System.out.print((ans ? "YES" : "NO"));
}
}
 
// This code is contributed by shikhasingrajput


Python3




# Python3 code to implement the approach:
 
# Function to check if all the strings can be made equal
def sameString(N, s) :
 
    # Vector of 26 to store the frequency
    # of each alphabet(characters).
    cnt = [0]*26;
 
    for i in range(N):
        for ch in s[i] :
 
            # Incrementing the frequency of
            # alphabet (subtracting and
            # finding the index, then
            # incrementing index by one.)
            cnt[ord(ch) - ord('a')]  += 1;
 
 
    ans = True;
    for i in range(26) :
 
        # Checking if divisible by N or not
        if (cnt[i] % N != 0) :
 
            # If not divisible at any time,
            # then its not possible to
            # divide equally.
            ans = False;
            break;
 
    # Return the final result to print
    # yes or no.
    return ans;
 
# Drivers code
if __name__ == "__main__" :
 
    # Number of strings in the given input.
    N = 3;
    S = [ "cba", "cba", "cbb" ];
     
    # Function call
    ans = sameString(N, S);
    if ans:
        print("YES")
    else:
        print("NO")
         
    # This Code is contributed by AnkThon


C#




// C# code to implement the above approach
using System;
 
public class GFG {
 
  // Function to check if all the Strings can be made
  // equal
  static bool sameString(int N, string[] s)
  {
    // Vector of 26 to store the frequency
    // of each alphabet(characters).
    int[] cnt = new int[26];
 
    for (int i = 0; i < N; i++) {
      String st = s[i];
      for (int j = 0; j < st.Length; j++) {
        // Incrementing the frequency of
        // alphabet (subtracting and
        // finding the index, then
        // incrementing index by one.)
        ++cnt[st[j] - 'a'];
      }
    }
    bool ans = true;
    for (int i = 0; i < 26; i++) {
      // Checking if divisible by N or not
      if (cnt[i] % N != 0) {
        // If not divisible at any time,
        // then its not possible to
        // divide equally.
        ans = false;
        break;
      }
    }
    // Return the final result to print
    // yes or no.
    return ans;
  }
 
  static public void Main()
  {
    // Code
 
    // Number of Strings in the given input.
    int N = 3;
    string[] S = new string[3] { "cba", "cba", "cbb" };
    bool ans;
 
    // Function call
    ans = sameString(N, S);
    Console.WriteLine((ans ? "YES" : "NO"));
  }
}
 
// This code is contributed by lokesh (lokeshmvs21).


Javascript




<script>
    // JavaScript code to implement the approach:
 
 
    // Function to check if all the strings can be made equal
    const sameString = (N, s) => {
        // Vector of 26 to store the frequency
        // of each alphabet(characters).
        let cnt = new Array(26).fill(0);
 
        for (let i = 0; i < N; ++i) {
            for (let ch in s[i]) {
 
                // Incrementing the frequency of
                // alphabet (subtracting and
                // finding the index, then
                // incrementing index by one.)
                ++cnt[s[i].charCodeAt(ch) - 'a'.charCodeAt(0)];
            }
        }
 
        let ans = true;
        for (let i = 0; i < 26; ++i) {
 
            // Checking if divisible by N or not
            if (cnt[i] % N != 0) {
 
                // If not divisible at any time,
                // then its not possible to
                // divide equally.
                ans = false;
                break;
            }
        }
 
        // Return the final result to print
        // yes or no.
        return ans;
    }
 
    // Drivers code
 
    // Number of strings in the given input.
    let N = 3;
    let S = ["cba", "cba", "cbb"];
    let ans;
 
    // Function call
    ans = sameString(N, S);
    if (ans) document.write("YES");
    else document.write("NO");
 
    // This code is contributed by rakeshsahni
 
</script>


Output

NO

Time Complexity: O(N * M) Where M is the maximum length of a string
Auxiliary Space: O(1).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads