Skip to content
Decoder

Sort Characters By Frequency

Medium

Problem

Given a string s, rearrange its characters so that they are ordered by how often they appear, most frequent first. All copies of a character must sit together. Characters with the same count can appear in any order, so several answers can be correct.

Uppercase and lowercase letters are different characters.

Example 1

Input
"tree"
Output
"eert"
Why
"eetr" is also fine

Example 2

Input
"cccaaa"
Output
"cccaaa"
Why
"aaaccc" is also fine, but "cacaca" is not

Example 3

Input
"Aabb"
Output
"bbAa"
Why
"bbaA" is also fine

Constraints

  • 1 <= s.length <= 5 * 10^5
  • s holds uppercase and lowercase English letters and digits.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.