Redistribute Characters to Make All Strings Equal

The idea here is to check whether each character in all the words can be equally distributed among the words. We can do this by counting the total occurrences of each character and then checking if each count is divisible by the number of words. If all counts are divisible, we return True, otherwise False.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def makeEqual(self, words: List[str]) -> bool:
        # Count the occurrences of each character in all the words
        counts = collections.Counter(''.join(words))

        # Number of words
        n = len(words)

        # Check if each count is divisible by the number of words
        for count in counts.values():
            if count % n != 0:
                return False

        return True

In this solution, we first count the occurrences of each character in all the words using Python’s built-in Counter class. This results in a dictionary-like object where keys are the characters and values are their counts. Then we get the number of words. We loop through each count and if we find a count that is not divisible by the number of words, we immediately return False. If we finish the loop without returning False, it means all counts are divisible by the number of words, so we return True.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def makeEqual(self, words: List[str]) -> bool:
        cnt = [0]*26
        for w in words:
            for ch in w:
                cnt[ord(ch) - ord('a')] += 1

        for c in cnt:
            if c % len(words) != 0:
                return False
        return True