Check if All Characters Have Equal Number of Occurrences

The problem involves determining if all characters in a string have the same frequency of occurrence. A simple way to approach this is to create a dictionary, where keys are the unique characters of the string, and values are their respective counts. Once we have this dictionary, we can check if all the counts are equal.

Python solution:

class Solution:
    def areOccurrencesEqual(self, s: str) -> bool:
        from collections import Counter
        counts = Counter(s)
        return len(set(counts.values())) == 1

In this code, we use Python’s collections.Counter to easily count the occurrences of each character in the string s. The result of Counter(s) is a dictionary where keys are unique characters from the string, and values are their respective counts.

The statement set(counts.values()) creates a set of all count values. Sets in Python can’t have duplicate elements, so if all counts were the same, the length of the set will be 1. The condition len(set(counts.values())) == 1 checks exactly this, so it will return True if all counts are the same and False otherwise.