Sort Characters By Frequency
Problem Statement
You get a string s. Reorder its characters so that the most frequent character comes first, then the next most frequent, and so on. All copies of one character must sit next to each other.
If two characters appear the same number of times, either one may come first. Return the new string.
A string s.
A string with the same characters, where each character's copies are together and characters with more copies come first.
e appears twice, so it comes first. r and t appear once each, so they may come in either order. eetr is also accepted.
c and a both appear three times, so either can come first. cacaca is wrong, because all copies of a character must be together.
A and a are different characters, and each appears once. b appears twice, so it must come first. Aabb is wrong for the same reason.
- • 1 ≤ s.length ≤ 5 · 10^5
- • `s` consists of uppercase letters, lowercase letters and digits only.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Count the characters, then sort the string by (count high to low, character low to high)
Count the characters; pop from a max-heap of (count, char) and write all copies of each
Count the characters; bucket them by count; walk from n down, writing each block
Count each character. Then sort the string itself with a comparator: a character with more copies goes first. When the counts are equal, compare the characters, so copies of one letter stay together.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Heap — Top K translate into production architectures and low-level memory mechanics.