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++
#include <bits/stdc++.h>
using namespace std;
bool checkLargest(string s1, string s2,
unordered_map< char , int >& order)
{
int n1 = s1.size();
int n2 = s2.size();
for ( int i = 0; i < min(n1, n2); i++) {
if (order[s1[i]] != order[s2[i]])
return order[s1[i]] > order[s2[i]];
}
if (n1 > n2)
return true ;
return false ;
}
string largestString(vector<string>& arr, string order)
{
unordered_map< char , int > mp;
for ( int i = 0; i < order.length(); i++)
mp[order[i]] = i;
string ans = "" ;
for (string s : arr) {
if (checkLargest(s, ans, mp))
ans = s;
}
return ans;
}
int main()
{
vector<string> arr = { "abc" , "abd" , "abz" };
string order = "abczdefghijklmnopqrstuvwxy" ;
cout << largestString(arr, order) << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
static boolean
checkLargest(String s1, String s2,
HashMap<Character, Integer> order)
{
int n1 = s1.length();
int n2 = s2.length();
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 (n1 > n2)
return true ;
return false ;
}
static String largestString(List<String> arr,
String order)
{
HashMap<Character, Integer> mp = new HashMap<>();
for ( int i = 0 ; i < order.length(); i++)
mp.put(order.charAt(i), i);
String ans = "" ;
for (String s : arr) {
if (checkLargest(s, ans, mp))
ans = s;
}
return ans;
}
public static void main(String[] args)
{
List<String> arr
= Arrays.asList( "abc" , "abd" , "abz" );
String order = "abczdefghijklmnopqrstuvwxy" ;
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 :
mp = defaultdict( int )
for i, char in enumerate (order):
mp[char] = i
ans = ''
for s in arr:
if checkLargest(s, ans, mp):
ans = s
return ans
if __name__ = = '__main__' :
arr = [ 'abc' , 'abd' , 'abz' ]
order = 'abczdefghijklmnopqrstuvwxy'
print (largestString(arr, order))
|
C#
using System;
using System.Collections.Generic;
class Program {
static bool CheckLargest( string s1, string s2,
Dictionary< char , int > order)
{
int n1 = s1.Length;
int n2 = s2.Length;
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 (n1 > n2)
return true ;
return false ;
}
static string LargestString(List< string > arr,
string order)
{
Dictionary< char , int > mp
= new Dictionary< char , int >();
for ( int i = 0; i < order.Length; i++)
mp[order[i]] = i;
string ans = "" ;
foreach ( string s in arr)
{
if (CheckLargest(s, ans, mp))
ans = s;
}
return ans;
}
static void Main( string [] args)
{
List< string > arr
= new List< string >{ "abc" , "abd" , "abz" };
string order = "abczdefghijklmnopqrstuvwxy" ;
Console.WriteLine(LargestString(arr, order));
}
}
|
Javascript
function checkLargest(s1, s2, order) {
let n1 = s1.length;
let n2 = s2.length;
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 (n1 > n2) {
return true ;
}
return false ;
}
function largestString(arr, order) {
let mp = {};
for (let i = 0; i < order.length; i++) {
mp[order[i]] = i;
}
let ans = "" ;
for (let s of arr) {
if (checkLargest(s, ans, mp)) {
ans = s;
}
}
return ans;
}
let arr = [ "abc" , "abd" , "abz" ];
let order = "abczdefghijklmnopqrstuvwxy" ;
console.log(largestString(arr, order));
|
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.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int compare(string word1, string word2,
int order[]);
string largestString(string a[], int n,
string order)
{
int map[26];
for ( int i = 0; i < order.length(); i++)
map[order[i] - 'a' ] = i;
string ans = a[0];
for ( int i = 1; i < n; i++)
{
if (compare(ans, a[i], map) < 0)
ans = a[i];
}
return ans;
}
int compare(string word1, string word2,
int order[])
{
int i = 0, j = 0, charcompareval = 0;
while (i < word1.length() &&
j < word2.length())
{
charcompareval = order[word1[i] - 'a' ] -
order[word2[i] - 'a' ];
if (charcompareval != 0)
return charcompareval;
i++;
j++;
}
if (charcompareval == 0)
return (word1.length() -
word2.length());
else
return charcompareval;
}
int main()
{
int n = 3;
string arr[] = { "abc" , "abd" , "abz" };
string order = "abczdefghijklmnopqrstuvwxy" ;
string ans = largestString(arr, n, order);
cout << ans;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static String
largestString(String[] a, int n,
String order)
{
int map[] = new int [ 26 ];
for ( int i = 0 ; i < order.length(); i++)
map[order.charAt(i) - 'a' ] = i;
String ans = a[ 0 ];
for ( int i = 1 ; i < n; i++) {
if (compare(ans, a[i], map) < 0 )
ans = a[i];
}
return ans;
}
public static int
compare(String word1, String word2,
int [] order)
{
int i = 0 , j = 0 , charcompareval = 0 ;
while (i < word1.length()
&& j < word2.length()) {
charcompareval
= order[word1.charAt(i) - 'a' ]
- order[word2.charAt(i) - 'a' ];
if (charcompareval != 0 )
return charcompareval;
i++;
j++;
}
if (charcompareval == 0 )
return (word1.length()
- word2.length());
else
return charcompareval;
}
public static void main(String args[])
{
int n = 3 ;
String arr[] = { "abc" , "abd" , "abz" };
String order
= "abczdefghijklmnopqrstuvwxy" ;
String ans
= largestString(arr, n, order);
System.out.println(ans);
}
}
|
Python3
def largestString(a, n, order):
map = [ 0 ] * 26
for i in range ( len (order)):
map [ ord (order[i]) - ord ( 'a' )] = i
ans = a[ 0 ]
for i in range ( 1 , n):
if (compare(ans, a[i], map ) < 0 ):
ans = a[i]
return ans
def compare(word1, word2, order):
i = 0
j = 0
charcompareval = 0 ;
while (i < len (word1) and
j < len (word2)):
charcompareval = (order[ ord (word1[i]) - ord ( 'a' )] -
order[ ord (word2[i]) - ord ( 'a' )])
if (charcompareval ! = 0 ):
return charcompareval
i + = 1
j + = 1
if (charcompareval = = 0 ):
return ( len (word1) - len (word2))
else :
return charcompareval
if __name__ = = "__main__" :
n = 3
arr = [ "abc" , "abd" , "abz" ]
order = "abczdefghijklmnopqrstuvwxy"
ans = largestString(arr, n, order)
print (ans)
|
C#
using System;
class GFG{
public static String largestString(String[] a, int n,
String order)
{
int []map = new int [26];
for ( int i = 0; i < order.Length; i++)
map[order[i] - 'a' ] = i;
String ans = a[0];
for ( int i = 1; i < n; i++)
{
if (compare(ans, a[i], map) < 0)
ans = a[i];
}
return ans;
}
public static int compare(String word1,
String word2,
int [] order)
{
int i = 0, j = 0, charcompareval = 0;
while (i < word1.Length &&
j < word2.Length)
{
charcompareval = order[word1[i] - 'a' ] -
order[word2[i] - 'a' ];
if (charcompareval != 0)
return charcompareval;
i++;
j++;
}
if (charcompareval == 0)
return (word1.Length -
word2.Length);
else
return charcompareval;
}
public static void Main(String []args)
{
int n = 3;
String []arr = { "abc" , "abd" , "abz" };
String order = "abczdefghijklmnopqrstuvwxy" ;
String ans = largestString(arr, n, order);
Console.WriteLine(ans);
}
}
|
Javascript
<script>
function largestString(a, n, order)
{
let map = new Array(26);
for (let i = 0; i < order.length; i++)
map[order[i].charCodeAt(0) -
'a' .charCodeAt(0)] = i;
let ans = a[0];
for (let i = 1; i < n; i++)
{
if (compare(ans, a[i], map) < 0)
ans = a[i];
}
return ans;
}
function compare(word1, word2, order)
{
let i = 0, j = 0, charcompareval = 0;
while (i < word1.length &&
j < word2.length)
{
charcompareval = order[word1[i].charCodeAt(0) -
'a' .charCodeAt(0)] -
order[word2[i].charCodeAt(0) -
'a' .charCodeAt(0)];
if (charcompareval != 0)
return charcompareval;
i++;
j++;
}
if (charcompareval == 0)
return (word1.length - word2.length);
else
return charcompareval;
}
let n = 3;
let arr = [ "abc" , "abd" , "abz" ];
let order = "abczdefghijklmnopqrstuvwxy" ;
let ans = largestString(arr, n, order);
document.write(ans);
</script>
|
Time Complexity: O(N *max_word_length)
Auxiliary Space: O(1)