Custom Sort String solution explained
Custom Sort String is solved by counting every character of the text, writing out the characters named in the order string in that sequence with their full counts, and then appending whatever is left. That is O(n + m) time for a text of length n and an order of length m, and any placement of the unlisted characters is accepted.
By Evin JohnPublished 6 min read
What the problem says
You get two strings. The first, the order, lists some lowercase letters with no repeats; it defines a ranking. The second, the text, is any lowercase string. Rearrange the text so that whenever two letters both appear in the order, the one ranked earlier comes first in the output. Letters missing from the order have no rank and can sit anywhere. Return any arrangement that follows the rule.
| Order | Text | A valid output | Note |
|---|---|---|---|
| zyx | xyzaz | zzyxa | Both z's come before y, then x; the unranked 'a' could go anywhere. |
| dcb | abcd | dcba | Also valid: adcb, dacb, dcab. |
| pq | qqpr | pqqr | The 'r' is unranked. |
| k | mnop | mnop | No letter of the text is ranked, so any order passes. |
| abc | (empty) | (empty) | Nothing to arrange. |
Ask about two details. Does the judge accept any valid arrangement, or does it expect unranked letters at the end? And can the order contain letters that never appear in the text? Usually any valid answer is accepted and yes, the order may name absent letters.
Why interviewers like it
It is a quick test of two ideas that matter in bigger problems: sorting with a custom key, and replacing a sort with counting when the alphabet is small. A good answer offers the sort first because it is short and obviously right, then notices that counting is faster and just as simple.
First approach: sort with a rank key
Build a dictionary from each letter in the order to its index. Sort the characters of the text by that index, giving unranked letters a value past the end so they gather at the back. Python's sort is stable, so unranked letters keep their original relative order, which is a nice property even though it is not required.
def arrange_by_sort(order, text):
rank = {ch: i for i, ch in enumerate(order)}
tail = len(order)
return "".join(sorted(text, key=lambda ch: rank.get(ch, tail)))A slower variant you sometimes see scans the whole text once for every letter in the order, collecting matches. That is O(m · n) and also needs a final pass for unranked letters, so it has no advantage over the sort.
Main approach: count, then write out
The order already tells you the output sequence, so there is nothing to compare. Count how many times each letter appears in the text. Walk the order string, and for each letter write it as many times as it was counted, then remove it from the counts. Whatever remains in the counts is unranked; write those letters out too. Every character of the text is written exactly once.
from collections import Counter
def arrange_by_count(order, text):
counts = Counter(text)
pieces = []
for ch in order:
pieces.append(ch * counts.pop(ch, 0))
for ch, n in counts.items():
pieces.append(ch * n)
return "".join(pieces)function arrangeByCount(order, text) {
const counts = new Map();
for (const ch of text) counts.set(ch, (counts.get(ch) || 0) + 1);
const pieces = [];
for (const ch of order) {
if (counts.has(ch)) {
pieces.push(ch.repeat(counts.get(ch)));
counts.delete(ch);
}
}
for (const [ch, n] of counts) pieces.push(ch.repeat(n));
return pieces.join("");
}Trace order zyx with text xyzaz. The counts are x:1, y:1, z:2, a:1. Walking the order writes zz, then y, then x. The leftover count holds only a:1, so the output is zzyxa.
How the two compare
| Approach | Time | Extra space | When to choose it |
|---|---|---|---|
| One scan of the text per ranked letter | O(m · n) | O(n) output | Rarely; it is only shown for contrast |
| Sort by rank key | O(n log n + m) | O(n + m) | Fast to write and explain |
| Count and write out | O(n + m) | O(k) counts plus the output | Best bound; k is the number of distinct letters |
With lowercase letters only, k is at most 26 and m is at most 26, so the counting version is linear in the text. The output string itself takes O(n) in both languages, since strings cannot be edited in place.
Edge cases
- An empty text returns an empty string, whatever the order.
- An order with letters the text never uses: they simply contribute nothing.
- A text with no ranked letters: return it unchanged or in any order.
- Heavy repetition, such as one letter thousands of times: counting handles it in one step per character.
- An empty order: every letter is unranked, so the text itself is a valid answer.
Frequent errors
- Dropping unranked letters. The output must be a rearrangement of the whole text, so its length must match.
- Writing each ranked letter once instead of once per occurrence.
- Using indexOf on the order string inside a JavaScript sort comparator. It works, but every comparison costs O(m), so precompute a rank map.
- Comparing the output with one fixed expected string in tests. Several answers are valid, so check the rule instead.
- Assuming the order lists every letter of the text. It often does not.
Follow-up questions
- Unranked letters must go last. The counting version already does this; the sort version does too, because of the tail rank.
- Check whether a text is already sorted under a custom order. Map each letter to its rank and confirm the ranks never decrease, which is the idea behind checking words in an alien dictionary.
- Order is given as a list of words to sort instead of letters. Compare words by mapping each to a tuple of ranks and sorting by that tuple.
Talking through it
Fictional example
- Candidate
- The quick version sorts the text by each letter's position in the order, with unranked letters pushed to the end. That is n log n.
- Candidate
- But the order already spells out the output sequence, so I can count the text and write each ranked letter its number of times, then the leftovers. That is linear.
- Candidate
- Several outputs are valid, so in my tests I check that the result uses the same letters and that ranked letters never go backward.
More walkthroughs nearby
Sort Characters by Frequency uses the same count-then-write pattern with a different ordering rule, and Largest Time for Given Digits shows when trying every arrangement beats being clever. Hash maps and counting arrays are covered in the data structure interview questions.
Practice support from Natively
For practice, Natively can read a screenshot of a string problem, suggest an approach and draft code, which gives you something to compare against once your own version runs. Since it can also transcribe a mock interview on your computer, you can check afterwards whether you mentioned that more than one output is valid. There is more on an AI interview assistant for Mac and Windows.
Questions people ask
What is the optimal solution to Custom Sort String?
Count each character in the text. Walk the order string and write each listed character as many times as it was counted, then append the characters the order does not mention. It runs in O(n + m) time.
Where do characters that are not in the order go?
Anywhere. They have no rank, so any position is valid. Putting them at the end is the easiest choice and is what both the counting and the sorting versions do.
Can I solve Custom Sort String with a sort?
Yes. Map each letter of the order to its index and sort the text by that index, giving unlisted letters a value past the end. It is O(n log n) and easy to explain.
How should I test Custom Sort String?
Since several outputs are valid, check the rule: the output uses exactly the same letters as the text, and letters that appear in the order never go backward in rank.
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.
