Show problems as
Classic problem #791MediumHash TableStringSorting

Custom Sort String

Real-world version: Rearranging a Label to a Given Letter Order
Tracked in this browser only
Read Custom Sort String on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A letter order is given as order, a string of distinct lowercase letters, and a label as s.

Rearrange the letters of s so that any two letters both appearing in order come in the same relative order as they do there. Letters of s not appearing in order all come after those that do, arranged alphabetically among themselves.

Return the rearranged label. Every letter of s is kept, repeats included.

Examples

Example 1

Input
order = "fedcba", s = "abcdefghij"
Output
"fedcbaghij"

The order reverses the first six letters, so those come out backwards, and the four letters not named there follow alphabetically.

Example 2

Input
order = "ba", s = "aabbcc"
Output
"bbaacc"

The order asks for b before a, so both b's come first, then both a's, and the unnamed c's follow.

Example 3

Input
order = "abc", s = "zyx"
Output
"xyz"

None of the label's letters are named in the order, so they simply come out alphabetically.

Constraints

  • 1 <= order.length <= 26
  • 1 <= s.length <= 200
  • order and s consist of lowercase English letters only
  • The letters of order are all different

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def custom_sort_string(order: str, s: str) -> str:
Java
public String customSortString(String order, String s)