1897. Redistribute Characters to Make All Strings Equal - Explanation
Description
You are given an array of strings words (0-indexed).
In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].
Return true if you can make every string in words equal using any number of operations, and false otherwise.
Example 1:
Input: words = ["abc","aabc","bc"]
Output: trueExplanation: 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: falseExplanation: It is impossible to make all the strings equal using the operation.
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]consists of lowercase English letters.
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Hash Maps (Dictionaries) - Used to count character frequencies across all strings
- Modular Arithmetic - Understanding divisibility to check if characters can be evenly distributed
1. Frequency Count (Hash Map)
Intuition
To make all strings equal, each character must be evenly distributed across all n strings. This means the total count of each character across all words must be divisible by n.
Think of it this way: if we have 6 occurrences of the letter 'a' and 3 words, each word can have exactly 2 'a's. But if we have 7 occurrences of 'a' and 3 words, there is no way to distribute them evenly.
The order of characters within each string does not matter since we can move characters freely. We only need to verify that redistribution is mathematically possible.
Algorithm
- Create a hash map to count the total frequency of each character across all words.
- Iterate through every character in every word, incrementing the count in the hash map.
- For each character in the hash map, check if its count is divisible by the number of words.
- If any character's count is not divisible by the number of words, return
false. - If all characters pass the divisibility check, return
true.
Time & Space Complexity
- Time complexity:
- Space complexity: since we have at most different characters.
Where is the number of words and is the average length of each word.
2. Frequency Count (Array)
Intuition
This approach uses the same divisibility principle but with a clever optimization. Instead of storing full counts and checking divisibility at the end, we track counts modulo n and use a flag counter to know whether all characters are evenly distributable.
When a character's frequency becomes divisible by n, it means that character can be perfectly distributed. We increment a flag when this happens and decrement it when a new character appears (since it starts at count 1, which is not divisible by n unless n = 1). At the end, if the flag is 0, all characters are evenly distributable.
Algorithm
- Create a frequency array of size 26 (for lowercase letters) and initialize a flag counter to 0.
- For each character encountered:
- If its current frequency is non-zero, increment it. If the new count is divisible by
n, increment the flag. - If its current frequency is zero, increment it to 1. If 1 is not divisible by
n, decrement the flag. - Take the frequency modulo
nto keep values small.
- If its current frequency is non-zero, increment it. If the new count is divisible by
- Return
trueif the flag equals 0, meaning all characters have counts divisible byn.
class Solution:
def makeEqual(self, words: List[str]) -> bool:
freq = [0] * 26
flag = 0
n = len(words)
for w in words:
for c in w:
i = ord(c) - ord('a')
if freq[i] != 0:
freq[i] += 1
if freq[i] % n == 0:
flag += 1
else:
freq[i] += 1
if freq[i] % n != 0:
flag -= 1
freq[i] %= n
return flag == 0Time & Space Complexity
- Time complexity:
- Space complexity: since we have at most different characters.
Where is the number of words and is the average length of each word.
Common Pitfalls
Forgetting to Check Divisibility by n
A common mistake is to only check if the total character count is even or to compare character counts between words directly. The key insight is that each character's total count must be divisible by n (the number of words), not just divisible by 2. For example, with 3 words and 4 occurrences of 'a', redistribution is impossible because 4 is not divisible by 3.
Assuming Words Must Already Be Similar
Some solutions incorrectly assume that redistribution is only possible if the words already share some characters or have similar lengths. In reality, the order and current arrangement of characters within each word is irrelevant. The only thing that matters is whether the global character counts allow for even distribution across all n words.
Sign in to join the discussion