MediumHash TableStringSortingHeap (Priority Queue)Bucket SortCounting

Sort Characters By Frequency

LeetCode
1 approach, code in all languages

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^5
  • s consists of uppercase and lowercase English letters and digits
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now