Sort Characters by Frequency solution explained
Sort Characters by Frequency is solved by counting each character, dropping characters into buckets indexed by their count, and reading the buckets from the highest count down, writing each character as many times as it appears. That runs in O(n) time; sorting the distinct characters by count instead costs O(n + k log k) and is also accepted.
By Evin JohnPublished 6 min read
The problem, restated
Given a string, return a rearrangement of it where characters that appear more often come before characters that appear less often. All copies of one character must sit next to each other. When two characters have the same count, either may come first. Upper and lower case letters are different characters, and digits can appear too.
| Input | One valid output | Other valid outputs |
|---|---|---|
| banana | aaannb | None; the counts 3, 2, 1 are all different. |
| Aabb | bbAa | bbaA, since 'A' and 'a' are separate and tie at one each. |
| committee | mmttee + c, o, i in any order | Any order of the three pairs, then any order of the three singles. |
| 1122x | 1122x | 2211x |
| q | q | Nothing else. |
Clarify the character set. If the input can include capitals, digits and maybe spaces, a 26-slot array will not do, and a hash map or a 128-slot ASCII array is the right container. Also confirm that ties can come out in any order, which nearly every version allows.
What this checks
It is a counting problem with a twist in the output: you are sorting groups, not characters. Interviewers watch for the interleaving bug, and for whether you know the bucket trick for sorting by a bounded integer. It also leads naturally into top-k questions, where a heap becomes the better tool.
A simple first version: sort with a tie-break
Count every character, then sort the characters of the string by negative count, so higher counts come first. Add the character itself as a second key. Without it, two letters that share a count would only be grouped if they already happened to be grouped in the input. With it, equal counts are ordered by character, which keeps every block contiguous.
from collections import Counter
def frequency_order_sorted(text):
counts = Counter(text)
return "".join(sorted(text, key=lambda ch: (-counts[ch], ch)))A slightly better version sorts only the distinct characters. Counter's most_common does exactly that, and then you write each character times its count. That costs O(n) to count plus O(k log k) to sort k distinct characters.
Main approach: buckets indexed by count
Counts are whole numbers between 1 and n, the string length. That makes them perfect bucket keys. Make n + 1 empty lists. Put each distinct character into the list at its count. Then walk the lists from n down to 1 and, for each character found, write it count times. No comparison sort is involved, so the whole thing is linear.
from collections import Counter
def frequency_order(text):
counts = Counter(text)
buckets = [[] for _ in range(len(text) + 1)]
for ch, n in counts.items():
buckets[n].append(ch)
pieces = []
for n in range(len(text), 0, -1):
for ch in buckets[n]:
pieces.append(ch * n)
return "".join(pieces)function frequencyOrder(text) {
const counts = new Map();
for (const ch of text) counts.set(ch, (counts.get(ch) || 0) + 1);
const buckets = Array.from({ length: text.length + 1 }, () => []);
for (const [ch, n] of counts) buckets[n].push(ch);
const pieces = [];
for (let n = text.length; n > 0; n--) {
for (const ch of buckets[n]) pieces.push(ch.repeat(n));
}
return pieces.join("");
}Trace banana. Counts are b:1, a:3, n:2. Bucket 3 holds a, bucket 2 holds n, bucket 1 holds b. Reading from 6 down, the empty buckets are skipped and the output is aaa, nn, b joined: aaannb.
One note for JavaScript: iterating a string with for...of walks code points, while text.length counts UTF-16 units. For ASCII input these agree. If the interviewer allows emoji or other characters outside the basic plane, the bucket array is simply a little larger than needed, which is harmless.
Cost of each option
| Option | Time | Extra space |
|---|---|---|
| Sort all characters with a tie-break | O(n log n) | O(n) |
| Sort distinct characters by count | O(n + k log k) | O(n + k) |
| Buckets indexed by count | O(n) | O(n) for the buckets and output |
For ASCII text, k is bounded by 128, so the middle option is linear in practice too. The bucket version is the one to name when the interviewer asks for a strict linear bound.
Inputs worth testing
- An empty string returns an empty string.
- A single repeated character returns the input unchanged.
- All characters distinct: every count is 1 and any order is valid.
- Mixed case, such as Aabb: 'A' and 'a' are separate entries.
- Two characters with equal counts that are interleaved in the input, like abab: the output must be aabb or bbaa, never abab.
Typical mistakes
- Sorting by count with no tie-break. For abab, a stable sort keeps abab, which breaks the grouping rule.
- Reading the buckets from 1 upward and returning the least frequent characters first.
- Using a 26-letter array on input that contains capitals or digits.
- Lowercasing the input to simplify counting, which merges characters the problem treats as different.
- Testing against one expected string. Ties make several outputs correct, so check the grouping and the counts instead.
Follow-ups
- Only the k most frequent characters. Keep a min-heap of size k over the counts for O(n + k' log k) where k' is the number of distinct characters, or read the buckets from the top until you have k.
- Ties must break alphabetically. Sort each bucket before writing it, or use the tie-break sort.
- Sort words in a document by frequency. Same idea with a word counter; the bucket array is sized by the number of words.
Saying it well
Fictional example
- Candidate
- I count every character with a hash map, since the input can mix cases and digits.
- Candidate
- Counts are between 1 and n, so I put characters into buckets by count and read from the top. Each character is written as one block, so equal counts can never interleave.
- Candidate
- That is O(n) time and O(n) space. If you only want the top few, a heap of size k is the better fit.
Other problems in this batch
Custom Sort String is the closest relative: count first, then write characters out in a chosen order. Lemonade Change keeps the counting habit but swaps strings for a till of bills. Bucket sort and hash map costs are covered on the data structure interview questions page.
Working through it with Natively
When you drill problems like this, Natively can read the statement from a screenshot, suggest a pattern and write a draft solution, useful for comparing against your own bucket version afterwards. It also transcribes your mock interview on your computer, so you can confirm you called out the interleaving bug before the interviewer did. Find out more about an AI interview assistant for Mac and Windows.
Questions people ask
How do you solve Sort Characters by Frequency?
Count each character with a hash map, place characters into buckets indexed by their count, then read the buckets from the highest count down and write each character as many times as it appears.
What is the time complexity of the bucket approach?
O(n) time and O(n) space. Counts never exceed the string length, so the buckets replace a comparison sort.
Why does sorting by count alone give wrong answers?
Two characters with the same count can stay interleaved, for example abab. Add the character as a tie-break key, or write each character's whole block at once.
Does Sort Characters by Frequency treat uppercase and lowercase as different?
In the usual version, yes. 'A' and 'a' are counted separately, so use a hash map or an ASCII-sized array rather than a 26-letter array.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
