Sort by Character Frequency

Medium~20 min

Given a string s consisting of lowercase English letters, sort it in decreasing order of character frequency.

If two characters have the same frequency, sort them in alphabetical order.

Return the resulting sorted string.

Examples

Example 1
Input: s = "tree"
Output: "eert"
Explanation: "e" appears 2 times, "r" and "t" each appear 1 time. Characters with frequency 1 are sorted alphabetically: r before t. Result: "eert".
Example 2
Input: s = "cccaaa"
Output: "aaaccc"
Explanation: "a" and "c" both appear 3 times. Same frequency, so alphabetical order: a before c. Result: "aaaccc".
Example 3
Input: s = "aab"
Output: "aab"
Explanation: "a" appears 2 times, "b" appears 1 time. Higher frequency first, so "aa" then "b". Result: "aab".

Constraints

  • 1 <= s.length <= 5 * 10^4
  • s consists of lowercase English letters only
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run