364. Sort Characters By Frequency
You are given a string s made of uppercase letters, lowercase letters, and digits. Rebuild it so that the characters appearing most often come first, with all copies of the same character grouped together.
To make the answer unique, order the distinct characters by descending count, and break count ties by ascending character code (so '2' comes before 'A', which comes before 'a'). Case matters: 'A' and 'a' are different characters.
Your function receives the string s and returns the rebuilt string.
Example 1:
Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice, so its group leads. 'r' and 't' both appear once; 'r' has the smaller character code, so it comes before 't'.
Example 2:
Input: s = "cccaaa"
Output: "aaaccc"
Explanation: 'a' and 'c' both appear three times — a tie — so the smaller character 'a' goes first. Something like "cacaca" is invalid because equal characters must stay together.
Example 3:
Input: s = "Aabb"
Output: "bbAa"
Explanation: 'b' appears twice and leads. 'A' (code 65) and 'a' (code 97) both appear once, so 'A' comes before 'a'.
Constraints:
- 1 ≤ s.length ≤ 5 * 10⁵
- s consists of uppercase English letters, lowercase English letters, and digits.
Hints:
You cannot decide anything until you know how often each character occurs — one counting pass over the string gives you a table of at most 62 entries.
Only the distinct characters need ordering, not the n characters themselves. Sort the (at most 62) table entries by (-count, character), or bucket characters by count since a count can never exceed n.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: s = "tree"
Expected output: "eert"