Sort Characters by Frequency
Min-Heap
Problem
Given a string, sort it in decreasing order based on the frequency of characters.
For example:
Thought Process
This problem is similar to Top K Frequent Elements where we built a min-heap but instead in this problem we are using a max-heap in order to get the largest frequencies in order. We don't care about the top K so that is why we are not using a min-heap.
Solution
Key Points
Using a max-heap so we get all the frequencies from largest to smallest in order
While the heap is not empty, we will build a string, appending the most occuring characters first.
Time Complexity
Time: where ‘D’ is the number of distinct characters in the input string. This means, in the worst case, when all characters are unique the time complexity of the algorithm will be where ‘N’ is the total number of characters in the string.
Space: as in the worst case, we need to store all the ‘N’ characters in the HashMap.
Last updated
Was this helpful?