I saw this in an interview question ,
Given a sorting order string, you are asked to sort the input string based on the given sorting order string.
for example if the sorting order string is dfbcae
and the Input string is abcdeeabc
the output should be dbbccaaee.
any ideas on how to do this , in an efficient way ?
Here’s a nice easy to understand algorithm that has decent algorithmic complexity.
For each character in the sort order string
This is
O(n*m), wherenis the length of the string to be sorted andmis the length of the sort order string. We’re able to beat the lower bound on comparison based sorting because this algorithm doesn’t really use comparisons. Like Counting Sort it relies on the fact that you have a predefined finite external ordering set.Here’s some psuedocode: