Leetcode 1897. Redistribute Characters to Make All Strings Equal
You are given an array of strings words (each string consists of lowercase English letters).
You need to determine if you can redistribute the characters of words such that every string in the array becomes equal.
Return true if you can achieve this and false otherwise.
Input: words = [“abc”, “aabc”, “bc”] Output: true Explanation: The strings can be converted into “aabbcc” or “abcabc”.
Input: words = [“ab”, “a”] Output: false Explanation: There is no way to make all strings equal.
1 <= words.length <= 10001 <= words[i].length <= 100import java.util.*;
public class RedistributeCharacters {
public boolean canRedistribute(String[] words) {
// Total frequency map for all characters
Map<Character, Integer> frequencyMap = new HashMap<>();
// Counting frequency of each character in all strings
for (String word : words) {
for (char c : word.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
}
int numStrings = words.length;
// Check if we can redistribute characters
for (int count : frequencyMap.values()) {
if (count % numStrings != 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
RedistributeCharacters solution = new RedistributeCharacters();
String[] words1 = {"abc", "aabc", "bc"};
System.out.println(solution.canRedistribute(words1)); // Output: true
String[] words2 = {"ab", "a"};
System.out.println(solution.canRedistribute(words2)); // Output: false
}
}
Overall, the time complexity is O(n \times m), which is efficient given the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?