Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a string using another sorting order string [closed]

Tags:

string

sorting

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 ?

like image 662
Mouna Cheikhna Avatar asked Aug 05 '11 13:08

Mouna Cheikhna


People also ask

How do you sort a string by another string in Python?

In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .

How do you custom sort a string?

Custom Sort String in C++ 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”.

How do you sort strings in ascending order?

It means that the array sorts elements in the ascending order by using the sort() method, after that the reverseOrder() method reverses the natural ordering, and we get the sorted array in descending order.


1 Answers

The Counting Sort option is pretty cool, and fast when the string to be sorted is long compared to the sort order string.

  • create an array where each index corresponds to a letter in the alphabet, this is the count array
  • for each letter in the sort target, increment the index in the count array which corresponds to that letter
  • for each letter in the sort order string
    • add that letter to the end of the output string a number of times equal to it's count in the count array

Algorithmic complexity is O(n) where n is the length of the string to be sorted. As the Wikipedia article explains we're able to beat the lower bound on standard comparison based sorting because this isn't a comparison based sort.

Here's some pseudocode.

char[26] countArray;
foreach(char c in sortTarget)
{
    countArray[c - 'a']++;
}

int head = 0;
foreach(char c in sortOrder)
{
    while(countArray[c - 'a'] > 0)
    {
        sortTarget[head] = c;
        head++;
        countArray[c - 'a']--;
    }
}

Note: this implementation requires that both strings contain only lowercase characters.

like image 95
Waylon Flinn Avatar answered Sep 28 '22 16:09

Waylon Flinn