< Back





1941. Check if All Characters Have Equal Number of Occurences

Given a string, check if all characters have the same frequency of occurences. This is where the
Counter class from the Python collections library comes in handy. We just provide the string to the
Counter class instantiation, which automagically counts the frequency of each character in the
string.

After this, we use the Counter.values() method to return a list of the frequency of each character in
the string. Finally, we declare this list as a set(), eliminating duplicate values. If the length of
the set is 1, we know that the frequency of the characters is the same.

The solution is as follows:


  from collections import Counter

  class Solution:
      def areOccurrencesEqual(self, s: str) -> bool:
          count = Counter(s)
          frequency = set(count.values())
          return len(frequency) == 1


_ Time Complexity:

  O(n) - We have to count the occurence of each character in the string.

_ Space Complexity:

  O(n) - We store the frequency of each character in the string in a Counter object.