Given a string, reorder its characters so that they appear in order of decreasing frequency. The frequency of a character is the number of times it shows up in the string.
Return any string that is a valid rearrangement. Characters that share the same frequency may appear in any relative order, but every occurrence of a given character must stay grouped together.
Example 1
Input: s = "tree"
Output: "eert"
'e' appears twice while 'r' and 't' appear once each, so 'e' comes first; "eetr" would also be accepted.
Example 2
Input: s = "cccaaa"
Output: "aaaccc"
Both 'a' and 'c' appear three times, so any grouping such as "cccaaa" is valid as long as identical characters are adjacent.
Constraints
1 <= s.length <= 5 * 10^5s consists of uppercase and lowercase English letters and digitsSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI