Open In App

Sort an array of strings based on the given order

Last Updated : 15 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to sort an array
// of strings based on the given order
 
#include <bits/stdc++.h>
using namespace std;
 
// For storing priority of each character
unordered_map<char, int> mp;
 
// Custom comparator function for sort
bool comp(string& a, string& b)
{
 
    // Loop through the minimum size
    // between two words
    for (int i = 0;
         i < min(a.size(), b.size());
         i++) {
 
        // Check if the characters
        // at position i are different,
        // then the word containing lower
        // valued character is smaller
        if (mp[a[i]] != mp[b[i]])
            return mp[a[i]] < mp[b[i]];
    }
 
    /* When loop breaks without returning, it
       means the prefix of both words were same
       till the execution of the loop.
       Now, the word with the smaller size will
       occur before in sorted order
        */
    return (a.size() < b.size());
}
 
// Function to print the
// new sorted array of strings
void printSorted(vector<string> words,
                 string order)
{
 
    // Mapping each character
    // to its occurrence position
    for (int i = 0; i < order.size(); i++)
        mp[order[i]] = i;
 
    // Sorting with custom sort function
    sort(words.begin(), words.end(), comp);
 
    // 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" };
 
    printSorted(words, order);
 
    return 0;
}


Java




// Java program to sort an array
// of strings based on the given order
import java.util.*;
 
class GFG
{
   
    // For storing priority of each character
    static HashMap<Character, Integer> mp = new HashMap<>();
 
    // class implementing Comparator interface
    class comp implements Comparator<String>
    {
       
        // Custom comparator function for sort
        public int compare(String a, String b)
        {
           
            // Loop through the minimum size
            // between two words
            for (int i = 0;
                 i < Math.min(a.length(), b.length());
                 i++) {
 
                // Check if the characters
                // at position i are different,
                // then the word containing lower
                // valued character is smaller
                if (mp.get(a.charAt(i))
                    != mp.get(b.charAt(i)))
                    return mp.get(a.charAt(i))
                        - mp.get(b.charAt(i));
            }
 
            /* When loop breaks without returning, it
            means the prefix of both words were same
            till the execution of the loop.
            Now, the word with the smaller size will
            occur before in sorted order
            */
            return (a.length() - b.length());
        }
    }
 
    // Function to print the
    // new sorted array of strings
    static void printSorted(String[] words, String order)
    {
 
        // Mapping each character
        // to its occurrence position
        for (int i = 0; i < order.length(); i++)
            mp.put(order.charAt(i), i);
 
        // Sorting with custom sort function
        Arrays.sort(words, new GFG().new comp());
 
        // Printing the sorted order of words
        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);
    }
}
 
// This code is contributed by karandeep1234.


Python3




# Python3 program to sort an array
# of strings based on the given order
from functools import cmp_to_key
 
# For storing priority of each character
mp = {}
 
# Custom comparator function for sort
def comp(a, b):
     
    # Loop through the minimum size
    # between two words
    for i in range( min(len(a), len(b))):
         
        # Check if the characters
        # at position i are different,
        # then the word containing lower
        # valued character is smaller
        if (mp[a[i]] != mp[b[i]]):
            if mp[a[i]] < mp[b[i]]:
                return -1
            else:
                return 1
     
    '''When loop breaks without returning, it
    means the prefix of both words were same
    till the execution of the loop.
    Now, the word with the smaller size will
    occur before in sorted order'''
    if (len(a) < len(b)):
        return -1
    else:
        return 1
 
# Function to print the
# new sorted array of strings
def printSorted(words, order):
     
    # Mapping each character
    # to its occurrence position
    for i in range(len(order)):
        mp[order[i]] = i
     
    # Sorting with custom sort function
    words = sorted(words, key = cmp_to_key(comp))
     
    # Printing the sorted order of words
    for x in words:
        print(x, end = " ")
 
# Driver code
words = [ "word", "world", "row" ]
order = "worldabcefghijkmnpqstuvxyz"
 
printSorted(words, order)
 
# This code is contributed by Shivani


C#




// C# program to sort an array
// of strings based on the given order
using System;
using System.Collections.Generic;
 
class Program
{
    // For storing priority of each character
    static Dictionary<char, int> mp = new Dictionary<char, int>();
 
    // Custom comparator function for sort
    static int Compare(string a, string b)
    {
        // Loop through the minimum size
        // between two words
        for (int i = 0;
             i < Math.Min(a.Length, b.Length);
             i++)
        {
            // Check if the characters
            // at position i are different,
            // then the word containing lower
            // valued character is smaller
            if (mp[a[i]] != mp[b[i]])
                return mp[a[i]] - mp[b[i]];
        }
 
        /* When loop breaks without returning, it
           means the prefix of both words were same
           till the execution of the loop.
           Now, the word with the smaller size will
           occur before in sorted order
            */
        return a.Length - b.Length;
    }
 
    // Function to print the
    // new sorted array of strings
    static void PrintSorted(List<string> words,
                 string order)
    {
        // Mapping each character
        // to its occurrence position
        for (int i = 0; i < order.Length; i++)
            mp[order[i]] = i;
 
        // Sorting with custom sort function
        words.Sort(Compare);
 
        // Printing the sorted order of words
        foreach (var x in words)
            Console.Write(x + " ");
    }
 
    // Driver code
    static void Main(string[] args)
    {
        List<string> words = new List<string>()
        {
            "word", "world", "row"
        };
        string order = "worldabcefghijkmnpqstuvxyz";
 
        PrintSorted(words, order);
 
        Console.ReadLine();
    }
}


Javascript




<script>
 
// JavaScript program to sort an array
// of strings based on the given order
 
// For storing priority of each character
let mp = new Map();
 
// Custom comparator function for sort
function comp(a, b)
{
 
    // Loop through the minimum size
    // between two words
    for (let i = 0; i < Math.min(a.length, b.length);i++) {
 
        // Check if the characters
        // at position i are different,
        // then the word containing lower
        // valued character is smaller
        if (mp.get(a[i]) != mp.get(b[i]))
            return mp.get(b[i]) - mp.get(a[i]);
    }
 
    /* When loop breaks without returning, it
    means the prefix of both words were same
    till the execution of the loop.
    Now, the word with the smaller size will
    occur before in sorted order
        */
    return (b.length - a.length);
}
 
// Function to print the
// new sorted array of strings
function printSorted(words,order)
{
 
    // Mapping each character
    // to its occurrence position
    for (let i = 0; i < order.length; i++)
        mp.set(order[i],i);
 
    // Sorting with custom sort function
    words.sort(comp);
 
    // Printing the sorted order of words
    for (let x of words)
        document.write(x +" ");
}
 
// Driver code
let words = ["word", "world", "row" ];
let order = ["worldabcefghijkmnpqstuvxyz" ];
 
printSorted(words, order);
 
// This code is contributed by shinjanpatra
 
</script>


Output

world word row 

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
Previous
Next
Share your thoughts in the comments

Similar Reads