Sort Characters By Frequency
Pattern: Strings basics and frequency
Count each character, put each one in a bucket numbered by its count, and read the buckets from the highest count down, writing each character as many times as it appears.
The problem
Given a string, sort its characters by how often they appear, most frequent first, keeping all copies of a character
together. For example, "tree" can become "eert" or "eetr", and "cccaaa" can become "cccaaa" or "aaaccc".
Upper and lower case count as different characters.
The function name frequencySort matches LeetCode. Use the link above for the exact statement and limits. LeetCode
accepts any order among characters with equal counts. So that the tests have one answer, this guide puts ties in
character-code order (so "tree" gives "eert" and "Aabb" gives "bbAa").
Think first
- What do you need to know about each character?
- Counts are between 1 and
n. How can you order characters by count without a comparison sort? - How do you break ties so the output is fixed?
Hints
Brute force, and why it fails
Sort the distinct characters by count with a comparison sort: O(n + k log k) for k distinct characters, which is fine
too. Buckets avoid the sort and make it O(n).
The key insight
Counts are small whole numbers, at most n. That makes them perfect bucket numbers, which sorts by count in linear
time.
Dry run
| counts | e 2, r 1, t 1 |
|---|
s = tree. Counts are t 1, r 1, e 2.
The plan
count each character
buckets = n + 1 empty lists
for each character c in code order with count[c] > 0: add c to buckets[count[c]]
out = empty builder
for f from n down to 1:
for each c in buckets[f]: append c, f times
return out
Complexity
- Time
O(n)- Space
O(n)
Counting and writing are O(n), and there are n + 1 buckets.
Edge cases
- One character: itself.
- All characters equally frequent: they come out in code order.
- Capitals and digits are separate characters.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public String frequencySort(String s) {
int[] count = new int[128];
for (int i = 0; i < s.length(); i++) count[s.charAt(i)]++;
List<List<Character>> buckets = new ArrayList<>(); // buckets.get(f) = characters seen exactly f times
for (int f = 0; f <= s.length(); f++) buckets.add(new ArrayList<>());
for (char c = 0; c < 128; c++) if (count[c] > 0) buckets.get(count[c]).add(c); // in code order
StringBuilder out = new StringBuilder();
for (int f = s.length(); f >= 1; f--) { // most frequent first
for (char c : buckets.get(f)) for (int k = 0; k < f; k++) out.append(c);
}
return out.toString();
}
}C++
class Solution {
public:
string frequencySort(string s) {
int count[128] = {0};
for (char c : s) count[static_cast<int>(c)]++;
vector<vector<char>> buckets(s.size() + 1); // buckets[f] = characters seen exactly f times
for (int c = 0; c < 128; c++) if (count[c] > 0) buckets[count[c]].push_back(static_cast<char>(c));
string out;
for (int f = static_cast<int>(s.size()); f >= 1; f--) { // most frequent first
for (char c : buckets[f]) out += string(f, c);
}
return out;
}
};Python
class Solution:
def frequencySort(self, s: str) -> str:
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
buckets = [[] for _ in range(len(s) + 1)] # buckets[f] = characters seen exactly f times
for c in sorted(count): # in code order, so ties come out smallest first
buckets[count[c]].append(c)
out = []
for f in range(len(s), 0, -1): # most frequent first
for c in buckets[f]:
out.append(c * f)
return "".join(out)Common mistakes
- Writing each character once instead of
counttimes. - Sorting the string itself with a comparator that calls
countfor every comparison. - Expecting one exact answer from LeetCode's examples when ties are free there.