Sort an array of strings based on the given order
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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
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 characterunordered_map<char, int> mp;// Custom comparator function for sortbool 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 stringsvoid 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 codeint main(){ vector<string> words = { "word", "world", "row" }; string order = { "worldabcefghijkmnpqstuvxyz" }; printSorted(words, order); return 0;} |
Python3
# Python3 program to sort an array# of strings based on the given orderfrom functools import cmp_to_key# For storing priority of each charactermp = {}# Custom comparator function for sortdef 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 stringsdef 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 codewords = [ "word", "world", "row" ]order = "worldabcefghijkmnpqstuvxyz"printSorted(words, order)# This code is contributed by Shivani |
world word row


