Open In App
Related Articles

Python | Sorting string using order defined by another string

Improve Article
Improve
Save Article
Save
Like Article
Like

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

Input : pat = "asbcklfdmegnot", str = "eksge" 
Output : str = "geeks"
(after sorting, str becomes "skeeg" and return its reverse)

Input : pat = "mgewqnasibkldjxruohypzcftv", str = "niocgd"
Output : str = "coding"

The idea is to first maintain a dictionary according to the index provided in Pattern and then passing the lambda function(which uses utility of dictionary) into the sort function. Below is the implementation of above idea. 

Python3




# Python program to sort a string and return
# its reverse string according to pattern string
 
# This function will return the reverse of sorted string
# according to the pattern
 
def sortbyPattern(pat, str):
 
    priority = list(pat)
 
    # Create a dictionary to store priority of each character
    myDict = { priority[i] : i for i in range(len(priority))}
 
    str = list(str)
 
    # Pass lambda function as key in sort function
    str.sort( key = lambda ele : myDict[ele])
 
    # Reverse the string using reverse()
    str.reverse()
 
    new_str = ''.join(str)
    return new_str
 
 
if __name__=='__main__':
    pat = "asbcklfdmegnot"
    str =  "eksge"
    new_str = sortbyPattern(pat, str)
    print(new_str)


Output:

geeks

Time Complexity: n*log(n) where n is the length of the string
Auxiliary Space: O(n) where n is length of string

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 27 Sep, 2022
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials