# Lexicographically largest string for given dictionary order

• Last Updated : 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:

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: 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: abdz
Explanation:
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:

1. Create a map to store the index of the character in the given order of string.
2. Consider first string of the array as the lexicographically largest string as ans.
3. Now traverse the given string in the range [1, N] and compare each string with string ans using the indexes stored in the map.
4. Keep updating the largest lexicographically string in the above step and print the string.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include  ``using` `namespace` `std; ``  ` `int` `compare(string word1, string word2,``            ``int` `order[]);``            ` `// Find the lexicographically``// largest string``string largestString(string a[], ``int` `n,``                     ``string order)``{``    ` `    ``// Create a map of characters``    ``int` `map;` `    ``// 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;` `    ``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``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 Code``int` `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

 `// 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

 `# Python3 program for the above approach` `# Find the lexicographically``# largest string``def` `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 order``def` `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 Code``if` `__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#

 `// C# program for the above approach``using` `System;``class` `GFG{` `// Find the lexicographically``// largest string``public` `static` `String largestString(String[] a, ``int` `n,``                                    ``String order)``{``    ``// Create a map of characters``    ``int` `[]map = ``new` `int``;` `    ``// 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;` `    ``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[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 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);` `    ``Console.WriteLine(ans);``}``}` `// This code is contributed by Amit Katiyar`

## Javascript

 ``
Output:
`abd`

Time Complexity: O(N *max_word_length)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up