# Custom Sort String in C++

C++Server Side ProgrammingProgramming

Suppose we have S and T two strings these are composed of lowercase letters. In S, no letter occurs more than once. S was sorted in some custom order previously. We have to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x will occur before y in the returned string.

So if the S = “cba” and T = “abcd”, then the output will be “cbad”. Here "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". As "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.

To solve this, we will follow these steps −

• set ret as empty string

• define a map m, and store the frequency of each character present in T into m

• for i in range 0 to size of S – 1

• x := S[i]

• for j in range 0 to m[x] – 1

• ret := ret + x

• m[x] := 0

• for each pair it in m −

• if value of it is > 0, then

• for i in range 0 to value of it – 1

• ret := ret concatenate key of it

• return ret

## Example(C++)

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string customSortString(string S, string T) {
string ret = "";
unordered_map <char, int> m;
for(int i = 0; i < T.size(); i++){
m[T[i]]++;
}
for(int i = 0; i < S.size(); i++){
char x = S[i];
for(int j = 0; j < m[x]; j++){
ret += x;
}
m[x] = 0;
}
unordered_map <char, int> :: iterator it = m.begin();
while(it != m.end()){
if(it->second > 0){
for(int i = 0; i < it->second; i++)ret += it->first;
}
it++;
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.customSortString("cba", "abcd"));
}

## Input

"cba"
"abcd"

## Output

cbad