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.
1function canMakeEqual(words) {
2 const charCount = new Array(26).fill(0);
3 const n = words.length;
4
5 for (const word of words) {
6 for (const char of word) {
7 charCount[char.charCodeAt(0) - 97]++;
8 }
9 }
10
11 return charCount.every(count => count % n === 0);
12}
13
14console.log(canMakeEqual(["abc", "aabc", "bc"]));
In JavaScript, we build a frequency array, updating it via parsed character codes. We use the every
method to test divisibility conditions, aligning with the approach logic.
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.