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.
defisValid(s):# Write your code herechar_freq:dict[str,int]={}freq_count:dict[int,int]={}forcharins:char_freq[char]=char_freq.get(char,0)+1forfreqinchar_freq.values():freq_count[freq]=freq_count.get(freq,0)+1# reject if more than 2 different frequencies (-1 in any cannot become uniform)iflen(freq_count.keys())>2:return"NO"# accept if all frequencies are the same / uniformiflen(freq_count.keys())==1:return"YES"freqs:list[int]=list(sorted(freq_count.keys()))big_freq=freqs[1]small_freq=freqs[0]# edge case for smaller freq is single charifsmall_freq==1andfreq_count[small_freq]==1:return"YES"# when there is only 1 character type with freq = big_freq, # and removing 1 of that char will make the freq_count uniformiffreq_count[big_freq]==1andbig_freq==small_freq+1:return"YES"return"NO"
Java 8 solution:
publicstaticStringisValid(Strings){// Write your code hereMap<Character,Long>charFreq=s.codePoints().mapToObj(x->(char)x).collect(Collectors.groupingBy(x->x,Collectors.counting()));Map<Long,Long>freqCount=charFreq.values().stream().collect(Collectors.groupingBy(x->x,Collectors.counting()));intkeySetSize=freqCount.size();// accept if all frequencies are the same / uniformif(keySetSize<2){return"YES";}// reject if more than 2 different frequencies (-1 in any cannot become uniform)if(keySetSize>2){return"NO";}Long[]freqs=freqCount.keySet().toArray(newLong[0]);intbigFreqIndex=freqs[1]>freqs[0]?1:0;longsmallFreq=freqs[1-bigFreqIndex];longbigFreq=freqs[bigFreqIndex];// edge case for smaller freq is single charif(smallFreq==1&&freqCount.get(smallFreq)==1){return"YES";}// when there is only 1 character type with freq = big_freq, // and removing 1 of that char will make the freq_count uniformif(bigFreq==smallFreq+1&&freqCount.get(bigFreq)==1l){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 →
Python 3 solution:
Java 8 solution: