Check if All Characters Have Equal Number of Occurrences

easy hash map string

Problem

Decide whether every character that appears in s appears the same number of times.

Inputs = "abacbc"
Outputtrue
a:2, b:2, c:2.

def are_occurrences_equal(s):
    from collections import Counter
    c = Counter(s)
    return len(set(c.values())) == 1
function areOccurrencesEqual(s) {
  const m = new Map();
  for (const c of s) m.set(c, (m.get(c) || 0) + 1);
  return new Set(m.values()).size === 1;
}
class Solution {
    public boolean areOccurrencesEqual(String s) {
        int[] c = new int[26];
        for (char ch : s.toCharArray()) c[ch - 'a']++;
        int first = 0;
        for (int x : c) if (x > 0) { first = x; break; }
        for (int x : c) if (x > 0 && x != first) return false;
        return true;
    }
}
bool areOccurrencesEqual(string s) {
    int c[26] = {0};
    for (char ch : s) c[ch - 'a']++;
    int first = 0;
    for (int x : c) if (x > 0) { first = x; break; }
    for (int x : c) if (x > 0 && x != first) return false;
    return true;
}
Time: O(n) Space: O(1)