Check if All Characters Have Equal Number of Occurrences — Easy Problem & Solution
A string is good if every character that appears in it appears the same number of times. Given s, return true if it is good.
- Difficulty: Easy
- Topics: Strings, Hash Table, Counting
- Asked at: TCS, Wipro, Zoho
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A string is good if every character that appears in it appears the same number of times.
Given s, return true if it is good.
Example 1
Input: s = "abacbc"
Output: true
Explanation: a, b and c each appear twice.
Example 2
Input: s = "aaabb"
Output: false
Explanation: a appears three times and b twice.
Example 3
Input: s = "codekairo"
Output: false
Explanation: o appears twice, everything else once.
Constraints
1 <= s.length <= 1000s consists of lowercase English letters.
How to solve Check if All Characters Have Equal Number of Occurrences
Tally the letters, then check that all non-zero tallies agree. The first non-zero tally becomes the reference value.
Approach
- Build
count[26]froms. - Scan the tallies, skipping zeros.
- Remember the first non-zero tally and reject as soon as another differs.
Why it works
The property is exactly 'the multiset of non-zero counts has one distinct value', and comparing every count against the first is the cheapest way to test that in one pass.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Including zero counts in the comparison rejects every string that does not use all 26 letters.
- Comparing
count[c]againstcount[0]rather than the first non-zero tally fails whenever'a'is absent.
Reference solution
Python
def areOccurrencesEqual(s: str) -> bool:
count = [0] * 26
for c in s:
count[ord(c) - 97] += 1
seen = [c for c in count if c > 0]
return all(c == seen[0] for c in seen)JavaScript
var areOccurrencesEqual = function(s) {
var count = [];
for (var t = 0; t < 26; t++) count.push(0);
for (var i = 0; i < s.length; i++) count[s.charCodeAt(i) - 97]++;
var first = -1;
for (var c = 0; c < 26; c++) {
if (count[c] === 0) continue;
if (first < 0) first = count[c];
else if (count[c] !== first) return false;
}
return true;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.