#1941
Check if All Characters Have Equal Number of Occurrences
EasyHash TableStringCountingHash MapCounting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a hash map to count the occurrences of each character in a single pass, and then checks if all counts are the same. This is efficient and reduces the number of operations significantly.
⚙️
Algorithm
3 steps- 1Step 1: Create a hash map to store the frequency of each character.
- 2Step 2: Iterate through the string and populate the hash map with character counts.
- 3Step 3: Extract the frequency values from the hash map and check if they are all the same.
solution.py5 lines
1from collections import Counter
2
3def areOccurrencesEqual(s):
4 freq = Counter(s)
5 return len(set(freq.values())) == 1ℹ
Complexity note: The time complexity is O(n) because we traverse the string once to count characters and then check the counts, which is efficient. The space complexity is O(n) due to the storage of character frequencies.
- 1Using a hash map allows for efficient counting of character occurrences in a single pass.
- 2Checking if all values in a hash map are the same can be done using a set, simplifying the logic.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.