Check if All Characters Have Equal Number of Occurrences - Problem

Given a string s, return true if s is a good string, or false otherwise.

A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).

Input & Output

Example 1 — Good String
$ Input: s = "abacbc"
Output: true
💡 Note: Each character appears exactly 2 times: 'a' appears 2 times, 'b' appears 2 times, 'c' appears 2 times. All frequencies are equal.
Example 2 — Bad String
$ Input: s = "aaabb"
Output: false
💡 Note: Character 'a' appears 3 times but 'b' appears 2 times. The frequencies are not equal.
Example 3 — Single Character
$ Input: s = "c"
Output: true
💡 Note: Only one unique character 'c' appears 1 time. All characters have the same frequency (trivially true).

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters

Visualization

Tap to expand
Equal Character Occurrences Check INPUT String s = "abacbc" a b a c b c 0 1 2 3 4 5 Input Details: s = "abacbc" Length: 6 characters Goal: Check if all chars have equal frequency ALGORITHM STEPS 1 Create Hash Map Store char frequencies 2 Count Each Char Iterate through string Hash Map: 'a': 2 'b': 2 'c': 2 All values = 2 3 Get Unique Counts Extract all frequencies 4 Check Uniqueness Only 1 unique count? FINAL RESULT Frequency Analysis: 'a' 2 'b' 2 'c' 2 Same Output: true String is GOOD All characters appear exactly 2 times: OK Key Insight: Use a hash map to count character frequencies in O(n) time. Then check if all frequency values are identical. If there's only one unique frequency value, the string is "good". Using a Set on the frequency values makes comparison simple: Set size == 1 means all frequencies are equal. TutorialsPoint - Check if All Characters Have Equal Number of Occurrences | Hash Map Approach
Asked in
Amazon 15 Microsoft 12
28.4K Views
Medium Frequency
~10 min Avg. Time
856 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