Solvarch
DSA ProblemsProgressPlanRoadmapsReviewCheat SheetsCompaniesSystem DesignCS FundamentalsQuestion Bank
Theme
Problems

Sort Characters By Frequency

Medium
heaphash-tablesortingstring

Given a string s, sort its characters by decreasing frequency and return the result. Characters with equal frequency appear in ascending character order (so the output is deterministic).

Input: one line, the string s. Output: the frequency-sorted string.

Example 1
Input:
tree
Output:
eert

'e' twice, then 'r' and 't' (tie → ascending).

Example 2
Input:
cccaaa
Output:
aaaccc

Tie at 3 — 'a' before 'c'.

Constraints

  • 1 ≤ s.length ≤ 5·10^5
  • Letters and digits.
Watch a video walkthrough

Run your code against the sample tests, or Submit to run the full suite.