Skip to main content

Check if All Characters Have Equal Number of Occurrences

LeetCode 2053 | Difficulty: Easy​

Easy

Problem Description​

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).

Example 1:

Input: s = "abacbc"
Output: true
Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.

Example 2:

Input: s = "aaabb"
Output: false
Explanation: The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.

Constraints:

- `1 <= s.length <= 1000`

- `s` consists of lowercase English letters.

Topics: Hash Table, String, Counting


Approach​

Hash Map​

Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?

When to use

Need fast lookups, counting frequencies, finding complements/pairs.

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 123 ms)​

MetricValue
Runtime123 ms
Memory36 MB
Date2022-01-22
Solution
public class Solution {
public bool AreOccurrencesEqual(string s) {
int[] freq = new int[26];
for(int i=0;i<s.Length;i++)
{
freq[s[i]-'a']++;
}
int current = freq[s[0]-'a'];
for(int i=0;i<26;i++)
{
if(freq[i]==0) continue;
if(freq[i]!= current) return false;
}

return true;
}
}

Complexity Analysis​

ApproachTimeSpace
Hash Map$O(n)$$O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Hash map gives O(1) lookup β€” think about what to use as key vs value.
  • LeetCode provides 2 hint(s) for this problem β€” try solving without them first.
πŸ’‘ Hints

Hint 1: Build a dictionary containing the frequency of each character appearing in s

Hint 2: Check if all values in the dictionary are the same.