Check if All Characters Have Equal Number of Occurrences — LeetCode 1941 Python Solution
- Problem
- #1941
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- s = "abacbc"
- Output
- true
- Explanation
- The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
Python solution
class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
return len(set(Counter(s).values())) == 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(|\Sigma|) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1941. Check if All Characters Have Equal Number of Occurrences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1941. Check if All Characters Have Equal Number of Occurrences?
- LeetCode 1941. Check if All Characters Have Equal Number of Occurrences is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1941. Check if All Characters Have Equal Number of Occurrences?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1941. Check if All Characters Have Equal Number of Occurrences?
- The Python solution on this page uses O(|\Sigma|) auxiliary space.
- What topics does LeetCode 1941. Check if All Characters Have Equal Number of Occurrences cover?
- LeetCode 1941. Check if All Characters Have Equal Number of Occurrences is tagged Hash Table, String and Counting on LeetCode.