Skip to main content
Back to problems
Leetcode
Medium
Hash Maps
Strings
Sorting
Custom Sort String

Reorder the characters of one string so they follow the relative order specified by another string.

Acceptance 0%
Problem Statement

Custom Sort String

You are given two strings, order and text.

The string order contains distinct characters that define a custom ranking from left to right. Reorder the characters in text so that:

  1. Characters that appear in order come first, following the order given by order.
  2. Characters not present in order may appear afterward in any order.
  3. The result must contain exactly the same multiset of characters as text.

Return any valid reordered string.

Notes

  • If a character appears multiple times in text, all of its occurrences must be kept.
  • Characters not listed in order can be placed arbitrarily after the ordered characters.
  • The custom order applies only to characters present in order; all other characters are treated as lower priority than any ordered character.

Input Format

  • order: a string of distinct characters defining the custom order.
  • text: the string to reorder.

Both strings consist of lowercase English letters unless otherwise stated.

Output Format

Return a string containing the same characters as text, arranged to respect the custom order.

Constraints

  • 1 <= order.length <= 26
  • 1 <= text.length <= 20000
  • order contains distinct characters.
  • text contains only lowercase English letters.
Examples
Sample cases returned by the problem API.

Example 1

Input

order = "cba", text = "abcd"

Output

"cbad"

Explanation

Characters c, b, and a must appear first in that order. The remaining character d can be placed afterward.

Example 2

Input

order = "bcafg", text = "abcd"

Output

"bcad"

Explanation

b, c, and a appear in the custom order. d is not in order, so it is appended at the end.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.