MediumPythonJavaScriptTypeScript
Sorting — Sort Characters by Frequency
AlgorithmsSortingHash MapStrings
solve(s) — return the characters of s sorted by decreasing frequency. Every
occurrence of a character stays grouped: "eert", not "erte".
Ties are broken by the character itself, ascending by character code, so there is
exactly one answer (uppercase letters sort before lowercase ones).
Count with a map, then sort the distinct characters — that is O(n + k log k) withk distinct characters — and rebuild the string.
Examples
solve("tree") → "eert"
solve("cccaaa") → "aaaccc" // tie: "a" before "c"
solve("Aabb") → "bbAa" // "A" (65) before "a" (97)Sample tests
Test #1One dominant letter
Input: ["tree"]
Output: "eert"
Test #2Tie broken alphabetically
Input: ["cccaaa"]
Output: "aaaccc"
Test #3Uppercase before lowercase on a tie
Input: ["Aabb"]
Output: "bbAa"