Skip to content

1897. Redistribute Characters to Make All Strings Equal 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  bool makeEqual(vector<string>& words) {
    vector<int> count(26);

    for (const string& word : words)
      for (const char c : word)
        ++count[c - 'a'];

    return ranges::all_of(count,
                          [&](const int c) { return c % words.size() == 0; });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public boolean makeEqual(String[] words) {
    int[] count = new int[26];

    for (final String word : words)
      for (final char c : word.toCharArray())
        ++count[c - 'a'];

    return Arrays.stream(count).allMatch(c -> c % words.length == 0);
  }
}
1
2
3
4
class Solution:
  def makeEqual(self, words: list[str]) -> bool:
    return all(c % len(words) == 0
               for c in collections.Counter(''.join(words)).values())