# Sort a string according to the order defined by another string

Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once.

Examples:

```Input  : pat = "bca", str = "abc"
Output : str = "bca"

Input  : pat = "bxyzca", str = "abcabcabc"
Output : str = "bbbcccaaa"

Input  : pat = "wcyuogmlrdfphitxjakqvzbnes", str = "jcdokai"
Output : str = "codijak"
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

The idea is to first count occurrences of all characters in str and store these counts in a count array. Then traverse pattern from left to right, and for each character pat[i], see how many times it appears in count array and copy this character these many times to str.

Below is the implementation of above idea.

## C++

 `// C++ program to sort a string according to the ` `// order defined by a pattern string ` `#include ` `using` `namespace` `std; ` `const` `int` `MAX_CHAR = 26; ` ` `  `// Sort str according to the order defined by pattern. ` `void` `sortByPattern(string& str, string pat) ` `{ ` `    ``// Create a count array store count of characters in str. ` `    ``int` `count[MAX_CHAR] = { 0 }; ` ` `  `    ``// Count number of occurrences of each character ` `    ``// in str. ` `    ``for` `(``int` `i = 0; i < str.length(); i++) ` `        ``count[str[i] - ``'a'``]++; ` ` `  `    ``// Traverse the pattern and print every characters ` `    ``// same number of times as it appears in str. This ` `    ``// loop takes O(m + n) time where m is length of ` `    ``// pattern and n is length of str. ` `    ``int` `index = 0; ` `    ``for` `(``int` `i = 0; i < pat.length(); i++) ` `        ``for` `(``int` `j = 0; j < count[pat[i] - ``'a'``]; j++) ` `            ``str[index++] = pat[i]; ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``string pat = ``"bca"``; ` `    ``string str = ``"abc"``; ` `    ``sortByPattern(str, pat); ` `    ``cout << str; ` `    ``return` `0; ` `} `

## Java

 `// Java program to sort a string according to the ` `// order defined by a pattern string ` ` `  `class` `GFG { ` ` `  `    ``static` `int` `MAX_CHAR = ``26``; ` ` `  `    ``// Sort str according to the order defined by pattern. ` `    ``static` `void` `sortByPattern(``char``[] str, ``char``[] pat) ` `    ``{ ` `        ``// Create a count array stor ` `        ``// count of characters in str. ` `        ``int` `count[] = ``new` `int``[MAX_CHAR]; ` ` `  `        ``// Count number of occurrences of ` `        ``// each character in str. ` `        ``for` `(``int` `i = ``0``; i < str.length; i++) { ` `            ``count[str[i] - ``'a'``]++; ` `        ``} ` ` `  `        ``// Traverse the pattern and print every characters ` `        ``// same number of times as it appears in str. This ` `        ``// loop takes O(m + n) time where m is length of ` `        ``// pattern and n is length of str. ` `        ``int` `index = ``0``; ` `        ``for` `(``int` `i = ``0``; i < pat.length; i++) { ` `            ``for` `(``int` `j = ``0``; j < count[pat[i] - ``'a'``]; j++) { ` `                ``str[index++] = pat[i]; ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``// Driver code ` `    ``public` `static` `void` `main(String args[]) ` `    ``{ ` `        ``char``[] pat = ``"bca"``.toCharArray(); ` `        ``char``[] str = ``"abc"``.toCharArray(); ` `        ``sortByPattern(str, pat); ` `        ``System.out.println(String.valueOf(str)); ` `    ``} ` `} ` ` `  `// This code has been contributed by 29AjayKumar `

## Python3

 `# Python3 program to sort a string according to  ` `# the order defined by a pattern string ` `MAX_CHAR ``=` `26` ` `  `# Sort str according to the order defined by pattern. ` `def` `sortByPattern(``str``, pat): ` `     `  `    ``global` `MAX_CHAR ` `     `  `    ``# Create a count array store count ` `    ``# of characters in str. ` `    ``count ``=` `[``0``] ``*` `MAX_CHAR  ` `     `  `    ``# Count number of occurrences of  ` `    ``# each character in str. ` `    ``for` `i ``in` `range` `(``0``, ``len``(``str``)): ` `        ``count[``ord``(``str``[i]) ``-` `97``] ``+``=` `1` `     `  `    ``# Traverse the pattern and print every characters ` `    ``# same number of times as it appears in str. This ` `    ``# loop takes O(m + n) time where m is length of ` `    ``# pattern and n is length of str. ` `    ``index ``=` `0``; ` `    ``str` `=` `"" ` `     `  `    ``for` `i ``in` `range` `(``0``, ``len``(pat)): ` `        ``j ``=` `0` `        ``while``(j < count[``ord``(pat[i]) ``-` `ord``(``'a'``)]):  ` `            ``str` `+``=` `pat[i] ` `            ``j ``=` `j ``+` `1` `            ``index ``+``=` `1` `     `  `    ``return` `str` ` `  `# Driver code ` `pat ``=` `"bca"` `str` `=` `"abc"` `print``(sortByPattern(``str``, pat)) ` ` `  `# This code is contributed by ihritik `

## C#

 `// C# program to sort a string according to the ` `// order defined by a pattern string ` `using` `System; ` ` `  `class` `GFG { ` ` `  `    ``static` `int` `MAX_CHAR = 26; ` ` `  `    ``// Sort str according to the order defined by pattern. ` `    ``static` `void` `sortByPattern(``char``[] str, ``char``[] pat) ` `    ``{ ` `        ``// Create a count array stor ` `        ``// count of characters in str. ` `        ``int``[] count = ``new` `int``[MAX_CHAR]; ` ` `  `        ``// Count number of occurrences of ` `        ``// each character in str. ` `        ``for` `(``int` `i = 0; i < str.Length; i++) { ` `            ``count[str[i] - ``'a'``]++; ` `        ``} ` ` `  `        ``// Traverse the pattern and print every characters ` `        ``// same number of times as it appears in str. This ` `        ``// loop takes O(m + n) time where m is length of ` `        ``// pattern and n is length of str. ` `        ``int` `index = 0; ` `        ``for` `(``int` `i = 0; i < pat.Length; i++) { ` `            ``for` `(``int` `j = 0; j < count[pat[i] - ``'a'``]; j++) { ` `                ``str[index++] = pat[i]; ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``// Driver code ` `    ``public` `static` `void` `Main(String[] args) ` `    ``{ ` `        ``char``[] pat = ``"bca"``.ToCharArray(); ` `        ``char``[] str = ``"abc"``.ToCharArray(); ` `        ``sortByPattern(str, pat); ` `        ``Console.WriteLine(String.Join(``""``, str)); ` `    ``} ` `} ` ` `  `/* This code contributed by PrinciRaj1992 */`

Output:

```bca
```

Time complexity : O(m + n) where m is length of pattern and n is length of str.

Exercise : In the above solution, it is assumed that pattern has all characters of str. Consider a modified version where pattern may not have all characters and the task is to put all remaining characters (in string but not in pattern) at the end. The remaining characters need to be put in alphabetically sorted order.

Hint : In the second loop, when increase index and put character in str, we can also decrease count at that time. And finally we traverse the count array to put remaining characters in alphabetically sorted order.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

3

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.