Sort Characters By Frequency
1 approach, code in every language
Problem description
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 digits
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Regroup The Sticker Sheet is our own problem on the technique behind Sort Characters By Frequency: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free