506/670

506. Custom Sort String

Medium

Your function receives two lowercase strings: order, whose characters are all distinct, and s. Rearrange the characters of s to respect the ranking defined by order: whenever letter x comes before letter y in order, every copy of x must appear before every copy of y in the result.

So the answer is unique, produce this canonical form: first all characters of s that appear in order, arranged by their order ranking (equal letters grouped together); then every character of s that does not appear in order, appended at the end in the same relative order they had in s. Return the rearranged string.

Example 1:

Input: order = "cba", s = "abcd"

Output: "cbad"

Explanation: order ranks c before b before a, so those letters of s are emitted as "cba". The letter d is not in order, so it goes at the end, giving "cbad".

Example 2:

Input: order = "kqep", s = "pekeq"

Output: "kqeep"

Explanation: Following order k, q, e, p: one k, one q, both e's, then one p — "kqeep". Every letter of s appears in order, so nothing is appended.

Constraints:

  • 1 ≤ order.length ≤ 26, all characters distinct
  • 1 ≤ s.length ≤ 10⁴
  • order and s contain only lowercase English letters

Hints:

This is sorting under a custom priority: each letter's key is its index in order. What key should a letter that is missing from order get so that it lands after every ranked letter — and what property must your sort have so ties keep their original relative order?

The alphabet has only 26 letters, so you can skip comparison sorting entirely: count every letter of s, then walk order emitting each of its letters count times, and finally scan s once more appending the letters that order does not mention.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: order = "cba", s = "abcd"

Expected output: "cbad"