We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if All Characters Have Equal Number of Occurrences

Number: 2053

Difficulty: Easy

Paid? No

Companies: Bloomberg, Bolt


Problem Description

Given a string s, determine whether it is a good string. A string is considered good if every character in the string has the same number of occurrences.


Key Insights

  • Use a hash table (or dictionary) to count the occurrence of each character.
  • After constructing the frequency map, verify if all values (counts) are identical.
  • Utilize a set to check the uniqueness of the frequency values; if the set size is 1, all characters occur equally.

Space and Time Complexity

Time Complexity: O(n) where n is the length of the string, since we traverse the string once to count the characters. Space Complexity: O(1) because the number of distinct characters is limited to 26 (lowercase English letters).


Solution

The solution involves iterating through the string, counting the frequency of each character using a hash table (or map). Once the counting is complete, we check if all frequency values are equal by converting them into a set. If the set's size is 1, it means all characters appear the same number of times. This is a direct and efficient O(n) solution in both time and space.


Code Solutions

# Function to check if all characters in the string have equal frequency
def are_occurrences_equal(s: str) -> bool:
    # Create a dictionary to count the occurrences of each character
    char_count = {}
    for char in s:
        # Increase the count for the current character
        char_count[char] = char_count.get(char, 0) + 1
    
    # Get all frequency values and check if they are all identical
    # Convert the list of counts to a set and verify it has only one unique value
    return len(set(char_count.values())) == 1

# Example usage:
s = "abacbc"
print(are_occurrences_equal(s))  # Should print True
← Back to All Questions