We can easily keep track of character occurences using a dict
or a Counter
(from the collections
module). To determine the validity of the input string, we can create an additional dictionary from the frequencies of each character where the keys are the frequencies and the values are the counts of those frequencies, e.g., how many characters had a frequency of two.
If all characters have the same frequency, then the set of frequency count values will consists of a single number and the string is valid. If there are two different frequency counts (two keys in our dictionary), then the string is only valid given either of these two conditions:
The string can never be valid if there are more than two different frequency values (more than two keys in our “frequency count” dictionary).
from collections import Counter
def is_valid(s):
char_count = Counter(s)
freq_count = Counter(char_count.values())
if len(freq_count) == 1:
return 'YES'
elif len(freq_count) == 2:
if abs(list(freq_count.keys())[0] - list(freq_count.keys())[1]) == 1 and freq_count[max(freq_count.keys())] == 1:
return 'YES'
elif (1, 1) in freq_count.items():
return 'YES'
else:
return 'NO'
else:
return 'NO'
if __name__ == '__main__':
import sys
s = sys.stdin.readline()
print(is_valid(s))