Skip to content

Sort Characters By Frequency

MediumHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

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.

"tree"    →  "eert"   ("eetr" is also fine)
"cccaaa"  →  "cccaaa" ("aaaccc" is also fine, but "cacaca" is not)
"Aabb"    →  "bbAa"   ("bbaA" is also fine)

Constraints

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