Redistribute Characters to Make All Strings Equal

Updated on 14 July, 2025
Redistribute Characters to Make All Strings Equal header image

Problem Statement

In the provided scenario, an array of string elements, referred to as words, is given. Each element in this array is a string of non-empty lowercase English letters. The task allows for a specific operation where you can select two distinct strings at indexes i and j within the array. During this operation, you can relocate any single character from words[i] and insert it at any position in words[j]. The main goal of the task is to determine whether it's feasible, through any number of such operations, to modify the array such that all strings within it become identical. If this can be achieved, the function should return true; otherwise, it should return false.

Examples

Example 1

Input:

words = ["abc","aabc","bc"]

Output:

true

Explanation:

Move the first 'a' in `words[1] to the front of words[2],
to make` `words[1]` = "abc" and words[2] = "abc".
All the strings are now equal to "abc", so return `true`.

Example 2

Input:

words = ["ab","a"]

Output:

false

Explanation:

It is impossible to make all the strings equal using the operation.

Constraints

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of lowercase English letters.

Approach and Intuition

In order to determine whether all strings in the array can be made identical through the permitted operations, the approach fundamentally focuses on the distribution and frequency of characters across all the strings. Here is a breakdown of the approach:

  1. Character Frequency Count: Count the frequency of each character across all the strings combined. This gives a clear picture of the total availability of each character.
  2. Uniform Distribution Check: To make all strings in the list identical using the allowed operations, each character present in the combined frequency count must have enough copies to be distributed evenly across all strings.
    • For example, if there are 50 characters in total across 10 strings, each resulting string (after all operations) should ideally have 5 characters.
  3. Character Permutation Possibility: If the total number of occurrences of each character is divisible evenly by the number of strings, the operations can potentially rearrange them to make all strings identical.

Let's consider the examples to see this:

  • Example 1: words = ["abc", "aabc", "bc"]
    • All characters from all strings can be rearranged such that each string becomes "abc" by moving characters between the strings. Here, the total character count and distribution allow a permutation where each string can be rearranged to become "abc".
  • Example 2: words = ["ab", "a"]
    • Here, it's impossible to perform operations to achieve identical strings due to the constraints in the length of the strings and unavailability of sufficient characters.

In essence, by analyzing the overall frequency and possibility to distribute this frequency uniformly across all strings, you can determine the feasibility of making all strings identical through the described operations.

Solutions

  • C++
cpp
class Solution {
public:
    bool canBeEqual(vector<string>& wordsList) {
        vector<int> charCounts(26, 0);
        for (string current : wordsList) {
            for (char letter : current) {
                charCounts[letter - 'a']++;
            }
        }
    
        int totalWords = wordsList.size();
        for (int count : charCounts) {
            if (count % totalWords != 0) {
                return false;
            }
        }
            
        return true;
    }
};

The provided C++ solution aims to determine if it is possible to redistribute the characters across a list of strings (wordsList) so that all strings can be made equal. This means each character's total occurrence in all strings must be divisible evenly across the strings. The approach implemented consists of the following steps:

  1. A vector charCounts initialized to store counts of each of the 26 lowercase English letters.
  2. Iterate over each string in wordsList and for every character in a string, increment its corresponding count in charCounts.
  3. After counting, the total number of words totalWords is recorded.
  4. The solution then checks if each count in charCounts is divisible by totalWords. If any count is not divisible, it means it's impossible to redistribute characters evenly, and the function returns false.
  5. If all counts are divisible by totalWords, the function returns true, indicating redistribution is possible.

The coding techniques involve:

  • Array operations to ensure efficient count management.
  • Modulo operation to check divisibility, crucial for verifying the possibility of even distribution of characters.

This solution utilizes direct index manipulation for efficiency, operating with a complexity that is linear to the total number of characters in all strings combined.

  • Java
java
class Solution {
    public boolean canEqualize(String[] inputWords) {
        int[] letterCounts = new int[26];
        for (String singleWord : inputWords) {
            for (char character : singleWord.toCharArray()) {
                letterCounts[character - 'a']++;
            }
        }
    
        int totalWords = inputWords.length;
        for (int countValue : letterCounts) {
            if (countValue % totalWords != 0) {
                return false;
            }
        }
    
        return true;
    }
}

The provided Java solution focuses on determining whether the characters in an array of strings can be redistributed such that each string becomes equal when rearranged. The approach used in this solution involves counting the occurrences of each character across all strings and checking if these counts are divisible by the number of strings, indicating that an equal redistribution is possible. Here's how the code achieves this:

  • Initializes an array letterCounts to store the count of each character (totaling 26 for the English alphabet).
  • Iterates through each string in the inputWords array, and further iterates through each character in these strings to populate the letterCounts array.
  • After counting, the method checks if each character count is divisible by the number of strings (totalWords). If all counts are divisible, it returns true, indicating that redistribution is possible. If it finds any count that isn't divisible, it returns false.

This method effectively checks the possibility of an equal redistribution of characters, ensuring that if redistribution is possible, each string can be rearranged to match every other string in the array.

  • Python
python
class Solution:
    def canMakeEqual(self, input_words: List[str]) -> bool:
        letter_counts = [0] * 26
        for each_word in input_words:
            for char in each_word:
                letter_counts[ord(char) - ord('a')] += 1
            
        total_words = len(input_words)
        for count in letter_counts:
            if count % total_words != 0:
                return False
    
        return True

This Python 3 solution solves the problem of determining if it's possible to redistribute characters across input words such that all words can be made equal. The implementation uses the following approach:

  1. Initialize a list letter_counts of size 26 to zero, which corresponds to the counts of each alphabet letter.
  2. Iterate over each word in the provided input_words list.
  3. For each character in a word, increment the corresponding index in letter_counts by converting the character to its alphabetical index.
  4. Calculate total_words as the length of the input_words list.
  5. Check if each count in letter_counts is divisible by total_words. If any count is not divisible, return False.
  6. If all counts are divisible, return True.

This method effectively checks the feasibility of making all input words equal by redistributing the characters among them, ensuring that the distribution is even.

Comments

No comments yet.