Skip to content
Problem 791 · LeetCode 791(opens in a new tab)

Custom Sort String

MediumHash tables

You are given two strings of lower-case letters. order lists some letters, each at most once, in a custom order. s is the string to rearrange.

Rearrange the letters of s so that whenever two letters both appear in order, the one that comes first in order also comes first in the result. Letters of s that are not in order can go anywhere. Return any rearrangement that follows this rule.

Example 1

Input:  order = "tba", s = "abate"
Output: "tbaae"
Why:    t, then b, then both a's; e is not in order
2 more examples and the constraints

Example 2

Input:  order = "xyz", s = "zoo"
Output: "zoo"
Why:    only z is in order; "ooz" is also fine

Example 3

Input:  order = "kq", s = "qqk"
Output: "kqq"
Why:    k comes before q in order

Constraints

  • 1 ≤ length of order ≤ 26, with no repeated letters
  • 1 ≤ length of s ≤ 200
  • Both strings hold only lower-case English letters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort with a rank keyO(n log n)
  2. Count, then write in orderO(n + m)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 200 lettersVerdict
Sort with a rank keyO(n log n)
Short and fine at this size
Count, then write in orderO(n + m)
Best; no sort at all

n = length of s, m = length of order.

Edge cases to test

  • No letter of s is in order. "xyz" and "pop": any rearrangement of pop is fine.
  • Every letter of s is in order. Then the answer is fully fixed, as in "kq" and "qqk".
  • Repeated letters. All copies of a letter must sit together in its slot, not just one.
  • Order letters missing from s. They are simply written zero times.
  • s is one letter. Return it unchanged.

Common mistakes

  • Writing each order letter once instead of as many times as it appears in s.
  • Forgetting the letters that are not in order, so the answer is shorter than s.
  • Writing order letters twice: once in the order pass and again with the leftovers.

How to talk through it

  1. 1Clarify. Where may letters missing from order go? Can s repeat letters? Is any valid answer accepted?
  2. 2Give the simple version. Sort s by each letter's index in order, with 26 for the others.
  3. 3Notice the small alphabet. Only 26 keys, so counting beats sorting.
  4. 4Code the count. Count s, write order letters by their counts, then the leftovers.
  5. 5Test out loud. Run a case with repeated letters and one with letters outside order.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?