Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Sort an array of strings based on the given order | Set-2

  • Last Updated : 08 Oct, 2021

Given an array of strings words[] and the sequential order of alphabets, the task is to sort the array according to the given order. Assume that the dictionary and the words only contain lowercase English alphabets.

Examples: 

Input: words[] = {“hello”, “geeksforgeeks”}, order[] = “hlabcdefgijkmnopqrstuvwxyz”
Output: hello geeksforgeeks 
Explanation: According to the given order ‘h’ occurs before ‘g’ and hence the words are considered to be sorted.

Input: words = {“word”, “world”, “row”}, order = “worldabcefghijkmnpqstuvxyz” 
Output: world word row 
Explanation: According to the given order ‘l’ occurs before ‘d’ hence the words “world” will be kept first.  

Approach: The given problem is already discussed in the article here. This article suggests a different approach that uses hashing. Since an order of alphabets is given, it can be used as a key where order[i]th alphabet can be replaced by the ith alphabet. For instance, in the given order[] = “hlabcdefgijkmnopqrstuvwxyz”, character ‘h’ can be replaced by ‘a’, character ‘l’ can be replaced by ‘b’, and so on. Using that observation the given problem can be solved by following the below steps:

  • Create a hashFunction that accepts a key as an argument and replaces all the characters of the string according to the given key i.e, character x will be replaced by character stored in key[x].
  • Use an unordered map encode, which store the sequence of characters as per the given order i.e, encode[‘h’] = ‘a’, encode[‘l’] = ‘b’… and so on. Similarly, store the reverse in decode i.e, decode[‘a’] = ‘h’, decode[‘b’] = ‘l’… and so on which can be used to restore the original array.
  • Sort the array after hashing it using encode as the key.
  • Restore the strings in the sorted array using decode as the key.

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to replace all the
// characters in the array of strings
// according to the given key
void hashFunction(vector<string>& words,
                  unordered_map<char, char> key)
{
    for (auto& x : words) {
        for (int i = 0; i < x.size(); i++) {
            x[i] = key[x[i]];
        }
    }
}
 
// Function to pring the strings
// according to the given order
void printSorted(vector<string> words, string order)
{
    // Stores the characters in order
    // to encode and decode the string
    unordered_map<char, char> encode, decode;
 
    // Loop to iterate over all characters
    for (int i = 0; i < 26; i++) {
        // Replace the order[i]th character
        // from the ith character
        encode[order[i]] = 'a' + i;
 
        // Replace the ith character
        // from the order[i]th character
        decode['a' + i] = order[i];
    }
 
    // Function Call to replace all characters
    // in words according to encode
    hashFunction(words, encode);
 
    // STL Function to sort the array
    sort(words.begin(), words.end());
 
    // Function Call to replace all characters
    // in words according to decode in order
    // to restore original strings
    hashFunction(words, decode);
 
    // Printing the sorted order of words
    for (auto x : words) {
        cout << x << " ";
    }
}
 
// Driver code
int main()
{
    vector<string> words = { "word", "world", "row" };
    string order = "worldabcefghijkmnpqstuvxyz";
 
    // Function Call
    printSorted(words, order);
 
    return 0;
}

Python3




# Python 3 program of the above approach
 
# Function to replace all the
# characters in the array of strings
# according to the given key
def hashFunction(words, key):
    for x in words:
        x = list(x)
        for i in range(len(x)):
            x[i] = key[x[i]]
        x = ''.join(x)
 
# Function to pring the strings
# according to the given order
def printSorted(words, order):
   
    # Stores the characters in order
    # to encode and decode the string
    encode = {}
    decode = {}
 
    # Loop to iterate over all characters
    for i in range(26):
        # Replace the order[i]th character
        # from the ith character
        encode[order[i]] = chr(ord('a') + i)
 
        # Replace the ith character
        # from the order[i]th character
        decode[chr(ord('a') + i)] = order[i]
 
    # Function Call to replace all characters
    # in words according to encode
    hashFunction(words, encode)
 
    # STL Function to sort the array
    words.sort(reverse = True)
 
    # Function Call to replace all characters
    # in words according to decode in order
    # to restore original strings
    hashFunction(words, decode)
 
    # Printing the sorted order of words
    for x in words:
        print(x,end = " ")
 
# Driver code
if __name__ == '__main__':
    words = ["word", "world", "row"]
    order = "worldabcefghijkmnpqstuvxyz"
 
    # Function Call
    printSorted(words, order)
     
    # This code is contributed by ipg2016107.

Javascript




<script>
// Javascript program of the above approach
 
// Function to replace all the
// characters in the array of strings
// according to the given key
function hashFunction(words, key) {
  for (x of words) {
    for (let i = 0; i < x.length; i++) {
      x[i] = key.get(x[i]);
    }
  }
  console.log(words);
}
 
// Function to pring the strings
// according to the given order
function printSorted(words, order) {
  // Stores the characters in order
  // to encode and decode the string
  let encode = new Map();
  let decode = new Map();
 
  // Loop to iterate over all characters
  for (let i = 0; i < 26; i++) {
    // Replace the order[i]th character
    // from the ith character
    encode.set(order[i], "a".charCodeAt(0) + i);
 
    // Replace the ith character
    // from the order[i]th character
    decode.set("a".charCodeAt(0) + i, order[i]);
  }
 
  // Function Call to replace all characters
  // in words according to encode
  hashFunction(words, encode);
 
  // Function to sort the array
  words.sort().reverse();
 
  // Function Call to replace all characters
  // in words according to decode in order
  // to restore original strings
  hashFunction(words, decode);
 
  // Printing the sorted order of words
  for (x of words) {
    document.write(x + " ");
  }
}
 
// Driver code
 
let words = ["word", "world", "row"];
let order = "worldabcefghijkmnpqstuvxyz";
 
// Function Call
printSorted(words, order);
 
</script>

 
 

Output
world word row 

 

Time Complexity: O(N*M*log(N)) where M is the average length of all the strings.
Auxiliary Space: O(1)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!