Code Logo

Check Equal Character Occurrences

Published at23 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
"a"
Output
true
Explanation

Single char.

Example 2
Input
"aaabb"
Output
false
Explanation

Freq 3 and 2.

Example 3
Input
"abacbc"
Output
true
Explanation

All freq 2.

Algorithm Flow

Recommendation Algorithm Flow for Check Equal Character Occurrences
Recommendation Algorithm Flow for Check Equal Character Occurrences

Solution Approach

Count frequencies with a hash map. Check if all frequency values are the same.

function solution(s) {
  var freq = {};
  for (var i = 0; i < s.length; i++) freq[s[i]] = (freq[s[i]] || 0) + 1;
  var vals = Object.values(freq);
  for (var i = 1; i < vals.length; i++) { if (vals[i] !== vals[0]) return false; }
  return true;
}

Time O(n), Space O(1).

Best Answers

java
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;
    }
}