sagelearnai

Sort Characters By Frequency

Difficulty: Medium · Pattern: Heap & Priority Queue · LeetCode #451

Sort a string in decreasing order of character frequency. Characters with the same frequency may come in any order, but all copies of a character must be grouped together. The tests list every valid answer.

Examples

text
"tree"   →  "eert"  or "eetr"
"cccaaa" →  "cccaaa" or "aaaccc"
"Aabb"   →  "bbAa"  or "bbaA"   (case-sensitive)

Hints

  1. Count each character.
  2. Frequencies are between 1 and n, so bucket sort gives O(n): bucket[f] holds the characters with count f.

Approach

Count with a hash map, then either:

  • Sort the distinct characters by count, descending. That's O(σ log σ), where σ ≤ 62 here, so effectively O(n).
  • Bucket: buckets[f].append(ch), then walk f from n down to 1 and emit ch * f. This is a true O(n) and the answer interviewers like to hear.

Complexity

Time: O(n). Space: O(n).

Python solution
from collections import Counter

def frequencySort(s):
    cnt = Counter(s)
    buckets = [[] for _ in range(len(s) + 1)]
    for ch, f in cnt.items():
        buckets[f].append(ch)
    out = []
    for f in range(len(s), 0, -1):
        for ch in buckets[f]:
            out.append(ch * f)
    return ''.join(out)
JavaScript solution
function frequencySort(s) {
  const cnt = new Map();
  for (const ch of s) cnt.set(ch, (cnt.get(ch) || 0) + 1);
  return [...cnt].sort((a, b) => b[1] - a[1]).map(([ch, f]) => ch.repeat(f)).join('');
}