← Questions
Custom sort string: order characters by a given order
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Given an order string of distinct characters and a string s, rearrange s so that its characters that appear in order come first, grouped and arranged as order lists them. The characters of s that are not in order follow, in the order they had in s.
Interface
Unless you agree on a different interface with the interviewer, assume:
custom_sort(order: str, s: str) -> str
Example
custom_sort("cba", "abcd") -> "cbad"
custom_sort("kqep", "pekeq") -> "kqeep" # k, q, e, e, p
custom_sort("ba", "aabbcc") -> "bbaacc"
custom_sort("ab", "zaybxa") -> "aabzyx" # z, y, x keep their order from s
custom_sort("", "xyz") -> "xyz"
Constraints
- The characters of
orderare distinct. Either string may be empty. - O(len(order) + len(s)) time.
Clarifying questions
- Where do characters missing from
ordergo: at the end in their original order, or anywhere? - Can
srepeat characters? - Are uppercase and lowercase the same character?
- Is the alphabet ASCII or full Unicode?
What a strong answer covers
- A count of each character of
sthat appears inorder, and a separate buffer for the others in their original order. Then emitorderwith each character repeated by its count, followed by the buffer. - O(len(order) + len(s)) time, O(alphabet) space for the counts plus the output.
- Why a sort with a custom key works too (O(n log n)), and that only a stable sort keeps the rest in place.
- Unicode: iterate over code points (or grapheme clusters if needed) and key the counts by them.
- Tests: empty
order, emptys, characters oforderabsent froms, every character absent fromorder.
Follow-ups
- Case-insensitive ordering that still outputs the original characters.
- Check whether a list of words is sorted under a custom alphabet.
-
orderhas duplicates or conflicting rules.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding

