← DiffPush

Sort characters by frequency

Standard Bar Strings · Medium O(n log n) · O(n)

Ranking the NOC's Loudest Event Codes

A network operations center triages a feed where every event is a single-character code, and by the end of a shift some codes have fired far more often than others. The digest printer re-emits the whole feed rearranged so the noisiest codes lead, repeating each code once per occurrence. Codes tied at the same frequency may land in any order — only the ranking is contractual.

Input: A string s of characters.

Output: A rearrangement of s in which every character's block is no shorter than the block of any character that follows it; ties may be ordered arbitrarily.

Constraints

Examples

Example 1

Input: {"s":"tree"}
Output: "eert"
e occurs twice so both e's lead; the once-occurring letters follow in either order.

Example 2

Input: {"s":"cccaaa"}
Output: "cccaaa"
Two codes tie at three occurrences, so either block may lead — the stored answer keeps the c block first.

Solve this in your browser →

Also on LeetCode ↗