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.
1#include <iostream>
2#include <vector>
3
4bool canMakeEqual(std::vector<std::string>& words) {
5 int charCount[26] = {0};
6 int n = words.size();
7
8 for (const std::string& word : words) {
9 for (char c : word) {
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
22int main() {
23 std::vector<std::string> words = {"abc", "aabc", "bc"};
24 std::cout << (canMakeEqual(words) ? "true" : "false") << std::endl;
25 return 0;
26}
The C++ solution follows the same logic as the C version. We maintain a charCount
array to accumulate character frequencies across all strings and verify if each can be evenly split among the strings.
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).
1import java.util.*;
2
3
The Java implementation here also leverages an early exit strategy, providing a performance gain when dealing with strings where early determination of impossibility can be made.