Sort Characters By Frequency

MediumStringHash TableSortingTree

Description

Given a string s, sort it in decreasing order based on the frequency of the characters. Characters with same frequency can be in any order. Return the result as a string.

Examples

Input:s = "tree"
Output:"eert"
Explanation:

Frequency: e=2, t=1, r=1. Sort by frequency descending: 'ee' then 'r' then 't'. Result: 'eert'.

Input:s = "programming"
Output:"ggmmrrainop"
Explanation:

r, g, and m each appear 2 times. The remaining characters p, o, a, i, and n each appear once, so any order among them is valid.

Input:s = "a"
Output:"a"
Explanation:

Single character string - the character 'a' appears once, so the output is just 'a'.

Constraints

  • 1 ≤ s.length ≤ 5 × 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!