Reorder the characters of one string so they follow the relative order specified by another string.
Custom Sort String
You are given two strings, order and text.
The string order contains distinct characters that define a custom ranking from left to right. Reorder the characters in text so that:
- Characters that appear in
ordercome first, following the order given byorder. - Characters not present in
ordermay appear afterward in any order. - The result must contain exactly the same multiset of characters as
text.
Return any valid reordered string.
Notes
- If a character appears multiple times in
text, all of its occurrences must be kept. - Characters not listed in
ordercan be placed arbitrarily after the ordered characters. - The custom order applies only to characters present in
order; all other characters are treated as lower priority than any ordered character.
Input Format
order: a string of distinct characters defining the custom order.text: the string to reorder.
Both strings consist of lowercase English letters unless otherwise stated.
Output Format
Return a string containing the same characters as text, arranged to respect the custom order.
Constraints
1 <= order.length <= 261 <= text.length <= 20000ordercontains distinct characters.textcontains only lowercase English letters.
Example 1
Input
order = "cba", text = "abcd"
Output
"cbad"
Explanation
Characters c, b, and a must appear first in that order. The remaining character d can be placed afterward.
Example 2
Input
order = "bcafg", text = "abcd"
Output
"bcad"
Explanation
b, c, and a appear in the custom order. d is not in order, so it is appended at the end.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.