← Non-Comparison Sorts (Counting, Radix, Bucket)Solve it on LeetCode ↗
Sort Characters By Frequency
MediumThe problem
Rearrange a string so characters appear in decreasing order of frequency (ties in any order).
Stuck? Reveal hints one at a time
How to approach it
- 1Count each character’s occurrences.
- 2Create buckets indexed by frequency; drop each character into bucket[frequency].
- 3Walk buckets from n down to 1, appending each character repeated by its frequency.
Key insight
When the sort key is a small integer (frequency ≤ n), bucket indexing replaces comparison sorting — the same trick behind Top K Frequent Elements.
The solution
Watch out for
- String concatenation in a loop is quadratic in some runtimes — collect parts and join.
- Case-sensitive: "A" and "a" count separately.