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.
false.true.Where is the number of words and is the average length of each word.
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.
n, increment the flag.n, decrement the flag.n to keep values small.true if the flag equals 0, meaning all characters have counts divisible by n.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 == 0Where is the number of words and is the average length of each word.