DEV Community

pythonic_solutions
pythonic_solutions

Posted on

3 1 1 1

Check if All Characters Have Equal Number of Occurrences

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.

class Solution:
    def areOccurrencesEqual(self, s: str) -> bool:
        from collections import Counter

        freq = Counter(s)
        values = set(freq.values())
        return len(values) == 1

Enter fullscreen mode Exit fullscreen mode

✅ Example 1: s = "abacbc"

freq = Counter(s) # {'a': 2, 'b': 2, 'c': 2}
freq.values() # dict_values([2, 2, 2])
set(freq.values()) # {2}
len(set(freq.values())) # 1 → True ✅
✔️ All characters occur 2 times → set has just one unique value (2)

❌ Example 2: s = "aaabb"

freq = Counter(s) # {'a': 3, 'b': 2}
freq.values() # dict_values([3, 2])
set(freq.values()) # {2, 3}
len(set(freq.values())) # 2 → False ❌
✖️ Frequencies differ (3 and 2) → set has two values → return False

✅ Example 3: s = "xyz"

freq = Counter(s) # {'x': 1, 'y': 1, 'z': 1}
freq.values() # dict_values([1, 1, 1])
set(freq.values()) # {1}
len(set(freq.values())) # 1 → True ✅
✔️ Each character occurs once → return True

❌ Example 4: s = "aaabbbcc"

freq = Counter(s) # {'a': 3, 'b': 3, 'c': 2}
freq.values() # dict_values([3, 3, 2])
set(freq.values()) # {2, 3}
len(set(freq.values())) # 2 → False ❌
✖️ Different counts → return False

✅ Example 5: s = "a"

freq = Counter(s) # {'a': 1}
freq.values() # dict_values([1])
set(freq.values()) # {1}
len(set(freq.values())) # 1 → True ✅
✔️ Only one character → always valid → return True

✅ Time Complexity:
Counter(s):

This goes through the entire string s once to count frequencies.

Time: O(n) where n is the length of the string.

freq.values():

Extracts the frequency values, which is proportional to the number of unique characters.

Worst case (e.g., all characters different): O(n)

set(freq.values()):

Building a set from up to n frequency values.

Time: O(k) where k is the number of unique characters (bounded by 26 if only lowercase letters).

len(values) == 1:

Constant time: O(1)

🔹 Total Time Complexity: O(n)

✅ Space Complexity:
freq (Counter):

Stores counts of each unique character.

Space: O(k) where k is the number of unique characters.

values (Set):

Stores unique frequencies.

Space: O(k) again.

🔹 Total Space Complexity: O(k)
Where k ≤ 26 if the input string contains only lowercase English letters.

Final Answer:
Time Complexity: O(n)

Space Complexity: O(k) (usually O(1) if alphabet is fixed)

DevCycle image

Ship Faster, Stay Flexible.

DevCycle is the first feature flag platform with OpenFeature built-in to every open source SDK, designed to help developers ship faster while avoiding vendor-lock in.

Start shipping

Top comments (1)

Collapse
 
csm18 profile image
csm

good explanation!

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Explore this practical breakdown on DEV’s open platform, where developers from every background come together to push boundaries. No matter your experience, your viewpoint enriches the conversation.

Dropping a simple “thank you” or question in the comments goes a long way in supporting authors—your feedback helps ideas evolve.

At DEV, shared discovery drives progress and builds lasting bonds. If this post resonated, a quick nod of appreciation can make all the difference.

Okay