Sort Characters By Frequency (LeetCode 451): Solution and Explanation
Rearrange a string so its characters appear in decreasing order of how often they occur, with all copies of a character kept together. Uppercase and lowercase letters count as different characters.
Intuition
The order only depends on each character's count, not on where it appears. So the first job is a frequency count, which takes one pass over the string.
After counting, you have at most 62 (character, count) pairs: 26 lowercase letters, 26 uppercase letters and 10 digits. The answer is just those pairs, biggest count first, each expanded into a block.
A max-heap keyed on count hands you the biggest remaining pair every time you pop. Pop, write that character count times, and repeat until the heap is empty.
When two characters share a count, either order is valid. The heap breaks ties in some fixed way, which is fine: the judge accepts any order among characters with the same count.
Approach: Count, then a max-heap
- Count every character of
sin a hash map. - Push each
(count, char)pair into a max-heap ordered by count. - While the heap is not empty, pop the root and append
charrepeatedcounttimes to the output. - Join the blocks and return the string.
Step-by-step example
s = "trreee"
- Count: t = 1, r = 2, e = 3.
- Push (t, 1). Push (r, 2), which beats its parent t and sifts up to the root. Push (e, 3), which beats r and becomes the root.
- Pop (e, 3) and write "eee". The last leaf moves to the root and sifts down, leaving r on top.
- Pop (r, 2) and write "rr", then pop (t, 1) and write "t".
- Return "eeerrt".
Code: Python, Java, C++
1class Solution:
2 def frequencySort(self, s: str) -> str:
3 count = Counter(s)
4 heap = []
5 for c, f in count.items():
6 heapq.heappush(heap, (-f, c))
7 out = []
8 while heap:
9 f, c = heapq.heappop(heap)
10 out.append(c * -f)
11 return "".join(out)1class Solution {
2 public String frequencySort(String s) {
3 Map<Character, Integer> count = new HashMap<>();
4 for (char c : s.toCharArray()) {
5 count.merge(c, 1, Integer::sum);
6 }
7 PriorityQueue<Map.Entry<Character, Integer>> heap = new PriorityQueue<>(
8 (a, b) -> !a.getValue().equals(b.getValue()) ? b.getValue() - a.getValue() : a.getKey() - b.getKey());
9 for (Map.Entry<Character, Integer> e : count.entrySet()) {
10 heap.offer(e);
11 }
12 StringBuilder out = new StringBuilder();
13 while (!heap.isEmpty()) {
14 Map.Entry<Character, Integer> e = heap.poll();
15 out.append(String.valueOf(e.getKey()).repeat(e.getValue()));
16 }
17 return out.toString();
18 }
19}1class Solution {
2public:
3 string frequencySort(string s) {
4 unordered_map<char, int> count;
5 for (char c : s) {
6 count[c]++;
7 }
8 priority_queue<pair<int, int>> heap;
9 for (auto& [c, f] : count) {
10 heap.push({f, -(int)c});
11 }
12 string out;
13 while (!heap.empty()) {
14 auto [f, nc] = heap.top(); heap.pop();
15 out.append(f, (char)(-nc));
16 }
17 return out;
18 }
19};Time and space complexity
O(n + k log k)
Counting is one pass over the n characters. The heap holds k distinct characters (at most 62), so its pushes and pops cost O(k log k), and writing the output is O(n).
O(n)
The count map and heap hold k entries; the output string holds all n characters.
Other approaches
Bucket sort by count (time O(n), space O(n))
Make buckets indexed by count from 1 to n, drop each character into bucket[count], then walk the buckets from n down to 1. No comparisons at all.
Sort the count pairs (time O(n + k log k), space O(n))
Collect the (char, count) pairs and sort them by count descending. With at most 62 pairs this is just as fast in practice and shorter to write.
Common mistakes
- Sorting characters by count but interleaving them. All copies of a character must be written as one block.
- Treating 'A' and 'a' as the same character. They are different and are counted separately.
- Building the output with repeated string concatenation in a loop. In languages with immutable strings that can turn quadratic; use a list or a string builder.
- Pushing the raw count into Python's heapq, which is a min-heap. Negate the count to get the largest first.
Frequently asked questions
Why use a heap when there are at most 62 distinct characters?
It is the natural tool for repeatedly taking the largest remaining item, and it is what interviewers usually expect here. Sorting the pairs or bucket sort work equally well for this input size.
What happens when two characters have the same count?
Any order between them is accepted, here and on LeetCode. The judge checks that each character's copies are together and that counts never increase from left to right.
Is the bucket approach really O(n)?
Yes. A character's count is between 1 and n, so n + 1 buckets cover every count, and each character lands in exactly one bucket.