Sort Characters By Frequency

Build a string where characters are sorted by descending frequency using a max-heap.

Sort Characters By Frequency

Problem: Given a string s, sort it so that characters with higher frequency come first. Characters with the same frequency can be in any relative order.

Example:

  • Input: s = "tree"
  • Output: "eert" or "eetr" — 'e' appears 2×, 't' and 'r' appear 1× each

Note

Count how often each character appears, then build the output by repeating each character its count number of times — most frequent first.


Brute Force


Optimal — Max-Heap


ApproachTimeSpace
Count + SortO(n log n)O(n)
Count + Max-HeapO(n log k)O(n)

LeetCode 451 — Sort Characters By Frequency