Applied AI Engineer (LLM) coding learning path Level 2 This level · 5 of 31

Sort Characters By Frequency

Medium String Sorting Counting

Problem

Reorder a string so that characters appear in decreasing order of frequency. If two characters have the same frequency, either order is acceptable.

Original: LeetCode 451: Sort Characters By Frequency.

Examples

Example 1

Input`s = "tree"`
Output`"eert"`

"eetr" is also valid: both r and t appear once.

Example 2

Input`s = "cccaaa"`
Output`"aaaccc"`

"cccaaa" is also valid, but "cacaca" is not, because equal characters must be together.

Example 3

Input`s = "Aabb"`
Output`"bbAa"`

"bbaA" is also valid. "A" and "a" are different characters.

Constraints

  • 1 <= s.length <= 5 * 10^5
  • s consists of uppercase and lowercase English letters and digits.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 451: Sort Characters By Frequencyleetcode.com
  2. Java SE 17 API: Map.mergedocs.oracle.com
Previous
Next