Sort Characters By Frequency
Master this topic with zero to advance depth.
Sort Characters By Frequency
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.
Visual Representation
s = "tree"
Frequency Count:
'e': 2
't': 1
'r': 1
Sorted by frequency: 'e' -> 't' -> 'r'
Result: "eetr" or "eert"Examples
Level I: Max-Heap (Standard)
Intuition
Count the frequency of each character. Then, construct a Max-Heap where the key is the frequency. Repeatedly pop the character with the highest frequency and append it to our result string the required number of times.
Thought Process
- Use a hash map to count character frequencies.
- Add all
(frequency, character)pairs to a Max-Heap. - Poll characters from the heap and append each to a
StringBuilderfrequencytimes. - Return the constructed string.
Detailed Dry Run
s = "tree"
- Map: {'t':1, 'r':1, 'e':2}
- Max-Heap: [('e',2), ('t',1), ('r',1)]
- Pop ('e',2). Appended 2 times -> "ee"
- Pop ('t',1). Appended 1 time -> "eet"
- Pop ('r',1). Appended 1 time -> "eetr" Result: "eetr"
Level II: Sorting Map Entries
Intuition
Collect character frequencies in a map, convert the map entries to a list, and sort the list by frequency in descending order. Then build the string based on the sorted list.
Detailed Dry Run
s = "tree"
- Map: {'t':1, 'r':1, 'e':2}
- List of entries: [('t',1), ('r',1), ('e',2)]
- Sorted List: [('e',2), ('t',1), ('r',1)]
- Result: "eetr"
Level III: Bucket Sort (Optimal)
Intuition
Since the maximum frequency a character can have is the length of the string N, we can use an array of lists as buckets. bucket[i] stores characters that appear exactly i times.
Detailed Dry Run
s = "tree", N=4
- Map: {'t':1, 'r':1, 'e':2}
- Buckets array of size 5: [0:[], 1:['t','r'], 2:['e'], 3:[], 4:[]]
- Iterate from 4 down to 1.
- i=2: bucket contains 'e'. Append 'e' 2 times -> "ee"
- i=1: bucket contains 't','r'. Append 't' 1 time, 'r' 1 time -> "eetr"
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.