Sort Characters By Frequency — LeetCode May Challenge Day 22

iAwale
1 min readMay 23, 2020

In today’s challenge, we need to sort a given String according to the frequencies of each character present in descending order.

addfffg -> fffddag or fffddga

We first calculate the frequency of each character(a-z and A-Z) in the String and put it in our HashMap.

Then, we sort the HashMap according to its values(frequency). Then we traverse through the sorted list while generating the String(repeating each character according to its frequency in the original String). The String generated is our answer.

The full walkthrough guide, and the code is present below.

class Solution{public String frequencySort(String s) {
HashMap<Character,Integer> hmap = new HashMap<>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
hmap.put(c, hmap.getOrDefault(c, 0)+ 1);
}

List<Map.Entry<Character, Integer>> listOfEntries =
new ArrayList<Map.Entry<Character, Integer>> (hmap.entrySet());

Collections.sort(listOfEntries, new Comparator<Map.Entry<Character, Integer> >() {
public int compare(Map.Entry<Character, Integer> e1,
Map.Entry<Character, Integer> e2)
{
return (e2.getValue()).compareTo(e1.getValue());
}
});

String sortedString = "";
for (Map.Entry<Character, Integer> entry : listOfEntries) {
sortedString +=String.valueOf(entry.getKey()).repeat(entry.getValue());
}

return sortedString;
}

}

Thank you for reading!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

iAwale
iAwale

Written by iAwale

Learn Productivity. Learn Growth. Learn Coding. Learn to Build Applications. If you like the content please follow Twitter Youtube

No responses yet

Write a response