LeetCode 1941. Check if All Characters Have Equal Number of Occurrences Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1941. Check if All Characters Have Equal Number of Occurrences

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.

Solutions

Solution 1: Counting

We use a hash table or an array of length 26 called cnt to record the number of occurrences of each character in the string s.

Next, we traverse each value in cnt and check if all non-zero values are equal.

The time complexity is O(n), and the space complexity is O(|Σ|). Here, n is the length of the string s, and Σ is the size of the character set. In this problem, the character set consists of lowercase English letters, so |Σ|=26.

PythonJavaC++GoTypeScriptPHP
class Solution: def areOccurrencesEqual(self, s: str) -> bool: return len(set(Counter(s).values())) == 1(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !