Sort Characters By Frequency

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem

Sort characters by frequency (descending). Tie-break by character value.

Solutions

// C++
string frequencySort(string s) {
    unordered_map<char, int> cnt;
    for (char c : s) cnt[c]++;
    priority_queue<pair<int,char>> maxH;
    for (auto& [c, f] : cnt) maxH.push({f, c});
    string res;
    while (!maxH.empty()) {
        auto [f, c] = maxH.top(); maxH.pop();
        res += string(f, c);
    }
    return res;
}
// Java
public String frequencySort(String s) {
    Map<Character, Integer> cnt = new HashMap<>();
    for (char c : s.toCharArray()) cnt.merge(c, 1, Integer::sum);
    PriorityQueue<Map.Entry<Character, Integer>> maxH =
        new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
    maxH.addAll(cnt.entrySet());
    StringBuilder sb = new StringBuilder();
    while (!maxH.isEmpty()) {
        var e = maxH.poll();
        for (int i = 0; i < e.getValue(); i++) sb.append(e.getKey());
    }
    return sb.toString();
}
// JavaScript
function frequencySort(s) {
    const cnt = new Map();
    for (const c of s) cnt.set(c, (cnt.get(c) || 0) + 1);
    const entries = [...cnt.entries()].sort((a, b) => b[1] - a[1]);
    return entries.map(([c, f]) => c.repeat(f)).join('');
}
# Python
from collections import Counter

def frequencySort(s):
    count = Counter(s)
    return ''.join(c * freq for c, freq in count.most_common())

Complexity

  • Time: O(n log n) due to sort
  • Space: O(n)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro