Sort Characters By Frequency
Sort Characters By Frequency is a medium heaps problem solved with the top k / kth largest / smallest pattern.
The best approach, optimal (bucket sort by frequency), runs in O(n) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (sort every character with a frequency comparator) up.
Problem
Given a string s, rearrange its characters so that they are ordered by how often they appear, most frequent first. All copies of the same character must sit next to each other.
Upper and lower case letters count as different characters. If two characters appear the same number of times, either one may come first; any valid arrangement is accepted.
Examples
Example 1
- Input
s = "banana"- Output
"aaannb"- Why
- 'a' appears 3 times, 'n' twice and 'b' once, so the a's come first, then the n's, then the b.
Example 2
- Input
s = "xY7Y7Y"- Output
"YYY77x"- Why
- 'Y' appears 3 times and '7' twice. Upper and lower case letters are different characters.
Example 3
- Input
s = "pqr"- Output
"pqr"- Why
- Every character appears once, so any order of the three is accepted, for example "rqp".
Constraints
1 <= s.length <= 5 * 10^5scontains only English letters (upper and lower case) and digits.- When several characters share a frequency, any order between their groups is accepted.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (sort every character with a frequency comparator) | O(n log n) | O(n) |
| Max-heap of distinct characters | O(n + k log k) | O(n + k) |
| Optimal (bucket sort by frequency) | O(n) | O(n) |
1Brute force (sort every character with a frequency comparator)
O(n log n)Sorting all n characters dominates.O(n)The array of n characters being sorted.Count each character, then sort all n characters by (count descending, character ascending). Ties are broken by the character so equal characters stay together.
- Count the frequency of each character.
- Put the n characters into an array and sort it by count descending, then by character.
- Join the sorted characters into the answer.
class Solution {
public String frequencySort(String s) {
int[] count = new int[128];
for (char c : s.toCharArray()) count[c]++;
Character[] chars = new Character[s.length()];
for (int i = 0; i < s.length(); i++) chars[i] = s.charAt(i);
Arrays.sort(chars, (a, b) -> count[a] != count[b] ? count[b] - count[a] : a - b);
StringBuilder sb = new StringBuilder();
for (char c : chars) sb.append(c);
return sb.toString();
}
}class Solution:
def frequencySort(self, s: str) -> str:
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
chars = sorted(s, key=lambda c: (-count[c], c))
return "".join(chars)class Solution {
public:
string frequencySort(string s) {
vector<int> count(128, 0);
for (char c : s) count[c]++;
string chars = s;
sort(chars.begin(), chars.end(), [&](char a, char b) {
if (count[a] != count[b]) return count[a] > count[b];
return a < b;
});
return chars;
}
};function frequencySort(s) {
const count = new Map();
for (const c of s) count.set(c, (count.get(c) || 0) + 1);
const chars = s.split("");
chars.sort((a, b) => {
if (count.get(a) !== count.get(b)) return count.get(b) - count.get(a);
return a < b ? -1 : a > b ? 1 : 0;
});
return chars.join("");
}2Max-heap of distinct characters
O(n + k log k)Counting and writing are O(n); the heap holds k <= 62 distinct characters.O(n + k)The heap has k entries and the output has n characters.There are at most 62 distinct characters. Push each (character, count) pair into a max-heap ordered by count and pop them one by one, writing each character count times.
- Count the frequency of each character.
- Push every character that appears into a max-heap keyed by count (ties by character).
- Pop the heap; append the popped character count times.
class Solution {
public String frequencySort(String s) {
int[] count = new int[128];
for (char c : s.toCharArray()) count[c]++;
PriorityQueue<Character> heap = new PriorityQueue<>(
(a, b) -> count[a] != count[b] ? count[b] - count[a] : a - b);
for (char c = 0; c < 128; c++) {
if (count[c] > 0) heap.offer(c);
}
StringBuilder sb = new StringBuilder();
while (!heap.isEmpty()) {
char c = heap.poll();
for (int i = 0; i < count[c]; i++) sb.append(c);
}
return sb.toString();
}
}class Solution:
def frequencySort(self, s: str) -> str:
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
heap = [(-cnt, c) for c, cnt in count.items()]
heapq.heapify(heap)
parts = []
while heap:
neg, c = heapq.heappop(heap)
parts.append(c * (-neg))
return "".join(parts)class Solution {
public:
string frequencySort(string s) {
vector<int> count(128, 0);
for (char c : s) count[c]++;
auto cmp = [&](char a, char b) {
if (count[a] != count[b]) return count[a] < count[b];
return a > b;
};
priority_queue<char, vector<char>, decltype(cmp)> heap(cmp);
for (int c = 0; c < 128; c++) {
if (count[c] > 0) heap.push((char)c);
}
string out;
while (!heap.empty()) {
char c = heap.top();
heap.pop();
out.append(count[c], c);
}
return out;
}
};function frequencySort(s) {
const count = new Map();
for (const c of s) count.set(c, (count.get(c) || 0) + 1);
// at most 62 distinct characters: a small binary heap keyed by count
const heap = [];
const better = (a, b) => count.get(a) !== count.get(b) ? count.get(a) > count.get(b) : a < b;
const push = (x) => {
heap.push(x);
let i = heap.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!better(heap[i], heap[p])) break;
[heap[i], heap[p]] = [heap[p], heap[i]];
i = p;
}
};
const pop = () => {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let best = i;
if (l < heap.length && better(heap[l], heap[best])) best = l;
if (r < heap.length && better(heap[r], heap[best])) best = r;
if (best === i) break;
[heap[i], heap[best]] = [heap[best], heap[i]];
i = best;
}
}
return top;
};
for (const c of count.keys()) push(c);
const parts = [];
while (heap.length > 0) {
const c = pop();
parts.push(c.repeat(count.get(c)));
}
return parts.join("");
}3Optimal (bucket sort by frequency)
O(n)Counting, filling buckets and writing the output are each linear.O(n)n + 1 buckets plus the output string.A frequency is between 1 and n, so use n + 1 buckets: bucket f holds the characters that appear exactly f times. Walking the buckets from n down to 1 lists the characters by decreasing frequency without any comparison sort.
- Count the frequency of each character.
- Put each character into bucket[count].
- For f from n down to 1, append each character in bucket[f] exactly f times.
class Solution {
public String frequencySort(String s) {
int n = s.length();
int[] count = new int[128];
for (char c : s.toCharArray()) count[c]++;
List<List<Character>> buckets = new ArrayList<>();
for (int i = 0; i <= n; i++) buckets.add(new ArrayList<>());
for (char c = 0; c < 128; c++) {
if (count[c] > 0) buckets.get(count[c]).add(c);
}
StringBuilder sb = new StringBuilder();
for (int f = n; f >= 1; f--) {
for (char c : buckets.get(f)) {
for (int i = 0; i < f; i++) sb.append(c);
}
}
return sb.toString();
}
}class Solution:
def frequencySort(self, s: str) -> str:
n = len(s)
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
buckets = [[] for _ in range(n + 1)]
for c in sorted(count):
buckets[count[c]].append(c)
parts = []
for f in range(n, 0, -1):
for c in buckets[f]:
parts.append(c * f)
return "".join(parts)class Solution {
public:
string frequencySort(string s) {
int n = s.size();
vector<int> count(128, 0);
for (char c : s) count[c]++;
vector<vector<char>> buckets(n + 1);
for (int c = 0; c < 128; c++) {
if (count[c] > 0) buckets[count[c]].push_back((char)c);
}
string out;
for (int f = n; f >= 1; f--) {
for (char c : buckets[f]) out.append(f, c);
}
return out;
}
};function frequencySort(s) {
const n = s.length;
const count = new Map();
for (const c of s) count.set(c, (count.get(c) || 0) + 1);
const buckets = Array.from({ length: n + 1 }, () => []);
for (const c of [...count.keys()].sort()) buckets[count.get(c)].push(c);
const parts = [];
for (let f = n; f >= 1; f--) {
for (const c of buckets[f]) parts.push(c.repeat(f));
}
return parts.join("");
}Edge cases to test
- A single character
- All characters the same
- Every character distinct (any permutation is valid)
- 'A' and 'a' both present: they are counted separately
Hints
Hint 1
First count how often each character appears.
Hint 2
Each character must be written as one contiguous block, longest block first. How do you order the distinct characters by count?
Hint 3
A count is at most n. Can you put characters into buckets indexed by their count instead of sorting?
FAQ
What is the best time complexity for Sort Characters By Frequency?
Optimal (bucket sort by frequency) runs in O(n) time and O(n) extra space. Counting, filling buckets and writing the output are each linear.
Which pattern does Sort Characters By Frequency use?
It is a heaps problem that uses the top k / kth largest / smallest pattern. Other problems with the same pattern: Kth Largest Element in an Array, Kth Largest Element in a Stream, Top K Frequent Words.
Is there a brute force solution for Sort Characters By Frequency?
Yes. Brute force (sort every character with a frequency comparator) takes O(n log n) time and O(n) space. Count each character, then sort all n characters by (count descending, character ascending).
Which edge cases should I test for Sort Characters By Frequency?
A single character; All characters the same; Every character distinct (any permutation is valid); 'A' and 'a' both present: they are counted separately.