All problems
0959MediumHash TableStringSorting

Rearranging a Label to a Given Letter Order

Tracked in this browser only
Write code

Trains the technique from

LeetCode 791Custom Sort String

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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