Sort Characters By Frequency

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

Example 1
Inputs = "tree"
Output"eert"
'e' appears twice while 'r' and 't' both appear once, so 'e' must appear before both 'r' and 't'; therefore "eetr" is also a valid answer.
Example 2
Inputs = "cccaaa"
Output"aaaccc"
Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers, but "cacaca" is incorrect because the same characters must be together.

Constraints

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

Asked at 15 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate