Sort Characters By Frequency
Build a string where characters are sorted by descending frequency using a max-heap.
Sort Characters By Frequency
Problem: Given a string s, sort it so that characters with higher frequency come first. Characters with the same frequency can be in any relative order.
Example:
- Input:
s = "tree" - Output:
"eert"or"eetr"— 'e' appears 2×, 't' and 'r' appear 1× each
Note
Count how often each character appears, then build the output by repeating each character its count number of times — most frequent first.
Brute Force
View Brute Force
Optimal — Max-Heap
View Optimal Solution
| Approach | Time | Space |
|---|---|---|
| Count + Sort | O(n log n) | O(n) |
| Count + Max-Heap | O(n log k) | O(n) |