medium +15 pts

Custom Sort String

Reorder characters by a custom priority order with stable sorting.

Write a function `custom_sort_string(order: str, s: str) -> str` that returns a permutation of `s` such that the characters which appear in `order` are placed first, arranged in the same relative sequence as they appear in `order`. All characters not present in `order` should come after those, preserving their original order in `s`. The sorting must be stable: for characters that do not appear in `order`, their relative order in `s` must be maintained. Examples: - custom_sort_string("cba", "abcd") -> "cbad" (c and b come first as per order, then a, then d because d is not in order). - custom_sort_string("kqep", "pekeq") -> "kqeep" (characters in order are placed as k,q,e; remaining: e, p? Actually implement according to definition). Verify with provided examples. Implement exactly the function signature above. Do not use external libraries.

Constraints

1 <= len(s) <= 1000 All characters are lowercase English letters. len(order) can be up to 26. Every character in order is unique.

Example

>>> custom_sort_string("cba", "abcd")
'cbad'
>>> custom_sort_string("kqep", "pekeq")
'kqeep'
>>> custom_sort_string("abc", "cba")
'cb'? Wait "cba" has a,b,c? Actually order abc, s=cba -> all characters in order, so return 'abc'? Let's see: order 'abc', s 'cba' -> expected 'abc'? That is not stable? Actually the definition: characters that appear in order are placed first in order of order; all others appended stable. Here all characters appear in order, so return 'abc'.
>>> custom_sort_string("", "abc")
'abc'
15 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Create a mapping from each character to its index in order.
Partition s into two lists: those in order and those not.
Sort the in-order characters by their index in order; keep the rest unchanged.
Concatenate both parts.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.