Lexicographically largest string for given dictionary order - GeeksforGeeks

12 Jun, 2021
Given an array arr[] of N strings and a string order which represents the new alphabetical order of the string. The task is to find the lexicographically largest string based on the given order.
Examples:
Input: a[] = {“abc”, “abd”, “abz”}, order = “abczdefghijklmnopqrstuvwxy” Output: abd Explanation:Compare two words “abc”, “abd”, the first non-matching character is c, d in the order, c comes before d so abd is largest among them. Similarly, compare abd and abz.
Input: arr[] = {“abc”, “abdz”, “abd”}, order = “abcdefghijklmnopqrstuvwxyz”Output: abdzExplanation:Among all the given strings abdz is the largest.
Naive Approach: The idea is to check for each string if it is lexicographically largest among the given strings or not. If yes then print that string else check for the next string.
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The idea is to implement a comparator function according to the given string order find the string which is lexicographically largest. Below are the steps:
Create a map to store the index of the character in the given order of string.Consider first string of the array as the lexicographically largest string as ans.Now traverse the given string in the range [1, N] and compare each string with string ans using the indexes stored in the map.Keep updating the largest lexicographically string in the above step and print the string.
Create a map to store the index of the character in the given order of string.
Consider first string of the array as the lexicographically largest string as ans.
Now traverse the given string in the range [1, N] and compare each string with string ans using the indexes stored in the map.
Keep updating the largest lexicographically string in the above step and print the string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h> using namespace std;    int compare(string word1, string word2,            int order[]);             // Find the lexicographically// largest stringstring largestString(string a[], int n,                     string order){         // Create a map of characters    int map[26];     // Value of each character is    // string is given priority    // according to their occurence    // in the string    for(int i = 0; i < order.length(); i++)        map[order[i] - 'a'] = i;     // Take first String as maximum    string ans = a[0];     for(int i = 1; i < n; i++)    {                 // Compare two strings each time        if (compare(ans, a[i], map) < 0)                 // Update answer            ans = a[i];    }    return ans;} // Implement compare function// to get the dictionary orderint compare(string word1, string word2,            int order[]){    int i = 0, j = 0, charcompareval = 0;     while (i < word1.length() &&           j < word2.length())    {                 // Compare each char        // according to the order        charcompareval = order[word1[i] - 'a'] -                         order[word2[i] - 'a'];             // Find the first non matching        // character in the string        if (charcompareval != 0)            return charcompareval;                     i++;        j++;    }     // If one word is prefix of    // other return shortest word    if (charcompareval == 0)        return (word1.length() -                word2.length());    else        return charcompareval;} // Driver Codeint main(){    int n = 3;     // Given array of strings arr    string arr[] = { "abc", "abd", "abz" };     // Given order of string    string order = "abczdefghijklmnopqrstuvwxy";     // Function call    string ans = largestString(arr, n, order);     cout << ans;         return 0;} // This code is contributed by rutvik_56
// Java program for the above approach import java.util.*;public class Main {     // Find the lexicographically    // largest string    public static String    largestString(String[] a, int n,                String order)    {        // Create a map of characters        int map[] = new int[26];         // Value of each character is        // string is given priority        // according to their occurence        // in the string        for (int i = 0; i < order.length(); i++)            map[order.charAt(i) - 'a'] = i;         // Take first String as maximum        String ans = a[0];         for (int i = 1; i < n; i++) {             // Compare two strings each time            if (compare(ans, a[i], map) < 0)                 // Update answer                ans = a[i];        }        return ans;    }     // Implement compare function    // to get the dictionary order    public static int    compare(String word1, String word2,            int[] order)    {        int i = 0, j = 0, charcompareval = 0;         while (i < word1.length()            && j < word2.length()) {             // Compare each char            // according to the order            charcompareval                = order[word1.charAt(i) - 'a']                - order[word2.charAt(i) - 'a'];             // Find the first non matching            // character in the string            if (charcompareval != 0)                 return charcompareval;            i++;            j++;        }         // If one word is prefix of        // other return shortest word        if (charcompareval == 0)            return (word1.length()                    - word2.length());        else            return charcompareval;    }     // Driver Code    public static void main(String args[])    {        int n = 3;         // Given array of strings arr        String arr[] = { "abc", "abd", "abz" };         // Given order of string        String order            = "abczdefghijklmnopqrstuvwxy";         // Function call        String ans            = largestString(arr, n, order);         System.out.println(ans);    }}
# Python3 program for the above approach # Find the lexicographically# largest stringdef largestString(a, n, order):     # Create a map of characters    map = [0] * 26     # Value of each character is    # string is given priority    # according to their occurence    # in the string    for i in range(len(order)):            map[ord(order[i]) - ord('a')] = i     # Take first String as maximum    ans = a[0]     for i in range(1, n):                 # Compare two strings each time        if (compare(ans, a[i], map) < 0):             # Update answer            ans = a[i]             return ans # Implement compare function# to get the dictionary orderdef compare(word1, word2, order):     i = 0    j = 0    charcompareval = 0;     while (i < len(word1) and        j < len(word2)):         # Compare each char        # according to the order        charcompareval = (order[ord(word1[i]) - ord('a')] -                        order[ord(word2[i]) - ord('a')])         # Find the first non matching        # character in the string        if (charcompareval != 0):            return charcompareval                     i += 1        j += 1     # If one word is prefix of    # other return shortest word    if (charcompareval == 0):        return (len(word1) - len(word2))    else:        return charcompareval     # Driver Codeif __name__ == "__main__":     n = 3     # Given array of strings arr    arr = [ "abc", "abd", "abz" ]     # Given order of string    order = "abczdefghijklmnopqrstuvwxy"     # Function call    ans = largestString(arr, n, order)         print(ans) # This code is contributed by chitranayal
// C# program for the above approachusing System;class GFG{ // Find the lexicographically// largest stringpublic static String largestString(String[] a, int n,                                    String order){    // Create a map of characters    int []map = new int[26];     // Value of each character is    // string is given priority    // according to their occurence    // in the string    for (int i = 0; i < order.Length; i++)    map[order[i] - 'a'] = i;     // Take first String as maximum    String ans = a[0];     for (int i = 1; i < n; i++)    {     // Compare two strings each time    if (compare(ans, a[i], map) < 0)         // Update answer        ans = a[i];    }    return ans;} // Implement compare function// to get the dictionary orderpublic static int compare(String word1,                            String word2,                            int[] order){    int i = 0, j = 0, charcompareval = 0;     while (i < word1.Length &&        j < word2.Length)    {     // Compare each char    // according to the order    charcompareval = order[word1[i] - 'a'] -                    order[word2[i] - 'a'];     // Find the first non matching    // character in the string    if (charcompareval != 0)         return charcompareval;    i++;    j++;    }     // If one word is prefix of    // other return shortest word    if (charcompareval == 0)    return (word1.Length -            word2.Length);    else    return charcompareval;} // Driver Codepublic static void Main(String []args){    int n = 3;     // Given array of strings arr    String []arr = { "abc", "abd", "abz" };     // Given order of string    String order = "abczdefghijklmnopqrstuvwxy";     // Function call    String ans = largestString(arr, n, order);     Console.WriteLine(ans);}} // This code is contributed by Amit Katiyar
<script> // Javascriptam for the above approach // Find the lexicographically// largest stringfunction largestString(a, n, order){         // Create a map of characters    let map = new Array(26);     // Value of each character is    // string is given priority    // according to their occurence    // in the string    for(let i = 0; i < order.length; i++)        map[order[i].charCodeAt(0) -                 'a'.charCodeAt(0)] = i;     // Take first String as maximum    let ans = a[0];     for(let i = 1; i < n; i++)    {                 // Compare two strings each time        if (compare(ans, a[i], map) < 0)             // Update answer            ans = a[i];    }    return ans;} // Implement compare function// to get the dictionary orderfunction compare(word1, word2, order){    let i = 0, j = 0, charcompareval = 0;           while (i < word1.length &&               j < word2.length)        {                         // Compare each char            // according to the order            charcompareval = order[word1[i].charCodeAt(0) -                                        'a'.charCodeAt(0)] -                             order[word2[i].charCodeAt(0) -                                        'a'.charCodeAt(0)];               // Find the first non matching            // character in the string            if (charcompareval != 0)                return charcompareval;                             i++;            j++;        }           // If one word is prefix of        // other return shortest word        if (charcompareval == 0)            return (word1.length - word2.length);        else            return charcompareval;} // Driver Codelet n = 3;let arr = [ "abc", "abd", "abz" ];let order = "abczdefghijklmnopqrstuvwxy";let ans = largestString(arr, n, order); document.write(ans); // This code is contributed by avanitrachhadiya2155 </script>
abd
Time Complexity: O(N *max_word_length)Auxiliary Space: O(1)
ukasp
amit143katiyar
rutvik_56
avanitrachhadiya2155
lexicographic-ordering
Arrays
Sorting
Strings
Arrays
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element