Sort Characters By Frequency
Sort Characters By Frequency is LeetCode 451 (Medium). Given a string s, rearrange its characters so they appear in decreasing order of how often they occur.
- All copies of a character must sit next to each other.
- Characters with the same count may come in either order, and any such answer is accepted.
- Uppercase letters, lowercase letters and digits are all different characters.
The string can be 500,000 characters long, but it can hold at most 62 distinct characters.
- 1 <= s.length <= 5 * 10^5
- s consists of uppercase and lowercase English letters and digits.
Intuition
Where a character sits in s does not matter. Only its total does. So count first, then sort the distinct characters, not the string.
- Counting: one pass over
sgives every character's total. - Ordering: at most 62 characters need sorting, which is cheap however long
sis. - Writing: each character's copies are written as one block, so equal characters can never end up apart.
Sorting all 500,000 letters would do far more work and still leave equal-count letters mixed together, which the counting route avoids.
"Order items by how often they occur" is count-then-sort. Top K Frequent Elements and Sort Array by Increasing Frequency use the same two steps; only what you output at the end changes.
Approach
Before reading on, decide what you really need to sort: the 500,000 letters, or something much smaller. Then decide how you will keep equal letters next to each other. Aim for O(n) time.
Two ways to solve it
Count, sort the distinct characters by count, write each run.
- Short: three lines in Python.
- Fast enough: at most 62 characters to sort.
The usual interview answer.
Put each character in the bucket for its count, then read the buckets from n down to 1.
- No comparison sort: strictly linear.
- Cost: n + 1 buckets, almost all empty.
The answer to "can you avoid the sort?"
Both are linear in practice, because there are at most 62 distinct characters. Counting and sorting is shorter, so the steps, code and demo use it; the bucket version comes after the demo.
Count every character
Walk the string once and add 1 to count[c] for each character. A hash map, such as Python's Counter, handles letters of both cases and digits with no index arithmetic.
Sort the distinct characters by count
Sort the keys of count by their count, largest first. There are at most 62 keys, so this sort is tiny even when s is huge.
Write each run in one piece
For each character in that order, append it count[c] times, then join the pieces once. A run written as one block keeps every copy together, and a single join keeps the build linear.
Why the result is correct
Each character appears exactly as often as it does in s, all of its copies are adjacent, and the runs come out with counts that never increase. Those three facts are the whole definition of a valid answer.
Code in Python, C++ and Java
Bucket by count
A count is always between 1 and n, so make n + 1 buckets and drop each character into the bucket for its count. Reading the buckets from n down to 1 visits the characters from most to least frequent without any comparison sort.
Common pitfalls
Counting into a 26-slot array
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1count = Counter(s)
s can hold uppercase letters and digits. On "Aabb", ord('A') - ord('a') is -32, which raises IndexError in Python and reads outside the array in C++. Use a map or a 128-slot array.
Sorting every letter by its count
return "".join(sorted(s, key=lambda c: -count[c]))
order = sorted(count, key=lambda c: -count[c])
Letters with equal counts keep their original order, so "abab" comes back as "abab" with the two a's apart. It also sorts all n letters instead of the few distinct ones.
Sorting the counts upward
order = sorted(count, key=lambda c: count[c])
order = sorted(count, key=lambda c: -count[c])
The most frequent character must come first. Sorting upward returns "tree" unchanged for the input "tree", when the answer starts with "ee".
Adding one character at a time to a Java String
for (int i = 0; i < k; i++) result += c;
result.append(String.valueOf(c).repeat(k)); // StringBuilder
Each += copies the whole string built so far. On a 500,000-letter input that is about 10^11 character copies and a time-out; a StringBuilder keeps it linear.
Edge cases
All counts tie at 1, so every arrangement is valid. The Python code returns the characters in the order it first met them.
Complexity
s and k is the number of distinct characters, at most 62. Counting and writing take O(n); the sort takes O(k log k), which is a constant here, so the run time is linear in practice. The answer takes O(n) space and the counts O(k).Sort Characters By Frequency FAQ
Can a heap solve it?
Yes. Push (-count, char) for each distinct character and pop until the heap is empty, writing each run as it comes out. That costs O(n + k log k), the same as sorting, so a heap only pays off when you need just the first few characters, as in Top K Frequent Elements.
What if equal counts must be in alphabetical order?
Some versions of the problem ask for that. Sort by the pair (-count[c], c) instead of the count alone; "bbaacd" then gives "aabbcd".