All problems

Sort Characters by Frequency

Medium · hash map

Given a string s of lowercase letters, rearrange its letters so that the most common letter comes first, then the next most common, and so on. All copies of a letter must stay together in one block.

If two letters appear the same number of times, the one that comes earlier in the alphabet goes first. This makes the answer unique. Return the rearranged string.

Examples

Example 1

Input: s = "banana"

Output: "aaannb"

There are three "a", two "n" and one "b", so the blocks go "aaa", "nn", "b".

Example 2

Input: s = "cabcab"

Output: "aabbcc"

All three letters appear twice, so they are ordered alphabetically.

Example 3

Input: s = "zzy"

Output: "zzy"

Constraints