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 x appears before character y in order, then x must appear before y in your result
  • Characters in s that don't appear in order can be placed anywhere
  • All characters from order are 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
๐Ÿ“š Custom Sort String - Library AnalogyMessy shelf (original string s = "abcd"):abcdPriority system (order = "cba"):c: 1stb: 2nda: 3rdStep 1: Count books โ†’ {a:1, b:1, c:1, d:1}Counting complete โœ“Step 2: Organized shelf (result = "cbad"):cbadโ† not in priority๐Ÿ’ก Key InsightInstead of sorting (expensive),we use the given priority orderto directly place items.Time: O(n + m) vs O(n log n)Space: O(k) for counting
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.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
32.0K Views
Medium Frequency
~15 min Avg. Time
1.5K 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