SDE & MLE Prep

451. Sort Characters By Frequency

Problem

Sort the characters of s by decreasing frequency (case-sensitive). Any order among characters with equal counts is fine.

Example: "tree" → "eert" (or "eetr"); "Aabb" → "bbAa" (or "bbaA")

Count characters, then emit them from most to least frequent (bucket sort by count, or sort the ≤ 62 distinct chars).

Complexity: O(n).

class Solution:
    def frequencySort(self, s: str) -> str:
        return "".join(ch * c for ch, c in Counter(s).most_common())