NeetCode #78LC-1897EasyArrays & Hashing
← Back to All Problems

#78 · #1897 · Redistribute Characters to Make All Strings Equal(重新分配字符使所有字符串都相等)

📌 Problem Statement & Constraints

Given an array of strings words, redistribute the characters so that all strings become equal (in any order). Return true if possible. Constraints: 1 <= words.length <= 1000, 1 <= words[i].length <= 100, all lowercase letters.

💡 Core Algorithmic Approaches

  1. If all strings must end up identical, they must all have the same length, and every character must be distributable evenly.
  2. Because redistribution is unrestricted, the only condition is that the total count of each character is divisible by the number of strings.
  3. Count all characters across all words, then verify total[ch] % n == 0 for every character.
  4. The common length is then total_characters / n, which is automatically consistent.

💻 Benchmark Python3 Implementation

class Solution:
    def makeEqual(self, words: List[str]) -> bool:
        from collections import Counter
        total = Counter("".join(words))
        n = len(words)
        return all(c % n == 0 for c in total.values())

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(total characters): one pass to count, plus a constant-size scan over the alphabet.
💾 Space Complexity
O(1): the counter holds at most 26 entries (the joined string is O(total characters), which can be avoided by counting incrementally).

⚠️ Interview Pitfalls & Follow-ups

  • Requiring the strings to already be equal: redistribution is unrestricted, so only the divisibility condition matters.
  • Checking only the lengths: equal lengths are necessary but far from sufficient; ["ab", "cd"] has equal lengths but cannot be made equal.
  • Forgetting that n divides every character count, not the total length: the total length is automatically divisible since each word has the same length when feasible, but the per-character condition is the real test.