LeetCode #451 Medium

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.

Constraints
  • 1 <= s.length <= 5 * 10^5
  • s consists of uppercase and lowercase English letters and digits.
heaphash-mapsortingstring
Open on LeetCode ↗
02

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 s gives every character's total.
  • Ordering: at most 62 characters need sorting, which is cheap however long s is.
  • 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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1from collections import Counter
▶2 
▶3 
▶4class Solution:
▶5 def frequencySort(self, s: str) -> str:
▶6 count = Counter(s)
▶7 order = sorted(count, key=lambda c: -count[c])
▶8 return "".join(c * count[c] for c in order)
st0r1e2e3counts1tanswer't' seen once → new column
s[0]'t'
count{t: 1}
Character 't' has not appeared before, so it gets its own column with one block. One pass like this finds every count in O(n).
st0r1e2e3counts1t1ranswer'r' seen once → new column
s[1]'r'
count{t: 1, r: 1}
Character 'r' has not appeared before, so it gets its own column with one block. One pass like this finds every count in O(n).
st0r1e2e3counts1t1r1eanswer'e' seen once → new column
s[2]'e'
count{t: 1, r: 1, e: 1}
Character 'e' has not appeared before, so it gets its own column with one block. One pass like this finds every count in O(n).
st0r1e2e3counts1t1r2eanswer'e' seen twice
s[3]'e'
count{t: 1, r: 1, e: 2}
'e' already has a column, so it grows to 2 blocks. Only the total matters, not where the copies sat in the string.
st0r1e2e3counts, most first2e1st1t2nd1r3rdanswermost frequent first: e, t, r
order['e', 't', 'r']distinct characters only
Sort the 3 distinct characters by their count, highest first, instead of sorting all 4 letters. Columns with the same height may sit in either order; both answers are accepted.
st0r1e2e3counts, most first2e1st1t2nd1r3rdanswereewrite 'e' twice in one block
c'e'
count[c]2
answer"ee"
Write all 2 copies of 'e' together. Writing each character's whole run at once is what keeps equal characters side by side.
st0r1e2e3counts, most first2e1st1t2nd1r3rdanswereetwrite the single 't'
c't'
count[c]1
answer"eet"
Write the single 't'. Writing each character's whole run at once is what keeps equal characters side by side.
st0r1e2e3counts, most first2e1st1t2nd1r3rdanswereetrwrite the single 'r'
c'r'
count[c]1
answer"eetr"
Write the single 'r'. Writing each character's whole run at once is what keeps equal characters side by side.
st0r1e2e3counts, most first2e1st1t2nd1r3rdanswereetranswer: eetr
return"eetr"
Every block is used and every slot is filled. The answer has the same letters as "tree", grouped by character, with counts that never go up from left to right.
05

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.

▶1from collections import Counter
▶2 
▶3 
▶4class Solution:
▶5 def frequencySort(self, s: str) -> str:
▶6 count = Counter(s)
▶7 buckets = [[] for _ in range(len(s) + 1)]
▶8 for c, k in count.items():
▶9 buckets[k].append(c)
▶10 
▶11 parts = []
▶12 for k in range(len(s), 0, -1):
▶13 for c in buckets[k]:
▶14 parts.append(c * k)
▶15 return "".join(parts)
06

Common pitfalls

Counting into a 26-slot array

✗ Wrong
count = [0] * 26
for c in s:
    count[ord(c) - ord('a')] += 1
✓ Right
count = 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

✗ Wrong
return "".join(sorted(s, key=lambda c: -count[c]))
✓ Right
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

✗ Wrong
order = sorted(count, key=lambda c: count[c])
✓ Right
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

✗ Wrong
for (int i = 0; i < k; i++) result += c;
✓ Right
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.

07

Edge cases

Every character appears once, like "abc"

All counts tie at 1, so every arrangement is valid. The Python code returns the characters in the order it first met them.

08

Complexity

Time
O(n + k log k)
Space
O(n)
n is the length of 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).
09

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".