life is too short for a diary




Sort Characters By Frequency solution leetcode

Tags: leetcode java python heap

Featured image for Sort Characters By Frequency solution leetcode

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them

Explanation

  1. Use hashmap to count the frequency of all characters in string

  2. Insert character & frequency pair into Max Heap where frequency is used for ranking.

  3. Extract Maximum from the heap and append it to the output string.

Solution


comments powered by Disqus