मुख्य कंटेंट तक स्किप करें
Back to ChallengesSort Characters by FrequencyHard 35 min

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.

Examples

Input: s = 'tree'
Output: 'eert'
'e' appears twice while 'r' and 't' both appear once.

Constraints

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

Complexity Analysis

Time
O(N + K log K)
where K is number of unique characters.
Space
O(N)
to store the result and map.

Test Cases

#1 Standard word
Input: s = 'tree'
Expected: 'eert'
#2 Case sensitivity
Input: s = 'Aabb'
Expected: 'bbAa'
JavaScript
Output
Click "Run Code" to see output here...