Custom Sort String - Problem
You are given two strings order and s. All characters in order are unique and represent a custom sorting order.
Your task is to permute the characters of string s so that they follow the custom order defined by order.
More specifically:
- If character
xappears before characteryinorder, thenxshould appear beforeyin the result string - Characters in
sthat don't appear inordercan be placed anywhere in the result
Return any valid permutation of s that satisfies this property.
Input & Output
Example 1 — Basic Custom Order
$
Input:
order = "cba", s = "abaccaba"
›
Output:
"ccbbaaaa"
💡 Note:
Characters must follow order c→b→a. We have 2 c's, 2 b's, and 4 a's in s. Following the custom order: cc + bb + aaaa = "ccbbaaaa"
Example 2 — Extra Characters
$
Input:
order = "cbafg", s = "abaccaba"
›
Output:
"ccbbaaaa"
💡 Note:
String s contains only characters c, b, a which are all in order. Result follows c→b→a priority: "ccbbaaaa"
Example 3 — Characters Not in Order
$
Input:
order = "kqep", s = "pekeq"
›
Output:
"kqeep"
💡 Note:
Following order k→q→e→p: k(1) + q(1) + ee(2) + p(1) = "kqeep". All characters from s appear in order.
Constraints
- 1 ≤ order.length ≤ 26
- 1 ≤ s.length ≤ 200
- order and s consist of lowercase English letters only
- All characters of order are unique
Visualization
Tap to expand
Understanding the Visualization
1
Input
Custom order and string to rearrange
2
Process
Rearrange characters following custom priority
3
Output
String with characters sorted by custom order
Key Takeaway
🎯 Key Insight: Count character frequencies first, then build result following the custom order sequence
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code