Skip to content

1941. Check if All Characters Have Equal Number of Occurrences 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  bool areOccurrencesEqual(string s) {
    vector<int> count(26);
    for (const char c : s)
      ++count[c - 'a'];
    return equalFreq(count, count[s[0] - 'a']);
  }

 private:
  bool equalFreq(const vector<int>& count, int theFreq) {
    return ranges::all_of(
        count, [theFreq](int freq) { return freq == 0 || freq == theFreq; });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public boolean areOccurrencesEqual(String s) {
    int[] count = new int[26];
    for (final char c : s.toCharArray())
      ++count[c - 'a'];
    return equalFreq(count, count[s.charAt(0) - 'a']);
  }

  private boolean equalFreq(int[] count, int theFreq) {
    return Arrays.stream(count).allMatch(freq -> freq == 0 || freq == theFreq);
  }
}
1
2
3
class Solution:
  def areOccurrencesEqual(self, s: str) -> bool:
    return len(set(collections.Counter(s).values())) == 1