Sort a string according to the order defined by another string | Python3 program to sort a string according to the order defined by a pattern string ; Sort str according to the order defined by pattern . ; Create a count array store count of characters in str . ; Count number of occurrences of each character in str . ; 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 . ; Driver code
MAX_CHAR = 26 NEW_LINE def sortByPattern ( str , pat ) : NEW_LINE INDENT global MAX_CHAR NEW_LINE count = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT count [ ord ( str [ i ] ) - 97 ] += 1 NEW_LINE DEDENT index = 0 ; NEW_LINE str = " " NEW_LINE for i in range ( 0 , len ( pat ) ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < count [ ord ( pat [ i ] ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT str += pat [ i ] NEW_LINE j = j + 1 NEW_LINE index += 1 NEW_LINE DEDENT DEDENT return str NEW_LINE DEDENT pat = " bca " NEW_LINE str = " abc " NEW_LINE print ( sortByPattern ( str , pat ) ) NEW_LINE