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
Character Frequency ValidationInput: "abacbc"Step 1: Scan and CountabacbcFrequency Map:a: 2b: 2c: 2Step 2: Extract Frequencies222All frequencies: [2, 2, 2]Step 3: Verify All EqualReference frequency: 2Check: 2 == 2 โœ“, 2 == 2 โœ“, 2 == 2 โœ“Step 4: ResultTRUEAll characters have equal frequency โ†’ String is good
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

n
2n
โœ“ Linear Growth
Space Complexity
O(k)

Hash table stores at most k distinct characters where k โ‰ค n

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 1000
  • s consists of lowercase English letters only
  • String is guaranteed to be non-empty
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
28.6K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen