Skip to main content
Back to problems
Leetcode
Medium
Hash Maps
Strings
Sorting
Heaps
Sort Characters By Frequency

Rearrange the characters of a string so that characters with higher frequency appear first.

Acceptance 0%
Problem Statement

Problem

Given a string s, reorder its characters so that characters with a higher occurrence count come before characters with a lower occurrence count.

If multiple valid answers exist, return any of them. Characters with the same frequency may appear in any order relative to one another.

Your task is to produce one such rearranged string.

Notes

  • The input consists of lowercase and uppercase letters and may include other visible characters depending on the platform version.
  • The result should contain exactly the same characters as the input, only reordered.

Input Format

  • A single string s.

Clarification

The string length is the total number of characters to reorder.

Output Format

  • Return a string containing the same characters as s, arranged in non-increasing order of character frequency.

Constraints

  • 1 <= s.length <= 5 * $10^{4}$
  • The answer is not necessarily unique.
  • The output must be a permutation of the input string.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "tree"

Output

"eert"

Explanation

e appears twice, while t and r appear once each. A valid ordering is eert.

Example 2

Input

s = "cccaaa"

Output

"cccaaa"

Explanation

Both c and a appear three times, so any order that keeps each character grouped by frequency is valid.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.