Sort Characters By Frequency

Given a string, reorder its characters so that characters with higher frequency come first. To keep the answer deterministic, break ties by smaller character code first.

Input Format

s = input string

Output Format

string sorted by frequency descending and character ascending on ties

Constraints

  • 1 <= s.length <= 10^5

Examples

Example 1:

Input:

s = "tree"

Output:

eert

Explanation:

e appears twice, while r and t appear once; r comes before t on the tie.

Example 2:

Input:

s = "cccaaa"

Output:

aaaccc

Explanation:

a and c both appear three times, so a comes first on the tie.

Loading...
Sort Characters By Frequency - Heap DSA Problem