Check Equal Character Occurrences
Given a string, return true if all characters that appear have the same frequency. Characters that do not appear are ignored. Uses a hash map to count frequencies, then checks if all frequency values are equal.
This is a simple hash map application that tests understanding of frequency counting and value comparison. An empty string or single-character string trivially returns true.
The problem is a straightforward frequency counting exercise that tests understanding of hash maps and value comparison. It filters out characters that do not appear, so only characters with at least one occurrence are considered in the frequency comparison.
Edge cases include empty strings (return true), single characters (return true), and strings where all characters happen to have the same frequency by coincidence. The hash map approach correctly handles all cases.
This problem tests the ability to count frequencies with a hash map and then compare the resulting values. The key insight is that characters not present are simply ignored, and the comparison only involves characters that appear at least once. An empty string vacuously satisfies the condition.
This problem reinforces hash map fundamentals and is a building block for more complex frequency analysis problems.
Example Input & Output
Single char.
Freq 3 and 2.
All freq 2.
Algorithm Flow

Solution Approach
Count frequencies with a hash map. Check if all frequency values are the same.
Time O(n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public boolean solution(String s) {
Map<Character,Integer> freq = new HashMap<>();
for (char ch : s.toCharArray()) freq.put(ch, freq.getOrDefault(ch, 0) + 1);
if (freq.isEmpty()) return true;
int first = freq.values().iterator().next();
for (int v : freq.values()) { if (v != first) return false; }
return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
