Check if All Characters Have Equal Number of Occurrences (LeetCode 1941): Solution and Explanation
Given a lowercase string, decide whether every character that appears in it appears the same number of times.
Intuition
The question is only about how often each letter appears, not where. So the first step is to turn the string into 26 counters.
Once the counters are filled, the string is good when all the non-zero counters are equal. Any letter that appears can serve as the reference, and s[0] is guaranteed to appear, so its count is a safe target.
Approach: Count letters, compare to one target
- Create an array
countof 26 zeros. - For each character c, increment
count[c - 'a']. - Set
target = count[s[0] - 'a']. - For every counter v: if v is non-zero and differs from
target, returnfalse. - Otherwise return
true.
Step-by-step example
s = "abacbc"
- Tally the six characters: a = 2, b = 2, c = 2, every other letter 0.
- s[0] is 'a', so target = 2.
- Bucket a holds 2, bucket b holds 2, bucket c holds 2. Empty buckets are skipped.
- No bucket differs from the target, so the answer is true.
Code: Python, Java, C++
1class Solution:
2 def areOccurrencesEqual(self, s: str) -> bool:
3 count = [0] * 26
4 for c in s:
5 count[ord(c) - ord('a')] += 1
6 target = count[ord(s[0]) - ord('a')]
7 for v in count:
8 if v != 0 and v != target:
9 return False
10 return True1class Solution {
2 public boolean areOccurrencesEqual(String s) {
3 int[] count = new int[26];
4 for (char c : s.toCharArray()) {
5 count[c - 'a']++;
6 }
7 int target = count[s.charAt(0) - 'a'];
8 for (int v : count) {
9 if (v != 0 && v != target) {
10 return false;
11 }
12 }
13 return true;
14 }
15}1class Solution {
2public:
3 bool areOccurrencesEqual(string s) {
4 vector<int> count(26, 0);
5 for (char c : s) {
6 count[c - 'a']++;
7 }
8 int target = count[s[0] - 'a'];
9 for (int v : count) {
10 if (v != 0 && v != target) {
11 return false;
12 }
13 }
14 return true;
15 }
16};Time and space complexity
O(n)
One pass over the string to count, plus a fixed pass over 26 counters.
O(1)
The counter array always has 26 slots, no matter how long the string is.
Other approaches
Set of counts (time O(n), space O(1))
Build a frequency map and check that the set of its values has size 1, for example len(set(Counter(s).values())) == 1 in Python. Short, with the same complexity.
Sort and measure runs (time O(n log n), space O(n))
Sort the characters, then compare the lengths of the runs of equal letters. It works but costs O(n log n) for no benefit.
Common mistakes
- Comparing zero counters with the target. Letters that never appear must be skipped.
- Taking the target from count[0] (the letter 'a'), which is zero when 'a' does not appear.
- Using the number of distinct letters or the string length alone; "aab" and "abb" have the same length as "abc" but different answers.
Frequently asked questions
Why use s[0] for the target?
Any letter that appears works, and s[0] is the easiest one that is guaranteed to appear because the string has at least one character.
Is a string with a single distinct letter good?
Yes. There is only one non-zero count, so all counts are trivially equal.
Does the order of the characters matter?
No. Only the counts matter, which is why the solution never looks at positions after the tally.