Custom Sort String

You are given two strings `order` and `s`. All the characters of `order` are unique and were sorted in some custom order. Permute the characters of `s` so that they match that custom order: if `x` comes before `y` in `order`, then `x` must come before `y` in the result. Characters of `s` that do not appear in `order` may go anywhere. Return any permutation of `s` that satisfies this.

30:00

Custom Sort String
medium
Free written solution
Topics
Companies

You are given two strings order and s. All the characters of order are unique and were sorted in some custom order. Permute the characters of s so that they match that custom order: if x comes before y in order, then x must come before y in the result. Characters of s that do not appear in order may go anywhere. Return any permutation of s that satisfies this.

Example 1:
Input: {"order":"cba","s":"abcd"}
Output: cbad
Constraints:
  • 1≤order.length≤261 \leq \text{order.length} \leq 26

  • 1≤s.length≤2001 \leq \text{s.length} \leq 200

  • order and s consist of lowercase English letters.

  • All the characters of order are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"order":"cba","s":"abcd"}

order "cba" ranks the letters. Tally the letters of s, then pour the bins out in that rank.

order (rank left to right)

c

0

b

1

a

2

s

a
b
c
d

count bins

c

0

rank 0

b

0

rank 1

a

0

rank 2

d

0

no rank

output

empty

Variables
VariableValue
ordercba
sabcd
DepthFunction Call
Stack empty
0/10