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.
Less Spoiler:
Possible scenarios:
case1: aaabbbcccddd
case2.abbbcccddd
case3:aaaabbbcccdddd
Spoiler:
// case 1: uniqueFreqs == 1 means: All characters have the same frequency
// example: "aabbccdd" all appear twice. The only distinct frequency is 2.
// case 2: There are 2 distinct values and one of them is "1" and it occurs only once
// example: aaaabbbbc the occurance of 4 (a and b) is 2 and the occurance of 1 is(c) is one. Remove the only letter which appears once
// case 3: Frequencies differ by 1, and the higher frequency appears only once example: aaaabbbbccccc
Java with array Hashmap is also an option I guess.
publicstaticStringisValid(Strings){// Step 1: Count character frequenciesint[]freq=newint[26];for(charc:s.toCharArray()){freq[c-'a']++;}// Step 2: Find the maximum frequencyintmaxFreq=0;for(intf:freq){if(f>maxFreq){maxFreq=f;}}// Step 3: Count occurrences of each frequencyint[]freqCounts=newint[maxFreq+1];for(intf:freq){if(f>0){freqCounts[f]++;}}// Step 4: Analyze frequency countsintuniqueFreqs=0;// Count of unique(non zero) frequenciesbooleancanRemoveOne=false;// Whether we can remove one character to make it validfor(inti=1;i<freqCounts.length;i++){if(freqCounts[i]>0){uniqueFreqs++;// Check if we can remove one character to balance frequenciesif(i<freqCounts.length-1&&freqCounts[i+1]==1){canRemoveOne=true;}}}// case 1: uniqueFreqs == 1 means: All characters have the same frequency// example: "aabbccdd" all appear twice. The only distinct frequency is 2.// case 2: There are 2 distinct values and one of them is "1" and it occurs only once// example: aaaabbbbc the occurance of 4 (a and b) is 2 and the occurance of 1 is(c) is one. Remove the only letter which appears once// case 3: Frequencies differ by 1, and the higher frequency appears only once example: aaaabbbbccccc// Step 5: Return the result based on the casesif(uniqueFreqs==1||(uniqueFreqs==2&&(freqCounts[1]==1||canRemoveOne))){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 →
Less Spoiler: Possible scenarios: case1: aaabbbcccddd case2.abbbcccddd case3:aaaabbbcccdddd
Spoiler: // case 1: uniqueFreqs == 1 means: All characters have the same frequency // example: "aabbccdd" all appear twice. The only distinct frequency is 2. // case 2: There are 2 distinct values and one of them is "1" and it occurs only once // example: aaaabbbbc the occurance of 4 (a and b) is 2 and the occurance of 1 is(c) is one. Remove the only letter which appears once // case 3: Frequencies differ by 1, and the higher frequency appears only once example: aaaabbbbccccc
Java with array Hashmap is also an option I guess.