#1897
Redistribute Characters to Make All Strings Equal
EasyHash TableStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach focuses on counting character frequencies and checking if they can be evenly distributed among the strings without needing to simulate the redistribution. This is efficient and straightforward.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a frequency counter for all characters in the input strings.
- 2Step 2: Calculate the total number of characters and check if it can be evenly divided by the number of strings.
- 3Step 3: If it can be evenly divided, return true; otherwise, return false.
solution.py9 lines
1# Full working Python code
2from collections import Counter
3
4def makeEqual(words):
5 total_count = Counter()
6 for word in words:
7 total_count.update(word)
8 total_chars = sum(total_count.values())
9 return total_chars % len(words) == 0ℹ
Complexity note: The optimal solution runs in O(n) time because we only need to count characters and sum their frequencies, which is linear with respect to the total number of characters.
- 1Character distribution depends solely on frequency, not arrangement.
- 2If the total character count is not divisible by the number of strings, equal distribution is impossible.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.