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 x appears before character y in order, then x should appear before y in the result string
  • Characters in s that don't appear in order can 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
Custom Sort String: Rearrange by PriorityOrder: "cba" (custom priority)String: "abaccaba"abaccabaOriginal string (mixed order)ccbbaaaaSorted by custom order: c→b→a
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
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
182.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen