We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
If the frequency of the characters is all the same, then return Yes.
Or if there's only 2 types of numbers representing the frequency of characters, and if by removing one character, all of them have the same frequency, return Yes. This can be represented in two ways:
1. n n n ... n 1, where removing the char with frequency 1 restores our condition, or
2. n n n ... n n+1 where removing the char with frequency n+1 restores the condition required.
Anything else gives us No.
Python3:
char_dict = {}
for i in s:
if i in char_dict:
char_dict[i] += 1
else:
char_dict[i] = 1
char_freq_list = list(char_dict.values())
print(char_freq_list)
freq_set = set(char_freq_list)
if len(freq_set) == 1:
return 'YES'
if len(freq_set) == 2:
if char_freq_list.count(max(freq_set)) == 1 and max(freq_set)-min(freq_set) == 1:
return 'YES'
if char_freq_list.count(min(freq_set)) == 1 and min(freq_set) == 1:
return 'YES'
return 'NO'
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and the Valid String
You are viewing a single comment's thread. Return to all comments →
If the frequency of the characters is all the same, then return Yes.
Or if there's only 2 types of numbers representing the frequency of characters, and if by removing one character, all of them have the same frequency, return Yes. This can be represented in two ways:
1. n n n ... n 1, where removing the char with frequency 1 restores our condition, or 2. n n n ... n n+1 where removing the char with frequency n+1 restores the condition required.
Anything else gives us No.
Python3: