Given a string s
, determine if all characters in the string have the same number of occurrences.
s
?
True
if all characters in the string have the same number of occurrences; otherwise, return False
.s
and count the occurrences of each character using a dictionary.True
(indicating all characters have the same frequency). Otherwise, return False
.Time Complexity: (O(n)), where (n) is the length of the string s
. This is because we traverse the string once to count the characters and then perform operations on a fixed size set of frequencies.
Space Complexity: (O(1)) or (O(26)) considering the fixed number of lowercase English letters, which can be considered as constant space (O(1)).
def areOccurrencesEqual(s: str) -> bool:
# Dictionary to store the frequency of each character
freq_dict = {}
# Count the frequencies of each character
for char in s:
if char in freq_dict:
freq_dict[char] += 1
else:
freq_dict[char] = 1
# Set to store unique frequencies
freq_set = set(freq_dict.values())
# If there's only one unique frequency, return True
return len(freq_set) == 1
s = "abacbc"
True
s = "aaabb"
False
This approach ensures we efficiently check whether all characters in the string s
occur the same number of times.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?