Redistribute Characters to Make All Strings Equal - Problem

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.

Input & Output

Example 1 — Even Distribution Possible
$ Input: words = ["abc","aabc","bc"]
Output: true
💡 Note: We have 3 'a's, 3 'b's, and 3 'c's total. Since we have 3 strings, each can get exactly 1 of each character. Final result could be ["abc", "abc", "abc"].
Example 2 — Uneven Character Count
$ Input: words = ["ab","a"]
Output: false
💡 Note: We have 2 'a's and 1 'b' but 2 strings. Each string should get 1 'a' and 0.5 'b', but we can't split characters.
Example 3 — Single Character Type
$ Input: words = ["a","aa","aaa"]
Output: true
💡 Note: Total of 6 'a's can be evenly distributed among 3 strings, giving 2 'a's per string: ["aa", "aa", "aa"].

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • words[i] consists of lowercase English letters only

Visualization

Tap to expand
Redistribute Characters to Make All Strings Equal INPUT words array: "abc" index 0 "aabc" index 1 "bc" index 2 All Characters: a b c a a b c b c ALGORITHM STEPS 1 Count Characters Count freq of each char 2 Get Total Strings n = 3 strings 3 Check Divisibility Each count % n == 0? 4 Return Result All divisible = true Character Frequency Table Char Count %3 'a' 3 0 OK 'b' 3 0 OK 'c' 3 0 OK FINAL RESULT After redistribution: "abc" "abc" "abc" = Output: true All strings can be made equal! Key Insight: For all strings to be equal, each character's total count must be divisible by the number of strings. We can freely move any character to any position, so only the total counts matter, not positions. TutorialsPoint - Redistribute Characters to Make All Strings Equal | Optimal Solution O(n) Time
Asked in
Amazon 15 Microsoft 12 Google 8
34.3K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen