Sort Characters of a String by Frequency
Implement frequencySort
Given a string
s, sort its characters in decreasing order by frequency and return the result — every occurrence of a character stays adjacent, and more frequent characters come first.
Repeatedly scanning for the current most-frequent remaining character works, but redoing that scan for every one of the k distinct characters is quadratic in k. The faster approach counts frequencies once, then sorts the distinct characters by frequency a single time — one clean sort instead of k linear scans.
Example 1:
Input: s = "aabbbc"
Output: "bbbaac"
Example 2:
Input: s = "zzzyyx"
Output: "zzzyyx"
Example 3:
Input: s = "mnnooo"
Output: "ooonnm"
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ s.length ≤ 5 × 10³ - ●
s consists of lowercase English letters - ●
No two distinct letters in s share the same frequency (guarantees one unambiguous answer)
s =
aabbbc