Open In App

Sort the array of strings according to alphabetical order defined by another string

Last Updated : 23 Feb, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report

Given a string str and an array of strings strArr[], the task is to sort the array according to the alphabetical order defined by str

Note: str and every string in strArr[] consists of only lower case alphabets.

Examples: 

Input: str = “fguecbdavwyxzhijklmnopqrst”, 
strArr[] = {“geeksforgeeks”, “is”, “the”, “best”, “place”, “for”, “learning”} 
Output: for geeksforgeeks best is learning place the

Input: str = “avdfghiwyxzjkecbmnopqrstul”, 
strArr[] = {“rainbow”, “consists”, “of”, “colours”} 
Output: consists colours of rainbow 

Approach: Traverse every character of str and store the value in a map with character as the key and its index in the array as the value
Now, this map will act as the new alphabetical order of the characters. Start comparing the string in the strArr[] and instead of comparing the ASCII values of the characters, compare the values mapped to those particular characters in the map i.e. if character c1 appears before character c2 in str then c1 < c2.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
 
using namespace std;
 
// Map to store the characters with their order
// in the new alphabetical order
map<char, int> h;
 
// Function that returns true if x < y
// according to the new alphabetical order
int Compare(string x, string y)
{
    int minSize = min(x.length(), y.length());
 
    for (int i = 0; i < minSize; i++)
    {
        if (h[x[i]] == h[y[i]])
            continue;
        return h[x[i]] - h[y[i]];
    }
 
    return x.length() - y.length();
}
 
// Driver code
int main()
{
    string str = "fguecbdavwyxzhijklmnopqrst";
    vector<string> v { "geeksforgeeks", "is", "the", "best", "place", "for", "learning" };
 
    // Store the order for each character
    // in the new alphabetical sequence
    h.clear();
    for (int i = 0; i < str.length(); i++)
        h[str[i]] = i;
 
    sort(v.begin(), v.end(), [](string x, string y) { return Compare(x, y) < 0; });
 
    // Print the strings after sorting
    for (auto x : v)
        cout << x << " ";
 
    return 0;
}


C#

Java

Python3

Javascript

Output

for geeksforgeeks best is learning place the 

Complexity Analysis:

  • Time Complexity: O(N * log(N)), where N is the size of the string str
  • Auxiliary Space: O(N)


Next Article

Similar Reads