Sponsored
Sponsored
This approach involves counting the total number of each character across all strings. For each character, we need to check if its total count is divisible by the number of strings. If this is true for all characters, it implies that we can redistribute them to make all strings equal.
Time Complexity: O(n * m), where n is the number of strings and m is the average length of the string. Space Complexity: O(1), since we use only a fixed-size array of 26 integers.
1import java.util.*;
2
3public class Main {
4 public static boolean canMakeEqual(String[] words) {
5 int[] charCount = new int[26];
6 int n = words.length;
7
8 for (String word : words) {
9 for (char c : word.toCharArray()) {
10 charCount[c - 'a']++;
11 }
12 }
13
14 for (int count : charCount) {
15 if (count % n != 0) {
16 return false;
17 }
18 }
19 return true;
20 }
21
22 public static void main(String[] args) {
23 String[] words = {"abc", "aabc", "bc"};
24 System.out.println(canMakeEqual(words));
25 }
26}
In Java, we also utilize a charCount
array to keep track of character totals and check divisibility by the number of strings to decide if equal redistribution is feasible.
This approach optimizes the solution by adding an early return if a character's count is found to be non-divisible by the number of strings early in the process. This avoids unnecessary subsequent checks, thereby potentially improving performance.
Time Complexity: O(n * m), potentially improved due to early exit. Space Complexity: O(1).
1def canMakeEqualOptimized(words):
2 charCount = [
This Python variant implements an early return within the loop examining divisibility. If a non-divisible character count is found, the function stops immediately, improving performance.