Check if All Characters Have Equal Number of Occurrences
LeetCode 2053 | Difficulty: Easyβ
EasyProblem 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?
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.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 123 ms)β
| Metric | Value |
|---|---|
| Runtime | 123 ms |
| Memory | 36 MB |
| Date | 2022-01-22 |
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β
| Approach | Time | Space |
|---|---|---|
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- 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.