Sort an array of strings based on the given order
Last Updated :
15 Feb, 2023
Given an array of strings words[] and the sequential order of alphabets, our task is to sort the array according to the order given. Assume that the dictionary and the words only contain lowercase 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: To solve the problem mentioned above we need to maintain the priority of each character in the given order. For doing that use Map Data Structure.
- Iterate in the given order and set the priority of a character to its index value.
- Use a custom comparator function to sort the array.
- In the comparator function, iterate through the minimum sized word between the two words and try to find the first different character, the word with the lesser priority value character will be the smaller word.
- If the words have the same prefix, then the word with a smaller size is the smaller word.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
unordered_map< char , int > mp;
bool comp(string& a, string& b)
{
for ( int i = 0;
i < min(a.size(), b.size());
i++) {
if (mp[a[i]] != mp[b[i]])
return mp[a[i]] < mp[b[i]];
}
return (a.size() < b.size());
}
void printSorted(vector<string> words,
string order)
{
for ( int i = 0; i < order.size(); i++)
mp[order[i]] = i;
sort(words.begin(), words.end(), comp);
for ( auto x : words)
cout << x << " " ;
}
int main()
{
vector<string> words
= { "word" , "world" , "row" };
string order
= { "worldabcefghijkmnpqstuvxyz" };
printSorted(words, order);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static HashMap<Character, Integer> mp = new HashMap<>();
class comp implements Comparator<String>
{
public int compare(String a, String b)
{
for ( int i = 0 ;
i < Math.min(a.length(), b.length());
i++) {
if (mp.get(a.charAt(i))
!= mp.get(b.charAt(i)))
return mp.get(a.charAt(i))
- mp.get(b.charAt(i));
}
return (a.length() - b.length());
}
}
static void printSorted(String[] words, String order)
{
for ( int i = 0 ; i < order.length(); i++)
mp.put(order.charAt(i), i);
Arrays.sort(words, new GFG(). new comp());
for (String x : words)
System.out.print(x + " " );
}
public static void main(String[] args)
{
String[] words = { "word" , "world" , "row" };
String order = "worldabcefghijkmnpqstuvxyz" ;
printSorted(words, order);
}
}
|
Python3
from functools import cmp_to_key
mp = {}
def comp(a, b):
for i in range ( min ( len (a), len (b))):
if (mp[a[i]] ! = mp[b[i]]):
if mp[a[i]] < mp[b[i]]:
return - 1
else :
return 1
if ( len (a) < len (b)):
return - 1
else :
return 1
def printSorted(words, order):
for i in range ( len (order)):
mp[order[i]] = i
words = sorted (words, key = cmp_to_key(comp))
for x in words:
print (x, end = " " )
words = [ "word" , "world" , "row" ]
order = "worldabcefghijkmnpqstuvxyz"
printSorted(words, order)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static Dictionary< char , int > mp = new Dictionary< char , int >();
static int Compare( string a, string b)
{
for ( int i = 0;
i < Math.Min(a.Length, b.Length);
i++)
{
if (mp[a[i]] != mp[b[i]])
return mp[a[i]] - mp[b[i]];
}
return a.Length - b.Length;
}
static void PrintSorted(List< string > words,
string order)
{
for ( int i = 0; i < order.Length; i++)
mp[order[i]] = i;
words.Sort(Compare);
foreach ( var x in words)
Console.Write(x + " " );
}
static void Main( string [] args)
{
List< string > words = new List< string >()
{
"word" , "world" , "row"
};
string order = "worldabcefghijkmnpqstuvxyz" ;
PrintSorted(words, order);
Console.ReadLine();
}
}
|
Javascript
<script>
let mp = new Map();
function comp(a, b)
{
for (let i = 0; i < Math.min(a.length, b.length);i++) {
if (mp.get(a[i]) != mp.get(b[i]))
return mp.get(b[i]) - mp.get(a[i]);
}
return (b.length - a.length);
}
function printSorted(words,order)
{
for (let i = 0; i < order.length; i++)
mp.set(order[i],i);
words.sort(comp);
for (let x of words)
document.write(x + " " );
}
let words = [ "word" , "world" , "row" ];
let order = [ "worldabcefghijkmnpqstuvxyz" ];
printSorted(words, order);
</script>
|
Time Complexity: O(l + nlogn), where l is the length of the string order and n is the size of the given vector of strings.
Auxiliary Space: O(l)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...