CMD Guide
HomeDSACompany Practice

easy Redistribute Characters to Make All Strings Equal

Problem Statement

Given an array of strings words, return true if you can make all strings equal in words array by performing any number of swap operations. Otherwise, return false.

In one swap operation, you can pick any two indices i and j, and move any characters from words[i] to any position of the words[j].

Examples

Try it yourself

Try solving this question here:

🎯 STRICT STANDOUT — Redistribute Characters to Make All Strings Equal easy

0. Why / judgment (K3)

Family: Global frequency · divisibility by word count

Any character can move to any string freely (unlimited moves). Final equality of strings means every character’s global count must be divisible by number of words — so each word can receive the same multiset. No need to construct the strings.

1. Pattern + recognition + when-NOT (K12)

Pattern / template: Count freq[c] over all words; return all(freq[c] % len(words) == 0). Recognition: redistribute / free reassignment → modular counting, not per-string anagrams.

When-NOT: Not “each pair anagram”. Not graph matching. Not greedy placement simulation. If moves only between adjacent words or costed → different. If order inside string matters beyond multiset → still multisets determine equality here once equal.

2. Complexity derivation (K11)

Let N = total characters across words, k=|words|.
Count pass Θ(N); check 26 counters O(1) or O(Σ).
Space O(Σ) = O(1) for lowercase.

3. Edge hand-run (K13)

words=["aaa","bbb","ccc","abc"]: counts a=4,b=4,c=4; 4%4=0 → true.
["ab","bc","cd","de","ea"]: each letter 2; 2%5 ≠0 → false.
Single word → always true (x%1==0).
Empty strings: 0%k==0 → true if all empty.

4. Interviewer follow-ups & drills

Q1. Why % len(words)?
Model answer: Each final equal string must get freq/k of each char.

Q2. Do string lengths matter separately?
Model answer: Equal strings ⇒ equal lengths; divisibility of all counts implies total N % k == 0.

Q3. Mis-tag?
Model answer: Not LCS / not edit distance between pairs.

✅ Solution Redistribute Characters to Make All Strings Equal

Problem Statement

Given an array of strings words, return true if you can make all strings equal in words array by performing any number of swap operations. Otherwise, return false.

In one swap operation, you can pick any two indices i and j, and move any characters from words[i] to any position of the words[j].

Examples

  • Example 1:

    • Input: words = ["aaa","bbb","ccc", "abc"]
    • Expected Output: true
    • Justification: Each string has 3 characters of a single type, and the last string has all 3 characters. We can redistribute the characters to form a string like "abc" making the distribution equal.
  • Example 2:

    • Input: words = ["ab","bc","cd","de","ea"]
    • Expected Output: false
    • Justification: The characters cannot be redistributed to make all strings equal because all characters appear only twice, making equal distribution impossible.
  • Example 3:

    • Input: words = ["zzx","xzz","zxz"]
    • Expected Output: true
    • Justification: We can redistribute characters to have each string contain one "x" and two "z"s, like "zzx", "xzz", "zxz", maintaining equal distribution.

Solution

To solve this problem, we'll focus on counting the frequency of each character across all strings and then check if these frequencies can be divided evenly by the number of strings. This approach works because, for the characters to be distributable equally, the total occurrences of each character must be a multiple of the number of strings. This method is effective as it simplifies the problem to a straightforward mathematical check, avoiding the need for complex manipulations or redistributions of the characters.

Our strategy will involve two main steps: first, creating a comprehensive count of each character's appearances across all strings. This is achieved by iterating through each string and incrementing the count for each character. Second, we'll verify if each character's total count is divisible by the number of strings. If all characters pass this test, it implies an equal distribution is possible; otherwise, it is not. This method is chosen for its efficiency and simplicity, directly addressing the problem's core requirement without unnecessary complexity.

Step-by-step algorithm

  1. Initialize a Character Frequency Map: Create an empty map (or dictionary) to keep track of the frequency of each character across all the strings. The key will be the character, and the value will be the count of how many times that character appears.

  2. Count Character Frequencies: Iterate over each string in the input array. For each string, iterate over each character and update the character frequency map by increasing the count for each character.

  3. Check for Equal Distribution:

    • Calculate the number of strings in the input array. This will be used to check if a character can be evenly distributed.
    • Iterate over the values in the character frequency map. For each frequency value, check if it is divisible by the number of strings. If any frequency is not divisible, return false, indicating that an equal distribution is not possible.
    • If all frequencies are divisible by the number of strings, return true.

Algorithm Walkthrough

Input: ["aaa","bbb","ccc", "abc"]

  • Step 1: Initialize a character frequency map. It will be empty initially: {}.

  • Step 2: Count character frequencies.

    • For the first string "aaa", update the map: {'a': 3}.
    • For the second string "bbb", update the map: {'a': 3, 'b': 3}.
    • For the third string "ccc", update the map: {'a': 3, 'b': 3, 'c': 3}.
    • For the fourth string "abc", update the map: {'a': 4, 'b': 4, 'c': 4}.
  • Step 3: Check for equal distribution.

    • The number of strings is 4.
    • Check divisibility for each character frequency:
      • {'a': 4}: 4 % 4 == 0, so 'a' can be evenly distributed.
      • {'b': 4}: 4 % 4 == 0, so 'b' can be evenly distributed.
      • {'c': 4}: 4 % 4 == 0, so 'c' can be evenly distributed.
    • Since all characters can be evenly distributed, return true.
Image
Image

Code

java
import java.util.HashMap;
import java.util.Map;

public class Solution {
    public boolean makeEqual(String[] words) {
        Map<Character, Integer> charCount = new HashMap<>();
        // Counting frequency of each character in all strings
        for (String word : words) {
            for (char c : word.toCharArray()) {
                charCount.put(c, charCount.getOrDefault(c, 0) + 1);
            }
        }
        
        int numWords = words.length;
        // Checking if each character's frequency is divisible by the number of strings
        for (int count : charCount.values()) {
            if (count % numWords != 0) {
                return false;
            }
        }
        
        return true; // All characters are evenly distributable
    }
    
    public static void main(String[] args) {
        Solution solution = new Solution();
        // Testing with the example inputs
        System.out.println(solution.makeEqual(new String[]{"aaa","bbb","ccc","abc"})); // true
        System.out.println(solution.makeEqual(new String[]{"ab","bc","cd","de","ea"})); // false
        System.out.println(solution.makeEqual(new String[]{"zzx","xzz","zxz"})); // true
    }
}

Complexity Analysis

Time Complexity: The time complexity of the algorithm is , where N is the number of strings in the input array and M is the average length of these strings. This complexity arises because the algorithm iterates through each character of each string to count the frequency of characters.

Space Complexity: The space complexity of the algorithm is , where K is the number of unique characters across all strings. This space is required to store the frequency of each character in a hash map or dictionary. The maximum size of this map depends on the size of the character set used in the strings.

🎯 STRICT STANDOUT — Solution Redistribute Characters to Make All Strings Equal

0. Why / judgment (K3)

Family: Global frequency · divisibility

Proof sketch: necessity — equal strings each hold c_i of char c with sum = global, so global ≡ 0 (mod k). Sufficiency — give each word global/k of every char and any order; free moves realize that assignment.

1. Pattern + recognition + when-NOT (K12)

Pattern / template: Counter over all chars; verify modulo k.

When-NOT: Do not simulate swaps (exponential). Do not sort each word.

2. Complexity derivation (K11)

Θ(N) time, Θ(1) space for a–z.

3. Edge hand-run (K13)

Hand-run ["a","b"]: a:1,b:1; k=2; 1%2≠0 → false.
["ab","a"]: wait lengths differ final — a:2,b:1; k=2 → false.
["abc","cba","bca"]: each letter 3; 3%3=0 → true.

4. Interviewer follow-ups & drills

Q1. Sufficiency argument in one line?
Model answer: Assign each char evenly; moves unrestricted ⇒ realizable.

Q2. Uppercase?
Model answer: Extend alphabet size; same math.

Q3. k does not divide N?
Model answer: Some char fails; total also fails — catch either.

🧩 Pattern · Arrays

Recognize it: Scan once tracking what you need (running max/sum), or precompute a prefix-sum / hash → turn O(n²) into O(n).

▶ Visualize this problem (step it, predict each fork)
⛶ Open this problem debugger in explore mode
🤖 Don't fully get this? Learn it with Claude

Stuck on Redistribute Characters to Make All Strings Equal? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Redistribute Characters to Make All Strings Equal** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Redistribute Characters to Make All Strings Equal** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Redistribute Characters to Make All Strings Equal**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Redistribute Characters to Make All Strings Equal**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes