Sort an array of strings based on the given order | Set-2
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++ 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 print 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;
}
// C++ program of the above approach
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 print 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;
}
// Java program of the above approach
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
public class GFG {
// Function to replace all the
// characters in the array of strings
// according to the given key
static void hashFunction(List<String> words, Map<Character, Character> key)
{
for (int i = 0; i < words.size(); i++) {
char[] ch = words.get(i).toCharArray();
for (int j = 0; j < words.get(i).length(); j++) {
ch[j] = key.get(ch[j]);
}
words.set(i, new String(ch));
}
}
// Function to print the strings
// according to the given order
static void printSorted(List<String> words, String order)
{
// Stores the characters in order
// to encode and decode the string
Map<Character, Character> encode = new HashMap<>();
Map<Character, Character> decode = new HashMap<>();
// Loop to iterate over all characters
for (int i = 0; i < 26; i++) {
// Replace the order[i]th character
// from the ith character
encode.put(order.charAt(i), (char)('a' + i));
// Replace the ith character
// from the order[i]th character
decode.put((char)('a' + i), order.charAt(i));
}
// Function Call to replace all characters
// in words according to encode
hashFunction(words, encode);
// STL Function to sort the array
Collections.sort(words);
// 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 (String x : words) {
System.out.print(x + " ");
}
}
// Driver code
public static void main(String[] args)
{
List<String> words = new ArrayList<>() {{
add("word");
add("world");
add("row");
}};
String order = "worldabcefghijkmnpqstuvxyz";
// Function Call
printSorted(words, order);
}
}
// This code is contributed by Harshad.
# 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 print 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.
// C# program of the above approach
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
// Function to replace all the
// characters in the array of strings
// according to the given key
static void hashFunction(List<string> words,
Dictionary<char, char> key)
{
for (int i = 0; i < words.Count; i++)
{
char[] ch = words[i].ToCharArray();
for (int j = 0; j < words[i].Length; j++)
{
ch[j] = key[ch[j]];
}
words[i] = new string(ch);
}
}
// Function to print the strings
// according to the given order
static void printSorted(List<string> words, string order)
{
// Stores the characters in order
// to encode and decode the string
Dictionary<char, char> encode = new Dictionary<char, char>();
Dictionary<char, char> decode = new Dictionary<char, char>();
// 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]] = (char)('a' + i);
// Replace the ith character
// from the order[i]th character
decode[(char)('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();
// 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
foreach (string x in words)
{
Console.Write(x + " ");
}
}
// Driver code
static public void Main()
{
List<string> words = new List<string> { "word", "world", "row" };
string order = "worldabcefghijkmnpqstuvxyz";
// Function Call
printSorted(words, order);
}
}
// This code is contributed by ruchikabaslas.
<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 print 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)