Check if All Characters Have Equal Number of Occurrences
Problem
Decide whether every character that appears in s appears the same number of times.
s = "abacbc"truedef 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;
}
Explanation
We need to check whether every letter that shows up in the string appears the same number of times. The trick is: count each letter, then ask if all those counts are identical.
First we tally the letters into a frequency map with Counter(s). This gives us how many times each character occurs, for example {a: 2, b: 2, c: 2}.
Now the clever part: take just the count values and drop them into a set. A set throws away duplicates, so if all the counts are equal, the set ends up with exactly one distinct value. We just check len(set(c.values())) == 1.
Example: s = "abacbc" gives counts 2, 2, 2. The set of those is {2}, size 1, so the answer is true. If instead one letter appeared 3 times, the set would be {2, 3}, size 2, giving false.
We pass over the string once to count and once over the counts to compare, so it is fast and simple.