Skip to content
BytePatterns

Sort Letters by Frequency

MediumHash Tables#bucket-sort#counting~20m

Problem

Rearrange the characters of a string so that equal characters sit together and the groups appear from most frequent to least frequent. When two characters appear equally often, the one whose first appearance in the input is earlier goes first. Return the rearranged string, and do it without a comparison sort over the characters.

Examples

Input:  text = "banana"
Output: "aaannb"
Why:    a appears 3 times, n twice and b once
Input:  text = "mississippi"
Output: "iiiissssppm"
Why:    i and s both appear 4 times, and i shows up first in the input
Input:  text = ""
Output: ""
Why:    edge case, nothing to rearrange

Hints

0 / 3

Stuck on the idea rather than the code? Top K Without a Heap covers it.