Check if All Characters Have Equal Number of Occurrences - Problem
You are given a string s and need to determine if it's a "good" string.
A string is considered good if every character that appears in the string has exactly the same frequency. In other words, all characters must occur the same number of times.
Examples:
"abacbc"is good because 'a', 'b', and 'c' each appear exactly 2 times"aaabb"is not good because 'a' appears 3 times while 'b' appears 2 times"aabbcc"is good because all characters appear exactly 2 times
Return true if the string is good, false otherwise.
Input & Output
example_1.py โ Python
$
Input:
s = "abacbc"
โบ
Output:
true
๐ก Note:
Characters 'a', 'b', and 'c' each appear exactly 2 times, so all have equal frequency.
example_2.py โ Python
$
Input:
s = "aaabb"
โบ
Output:
false
๐ก Note:
Character 'a' appears 3 times while 'b' appears 2 times. Since frequencies are different, return false.
example_3.py โ Python
$
Input:
s = "a"
โบ
Output:
true
๐ก Note:
Single character always has equal frequency (trivially true case).
Visualization
Tap to expand
Understanding the Visualization
1
Count Character Frequencies
Scan the string and build a frequency map: 'a'โ2, 'b'โ2, 'c'โ2
2
Extract All Frequency Values
Get all frequency counts from the map: [2, 2, 2]
3
Verify All Equal
Check if all frequencies are the same by comparing with the first frequency
4
Return Result
Return true if all frequencies are equal, false otherwise
Key Takeaway
๐ฏ Key Insight: Use a hash table to count frequencies in O(n) time, then verify all frequency values are identical. This is much more efficient than counting each character separately.
Time & Space Complexity
Time Complexity
O(n)
First pass through string O(n) + second pass through unique characters O(k) where k โค n
โ Linear Growth
Space Complexity
O(k)
Hash table stores at most k distinct characters where k โค n
โ Linear Space
Constraints
- 1 โค s.length โค 1000
- s consists of lowercase English letters only
- String is guaranteed to be non-empty
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code