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++
|
Time Complexity: O(N * M) Where M is the maximum length of a string
Auxiliary Space: O(1).