🔗 Problem Link
LeetCode 1941 – Check if All Characters Have Equal Number of Occurrences
👉 https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/
Introduction
This is one of those problems that looks very simple at first glance — and it actually is — but it helps strengthen your understanding of frequency counting using HashMap.
The problem asks us to determine whether all characters in a string occur the same number of times.
No sliding window.
No binary search.
Just clean frequency logic.
But even simple problems help build strong foundations.
📌 Problem Understanding
A string is considered "good" if:
- Every character that appears in the string
- Appears the same number of times
If even one character has a different frequency → return false.
Example 1
Character counts:
- a → 2
- b → 2
- c → 2
All equal → ✔ true
Example 2
Character counts:
- a → 3
- b → 2
Not equal → ✘ false
🧠 Approach & Intuition
When I saw this problem, my thinking was:
- Count the frequency of every character.
- Compare all frequencies.
- If all are equal → return true.
The important part is choosing a reference frequency and comparing everything against it.
💻 Your Code
🔍 Step-by-Step Explanation
1️⃣ Initialize HashMap
This stores frequency of each character.
2️⃣ Choose Reference Character
You use the first character as a reference.
Then count how many times it appears while also building the frequency map.
3️⃣ Build Frequency Map
This line increases count for each character.
4️⃣ Compare Frequencies
If any frequency differs from the reference count → return false.
Otherwise → true.
⏱ Time and Space Complexity
Time Complexity: O(n)
- One loop to count frequencies
- One loop over at most 26 characters
Space Complexity: O(26) ≈ O(1)
Only lowercase English letters are allowed.
🔥 Small Optimization Idea
Your solution works perfectly.
However, we can simplify it slightly:
Instead of separately counting the reference frequency, we can:
- First build the entire frequency map.
- Take the frequency of the first character from the map.
- Compare all values with it.
Cleaner Version
Same logic — slightly cleaner structure.
🎯 Key Learning from This Problem
This problem reinforces:
- Frequency counting using HashMap
- Using a reference value for comparison
- Clean loop logic
- Early return for optimization
Even though it is an easy problem, it builds the base for harder problems like:
- Valid Anagram
- Group Anagrams
- First Unique Character
- Ransom Note
🏁 Final Thoughts
Problems like this are not about complexity.
They are about:
- Writing clean logic
- Handling frequency maps properly
- Thinking clearly about conditions
Mastering easy problems makes medium and hard problems much easier later.




