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 INPUT order = "cba" c b a 1st 2nd 3rd s = "abaccaba" a b a c c a b a Character Count: a: 4 b: 2 c: 2 ALGORITHM STEPS 1 Count Characters Build frequency map of s 2 Process Order String Iterate through 'order' 3 Build Result Append chars per order 4 Add Remaining Append unordered chars Building Result: order[0]='c' --> "cc" order[1]='b' --> "ccbb" order[2]='a' --> "ccbbaaaa" No remaining chars! FINAL RESULT Sorted String: c c b b a a a a Output: "ccbbaaaa" OK - Verified! Order Preserved: 'c' comes before 'b' -- OK 'c' comes before 'a' -- OK 'b' comes before 'a' -- OK All chars accounted for Length: 8 = 8 Key Insight: Use a frequency map to count each character in s, then iterate through 'order' string to build the result by appending characters in the specified order. This achieves O(n) time complexity where n is the length of s. Characters not in 'order' can be appended at the end in any order. TutorialsPoint - Custom Sort String | Optimal Solution (Counting Sort Approach)
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