AlgoViz

Sort Characters by Frequency

Easy

Count, then order by count

Problem

Sort a string's characters by decreasing frequency.

In simple words

Count each character, then rebuild the string with the most frequent letters first.

The idea

Build the frequency map in one pass, then emit characters in descending count order — either by sorting the distinct characters or by bucketing them by frequency. Bucketing avoids the sort entirely since counts are bounded by the string length.

The trick

  • Bucket by count for O(n); sorting the distinct characters is O(k log k) and usually fine.
  • Emit each character repeated by its count.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

0
0

Step 1 of 2. Here's the example — tree Values: 0.

1/2
Optimal
timeO(n log n)spaceO(n)
1freq = counts(s)2sort chars by freq desc3build string repeating each char freq times

Input

array
[0]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
s = "tree"
Output:
"eert"
Explanation:
e appears twice, so it leads.

Example 2

Input:
s = "cccaaa"
Output:
"aaaccc"
Explanation:
Both appear 3 times; ties broken alphabetically.

Example 3

Input:
s = "Aabb"
Output:
"bbAa"
Explanation:
b is most frequent, then a, then A.

Finished the walkthrough? Add it to your streak.