Sort Characters by Frequency

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Sort Characters by Frequency

Approach

Count character frequencies using a hash map. Sort the unique characters by their frequency in descending order. Build the result by repeating each character by its count. Alternative: use bucket sort indexed by frequency for O(n) time.

Complexity Analysis

Time
O(n log n)
Space
O(n)

Pattern

Frequency Count + Sort

Why It Works

The hash map captures frequency in O(n). Sorting by frequency groups characters by their count. Repeating each character by its frequency reconstructs the string in the desired order. Bucket sort variant avoids the O(n log n) comparison sort.

Updated Feb 2026