Open In App

Lexicographically largest string for given dictionary order

Improve
Improve
Like Article
Like
Save
Share
Report

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: arr[] = {“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.

Steps that were to follow the above approach:

  •    Define a function named “checkLargest” which takes two string arguments “s1” and “s2”, and an unordered_map “order” as input.
  •    In the “checkLargest” function, compare the length of “s1” and “s2” and store it in n1 and n2 respectively.
  •    Traverse both strings and find the first mismatching character and check if it is lexicographically largest or not using the unordered_map      “order”.
  •    If all characters match and length of s1 is greater than s2, then s1 is lexicographically largest, so return true.
  •    If no mismatching character is found, then return the length comparison result.
  •    Define another function named “largestString” which takes a vector “arr” and a string “order” as input.
  •    Inside the “largestString” function, create an unordered_map “mp” to store the order of characters using “order”.
  •   Traverse all strings in the “arr” vector and compare each string with the current lexicographically largest string using the “checkLargest”       function.
  •   If the current string is lexicographically larger than the current largest string, update the largest string with the current string.
  •   Finally, return the largest string.
  •   In the main function, define the input vector “arr” and string “order”.
  •   Call the “largestString” function with “arr” and “order” as input and print the returned result.

Below is the code to implement the above steps:

C++




// C++ program to find the lexicographically largest
// string based on the given order
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a string is lexicographically
// largest among the given strings or not
bool checkLargest(string s1, string s2,
                  unordered_map<char, int>& order)
{
    int n1 = s1.size();
    int n2 = s2.size();
 
    // Traverse both strings and find the first mismatching
    // character and check if it is lexicographically
    // largest or not
    for (int i = 0; i < min(n1, n2); i++) {
        if (order[s1[i]] != order[s2[i]])
            return order[s1[i]] > order[s2[i]];
    }
 
    // If all characters match and length of s1 is greater
    // than s2, then s1 is lexicographically largest
    if (n1 > n2)
        return true;
 
    return false;
}
 
// Function to find the lexicographically largest string
// based on the given order
string largestString(vector<string>& arr, string order)
{
    // Create a hash map to store the order of characters
    unordered_map<char, int> mp;
    for (int i = 0; i < order.length(); i++)
        mp[order[i]] = i;
 
    // Traverse all strings to find the lexicographically
    // largest string
    string ans = "";
    for (string s : arr) {
        if (checkLargest(s, ans, mp))
            ans = s;
    }
 
    return ans;
}
 
// Driver code
int main()
{
    // Given array of strings
    vector<string> arr = { "abc", "abd", "abz" };
 
    // Given alphabetical order
    string order = "abczdefghijklmnopqrstuvwxy";
 
    // Function call to find the lexicographically
    // largest string based on the given order
    cout << largestString(arr, order) << endl;
 
    return 0;
}


Java




// Java program to find the lexicographically largest
// string based on the given order
 
import java.util.*;
 
public class GFG {
    // Function to check if a string is lexicographically
    // largest among the given strings or not
    static boolean
    checkLargest(String s1, String s2,
                 HashMap<Character, Integer> order)
    {
        int n1 = s1.length();
        int n2 = s2.length();
        // Traverse both strings and find the first
        // mismatching
        // character and check if it is lexicographically
        // largest or not
        for (int i = 0; i < Math.min(n1, n2); i++) {
            if (order.get(s1.charAt(i))
                != order.get(s2.charAt(i)))
                return order.get(s1.charAt(i))
                    > order.get(s2.charAt(i));
        }
 
        // If all characters match and length of s1 is
        // greater than s2, then s1 is lexicographically
        // largest
        if (n1 > n2)
            return true;
 
        return false;
    }
 
    // Function to find the lexicographically largest string
    // based on the given order
    static String largestString(List<String> arr,
                                String order)
    {
        // Create a hash map to store the order of
        // characters
        HashMap<Character, Integer> mp = new HashMap<>();
        for (int i = 0; i < order.length(); i++)
            mp.put(order.charAt(i), i);
 
        // Traverse all strings to find the
        // lexicographically largest string
        String ans = "";
        for (String s : arr) {
            if (checkLargest(s, ans, mp))
                ans = s;
        }
 
        return ans;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Given array of strings
        List<String> arr
            = Arrays.asList("abc", "abd", "abz");
 
        // Given alphabetical order
        String order = "abczdefghijklmnopqrstuvwxy";
 
        // Function call to find the lexicographically
        // largest string based on the given order
        System.out.println(largestString(arr, order));
    }
}


Python3




from typing import List
from collections import defaultdict
 
 
def checkLargest(s1: str, s2: str, order: dict) -> bool:
    n1, n2 = len(s1), len(s2)
    for i in range(min(n1, n2)):
        if order[s1[i]] != order[s2[i]]:
            return order[s1[i]] > order[s2[i]]
    return n1 > n2
 
 
def largestString(arr: List[str], order: str) -> str:
    # Create a dictionary to store the order of characters
    mp = defaultdict(int)
    for i, char in enumerate(order):
        mp[char] = i
 
    # Traverse all strings to find the lexicographically largest string
    ans = ''
    for s in arr:
        if checkLargest(s, ans, mp):
            ans = s
    return ans
 
 
# Driver code
if __name__ == '__main__':
    # Given array of strings
    arr = ['abc', 'abd', 'abz']
 
    # Given alphabetical order
    order = 'abczdefghijklmnopqrstuvwxy'
 
    # Function call to find the lexicographically largest string
    print(largestString(arr, order))


C#




using System;
using System.Collections.Generic;
 
class Program {
  // Function to check if a string is lexicographically
  // largest among the given strings or not
  static bool CheckLargest(string s1, string s2,
                           Dictionary<char, int> order)
  {
    int n1 = s1.Length;
    int n2 = s2.Length;
 
    // Traverse both strings and find the first
    // mismatching character and check if it is
    // lexicographically largest or not
    for (int i = 0; i < Math.Min(n1, n2); i++) {
      if (order[s1[i]] != order[s2[i]])
        return order[s1[i]] > order[s2[i]];
    }
 
    // If all characters match and length of s1 is
    // greater than s2, then s1 is lexicographically
    // largest
    if (n1 > n2)
      return true;
 
    return false;
  }
 
  // Function to find the lexicographically largest string
  // based on the given order
  static string LargestString(List<string> arr,
                              string order)
  {
    // Create a dictionary to store the order of
    // characters
    Dictionary<char, int> mp
      = new Dictionary<char, int>();
    for (int i = 0; i < order.Length; i++)
      mp[order[i]] = i;
 
    // Traverse all strings to find the
    // lexicographically largest string
    string ans = "";
    foreach(string s in arr)
    {
      if (CheckLargest(s, ans, mp))
        ans = s;
    }
 
    return ans;
  }
 
  static void Main(string[] args)
  {
    // Given array of strings
    List<string> arr
      = new List<string>{ "abc", "abd", "abz" };
 
    // Given alphabetical order
    string order = "abczdefghijklmnopqrstuvwxy";
 
    // Function call to find the lexicographically
    // largest string based on the given order
    Console.WriteLine(LargestString(arr, order));
  }
}


Javascript




function checkLargest(s1, s2, order) {
  let n1 = s1.length;
  let n2 = s2.length;
 
  // Traverse both strings and find the first mismatching
  // character and check if it is lexicographically
  // largest or not
  for (let i = 0; i < Math.min(n1, n2); i++) {
    if (order[s1[i]] !== order[s2[i]]) {
      return order[s1[i]] > order[s2[i]];
    }
  }
 
  // If all characters match and length of s1 is greater
  // than s2, then s1 is lexicographically largest
  if (n1 > n2) {
    return true;
  }
 
  return false;
}
 
function largestString(arr, order) {
  // Create a hash map to store the order of characters
  let mp = {};
  for (let i = 0; i < order.length; i++) {
    mp[order[i]] = i;
  }
 
  // Traverse all strings to find the lexicographically
  // largest string
  let ans = "";
  for (let s of arr) {
    if (checkLargest(s, ans, mp)) {
      ans = s;
    }
  }
 
  return ans;
}
 
// Driver code
let arr = ["abc", "abd", "abz"];
let order = "abczdefghijklmnopqrstuvwxy";
 
// Function call to find the lexicographically
// largest string based on the given order
console.log(largestString(arr, order));


Output

abd

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 <bits/stdc++.h> 
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[26];
 
    // Value of each character is
    // string is given priority
    // according to their occurrence
    // 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 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 occurrence
        // 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 occurrence
    # 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[26];
 
    // Value of each character is
    // string is given priority
    // according to their occurrence
    // 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 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




<script>
 
// Javascriptam for the above approach
 
// Find the lexicographically
// largest string
function 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 occurrence
    // 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 order
function 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 Code
let 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>


Output: 

abd

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



Last Updated : 19 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads