Check if Strings can be made equal by interchanging Characters
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 eqaul.
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 equalbool 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 codeint 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;} |
NO
Time Complexity: O(N * M) Where M is the maximum length of a string
Auxiliary Space: O(1).



.png)