Skip to main content

Custom Sort String

Problem

You are given two strings order and s. All the words of order are unique and were sorted in some custom order previously.

Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.

Return any permutation of s that satisfies this property.

 

Example 1:

Input: order = "cba", s = "abcd"
Output: "cbad"
Explanation: 
"a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a". 
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.

Example 2:

Input: order = "cbafg", s = "abcd"
Output: "cbad"

 

Constraints:

  • 1 <= order.length <= 26
  • 1 <= s.length <= 200
  • order and s consist of lowercase English letters.
  • All the characters of order are unique.

Solution

/**
* @param {string} S
* @param {string} T
* @return {string}
*/
var customSortString = function(S, T) {
map = {};
for (let i = 0; i < S.length; ++i) {
map[S[i]] = i;
}
t = T.split("");
return t.sort((a, b) => {
a = a in map ? map[a] : -1;
b = b in map ? map[b] : -1;
return a - b;
}).join("");
};

Store the indices of S by the value of their elements in a hashmap. Next, simply sort the characters in T by the stored values of the indices in map (if the character is not in map, use -1, this would push all non-specified elements to the front of the sorted string).