Check if All Characters Have Equal Number of Occurrences

hash-table string counting

Description

Given a string s, return true if s is a good string, or false otherwise.

A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).

Example 1:
Input: s = "abacbc"
Output: true
Explanation: The characters 'a', 'b', and 'c' all appear 2 times. Since all characters have the same frequency, return true.

Example 2:
Input: s = "aaabb"
Output: false
Explanation: 'a' appears 3 times while 'b' appears 2 times. Since the frequencies are different, return false.

Example 3:
Input: s = "a"
Output: true
Explanation: Only 'a' appears, with frequency 1. A single character trivially satisfies the condition.

Constraints

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters

Complexity

Show Complexity
  • Time: O(n)
  • Space: O(1)

Hints

Show Hints
Pattern
Hash table for frequency counting
Approach
Build a frequency map of all characters, then check if all values in the map are equal
Complexity
Count frequencies in O(n), check uniqueness in O(26) = O(1)

Solutions

Show PY Solution
def solution(s: str) -> bool:
    m = {}

    for i in range(len(s)):
        if s[i] not in m:
            m[s[i]] = 0
        m[s[i]] += 1

    curr = -1
    for v in m.values():
        if curr == -1:
            curr = v
        if curr != v:
            return False

    return True