Skip to content
Problem 451 · LeetCode 451(opens in a new tab)

Sort Characters By Frequency

MediumHash tables

You get a string s of letters and digits. Rearrange it so that characters that appear more often come first, with all copies of a character next to each other.

Upper-case and lower-case letters are different characters. When two characters appear the same number of times, either may come first; any valid arrangement is accepted.

Example 1

Input:  s = "door"
Output: "oodr"
Why:    o appears twice; "oord" is also fine
2 more examples and the constraints

Example 2

Input:  s = "xxyyy"
Output: "yyyxx"
Why:    3 y's, then 2 x's

Example 3

Input:  s = "zZz"
Output: "zzZ"
Why:    z and Z are different characters

Constraints

  • 1 ≤ length of s ≤ 500,000
  • s holds only English letters (upper or lower case) and digits

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count, then sort the stringO(n log n)
  2. Bucket by countO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 500,000 charactersVerdict
Count, then sort the stringO(n log n)
Passes; sorts more than it needs
Bucket by countO(n)
Best; no comparisons at all

n = length of s.

Edge cases to test

  • One character. "q" comes back as "q".
  • All the same character. "7777" is already its own answer.
  • Ties. "abab" may give "aabb" or "bbaa", never "abab".
  • Case and digits. 'A' and 'a' are counted separately, and digits count like letters.

Common mistakes

  • Sorting by count alone, so tied characters interleave ("abab" stays "abab").
  • Treating upper and lower case as the same character.
  • Building the result by repeated string concatenation in a loop, which can be slow in some languages.

How to talk through it

  1. 1Clarify. Is it case-sensitive? Which characters can appear? Is any order of ties fine?
  2. 2Count first. Any approach starts with a count per character; say it is one pass.
  3. 3Give the sort. Sort by (−count, char), O(n log n); point out why the tie-break is needed.
  4. 4Code the buckets. Counts are 1 to n, so bucket by count and read from the top.
  5. 5Test out loud. Run "door", a single character and a tie like "abab".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?