Check if All Characters Have Equal Number of Occurrences Problem
#1941
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1941.
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 <= 1000sconsists of lowercase English letters.
Solution
Approach: Counting
Count how many times each letter occurs in an array cnt of size 26. The string is good when all the non-zero counts are equal, so remember the first non-zero count and compare every other non-zero count with it.
Complexity: O(n) time and O(26) extra space, where n is the length of s.
from collections import Counter
class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
return len(set(Counter(s).values())) == 1