Custom Sort String - Problem
Imagine you have your own custom alphabet where letters are ordered differently than the standard A-Z sequence. You're given a string order that represents this custom alphabet ordering, and another string s containing characters you need to sort.
Your task: Rearrange all characters in string s to follow the custom ordering defined by order.
Key Rules:
- If character
xappears before characteryinorder, thenxmust appear beforeyin your result - Characters in
sthat don't appear inordercan be placed anywhere - All characters from
orderare unique
Example: If order = "cba" and s = "abcd", then c should come first, then b, then a, and d can go anywhere since it's not in the custom order.
Input & Output
example_1.py โ Basic Custom Sort
$
Input:
order = "cba", s = "abcd"
โบ
Output:
"cbad"
๐ก Note:
Characters 'c', 'b', 'a' follow the custom order. Character 'd' is not in the custom order, so it can be placed anywhere (here at the end).
example_2.py โ Multiple Same Characters
$
Input:
order = "cbafg", s = "abcd"
โบ
Output:
"cbad"
๐ก Note:
Even though the order string is longer, we only sort characters that exist in string s. The result follows the custom priority: cโbโa, with d at the end.
example_3.py โ Duplicate Characters
$
Input:
order = "kqep", s = "pekeq"
โบ
Output:
"kqeep"
๐ก Note:
All characters from s exist in order. Following the custom priority kโqโeโp, we get k(1), q(1), e(2), p(1) = "kqeep".
Constraints
- 1 โค order.length โค 26
- 1 โค s.length โค 1000
- order and s consist of lowercase English letters only
- All characters of order are unique
Visualization
Tap to expand
Understanding the Visualization
1
Count Your Books
First, count how many of each book type you have on your current messy shelf
2
Follow Priority Order
Place books on the new shelf following your custom priority list
3
Add Remaining
Any books not in your priority list go at the end
Key Takeaway
๐ฏ Key Insight: By counting character frequencies first, then following the custom order to build the result, we avoid expensive sorting operations and achieve optimal O(n + m) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code