Sort Characters By Frequency

Given a string `s`, sort it in decreasing order of how often each character occurs, keeping all copies of a character together. If several answers are valid, return any of them.

30:00

Sort Characters By Frequency
medium
Free written solution
Topics
Companies

Given a string s, sort it in decreasing order of how often each character occurs, keeping all copies of a character together. If several answers are valid, return any of them.

Example 1:
Input: {"s":"tree"}
Output: eert
Constraints:
  • 1≤s.length≤5×1051 \leq s.\text{length} \leq 5 \times 10^5

  • s consists of uppercase and lowercase English letters and digits.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"tree"}

s (4 chars)

t
r
e
e

count

empty

max-heap by count (0)

nothing pushed yet

output (0 chars)

empty

Characters with bigger counts must come first, so count them, then let a max-heap hand them out biggest first.

Variables
VariableValue
n4
DepthFunction Call
Stack empty
0/11