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.
1using System;
2
3public class Solution {
4 public static bool CanMakeEqual(string[] words) {
5 int[] charCount = new int[26];
6 int n = words.Length;
7
8 foreach (string word in words) {
9 foreach (char c in word) {
10 charCount[c - 'a']++;
11 }
12 }
13
14 foreach (int count in charCount) {
15 if (count % n != 0) return false;
16 }
17 return true;
18 }
19
20 public static void Main() {
21 string[] words = {"abc", "aabc", "bc"};
22 Console.WriteLine(CanMakeEqual(words));
23 }
24}
The C# solution effectively repeats the frequency counting and checking steps, ensuring all characters can be equally distributed among the provided 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.