127. Loudest Letters First
A radio host wants to display a message with its most frequent characters first. Given the string s, rearrange its characters so that characters that occur more often come earlier. All copies of one character must stay together as a block. If two different characters occur equally often, the one with the smaller character code (so digits come before capital letters, and capital letters before lower case letters) comes first.
Return the rearranged string. It must contain exactly the same characters as s. Count the characters first, then sort only the distinct characters; sorting every position separately is too slow for long messages.
Example 1
- Input:
- s = "banana"
- Output:
- "aaannb"
- Explanation:
a occurs 3 times, n twice and b once, giving aaannb.
Example 2
- Input:
- s = "zzyx"
- Output:
- "zzxy"
- Explanation:
z occurs twice and comes first; y and x occur once each, and x has the smaller code, giving zzxy.
Constraints
1 ≤ s.length ≤ 105
s contains only English letters and digits
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n + k log k)
- Space
- O(n)