Sort Characters By Frequency
Medium
Topics
Given a string s, rearrange its characters so that the most frequent character comes first, then the next most frequent, and so on. All copies of a character stay together.
Characters that occur the same number of times are ordered by their character code, smallest first, which makes the answer unique.
LeetCode accepts any ordering among equally frequent characters. The tie-break above is added here so the judge has a single answer to compare against.
Example 1
r and t both occur 1 times, and the character code decides which comes first — without that rule either order would be defensible.Input: s = "tree" Output: "eert" Explanation: "e" occurs twice. "r" and "t" occur once each, and "r" has the smaller character code, so it comes first. LeetCode would also accept "eetr"; the tie-break here does not.
Example 2
Input: s = "cccaaa" Output: "aaaccc" Explanation: Both occur three times, so the tie-break puts "a" first.
Example 3
Input: s = "Aabb" Output: "bbAa" Explanation: "b" occurs twice. Then "A" and "a" tie at one, and uppercase "A" has the smaller code.
Constraints
- 1 <= s.length <= 5 * 10^5
- s consists of uppercase and lowercase English letters and digits
Editorial — intuition, approach, complexity and pitfalls
Intuition
Count the characters, order the distinct ones, then write each out as many times as it occurred. The only thing that needs care is the ordering, because the two keys run in opposite directions: count descending, character ascending.
Expressed as a single sort key that is (-count, character). Sorting by count and then reversing is wrong, because it reverses the character key as well and ties come out backwards.
There is a second route that avoids comparison entirely. A character can occur at most len(s) times, so make a list of that many slots and put each character in the slot matching its count. Walking the slots from the highest down yields the counts in descending order for free, and keeping each slot internally sorted handles the tie-break.
That slot approach is linear rather than log-factored, which matters at half a million characters, though in practice the distinct alphabet here is tiny so the sort is already fast.
Approach
- Count occurrences of each distinct character.
- Order the distinct characters by count descending, breaking ties by character code ascending.
- Build the answer by appending each character repeated by its count.
- For the counting-sort variant: create buckets indexed
0tolen(s), place each character in the bucket for its count, then walk the buckets from the top down, emitting each bucket’s characters in sorted order.
Walkthrough
s = "Aabb"
counts
A 1
a 1
b 2
sort key (-count, char)
b (-2, "b")
A (-1, "A") code 65
a (-1, "a") code 97
A and a tie on count, so the character code decides,
and 65 < 97 puts "A" first.
write out
"b" * 2 + "A" * 1 + "a" * 1 = "bbAa"
what reversing would do
sort ascending by count: A a b
reverse: b a A
-> "bbaA", which has the tie backwards.Complexity
- Time — O(n + d log d): counting is linear; the sort is over the d distinct characters, at most 62 here.
- Space — O(n): the output string, plus one counter per distinct character.
Common Pitfalls
- Sorting ascending and reversing, which puts tied characters in the wrong order.
- Comparing characters as strings in one language and as code points in another. The tie-break is by character code, so
"Z"precedes"a". - Splitting the copies of a character across the output. All copies are contiguous.
- Returning the distinct characters in order rather than repeating each by its count.
- Assuming only lowercase letters. Digits and uppercase letters appear, which is what the character-code tie-break has to handle.
Full Solution — all languages
class Solution:
def frequencySort(self, s):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
# Count descending, character ascending.
ordered = sorted(counts, key=lambda ch: (-counts[ch], ch))
return "".join(ch * counts[ch] for ch in ordered)import java.util.*;
class Solution {
public String frequencySort(String s) {
Map<Character, Integer> counts = new HashMap<>();
for (char ch : s.toCharArray()) counts.merge(ch, 1, Integer::sum);
List<Character> distinct = new ArrayList<>(counts.keySet());
distinct.sort((x, y) -> {
int byCount = counts.get(y) - counts.get(x); return byCount != 0 ? byCount : Character.compare(x, y);
})
;
StringBuilder out = new StringBuilder();
for (char ch : distinct) {
for (int i = 0; i < counts.get(ch); i++) out.append(ch);
}
return out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string frequencySort(string s) {
unordered_map<char, int> counts;
for (char ch : s) counts[ch]++;
vector<char> distinct;
for (auto& kv : counts) distinct.push_back(kv.first);
sort(distinct.begin(), distinct.end(), [&](char x, char y) {
if (counts[x] != counts[y]) return counts[x] > counts[y]; return x < y;
})
;
string out;
for (char ch : distinct) out += string(counts[ch], ch);
return out;
}
};/**
* @param {string} s
* @return {string}
*/ var frequencySort = function(s) {
const counts = new Map();
for (const ch of s) counts.set(ch, (counts.get(ch) || 0) + 1);
return [...counts.keys()] .sort((x, y) => (counts.get(y) - counts.get(x)) || (x < y ? -1 : (x > y ? 1 : 0))) .map((ch) => ch.repeat(counts.get(ch))) .join("");
};