You are given a string word
. In one operation, you can choose any character of the string and remove it. You need to determine if it’s possible to remove exactly one character so that the frequency of each distinct character in the resulting string becomes the same.
Return true
if it’s possible, otherwise return false
.
word
?
word
contain any characters other than lowercase English letters?
word
consists only of lowercase English letters.word
is of length 1?
false
.from collections import Counter
def equalFrequency(word: str) -> bool:
# Counting frequency of each character
freq = Counter(word)
# Counting the frequency of these frequencies
freq_of_freq = Counter(freq.values())
if len(freq_of_freq) == 1:
# All characters have the same frequency
return True
if len(freq_of_freq) == 2:
# Extract the two frequencies and their counts
(freq1, count1), (freq2, count2) = freq_of_freq.items()
# Determine which is the higher frequency
if freq1 > freq2:
freq1, freq2 = freq2, freq1
count1, count2 = count2, count1
# Check if we can match frequencies by removing one character
if (freq2 == freq1 + 1 and count2 == 1) or (freq1 == 1 and count1 == 1):
return True
return False
With this approach, the solution is efficient and accommodates the constraints provided by the problem, ensuring that we can handle the maximum input size effectively.
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?