Lexicographically largest string formed from the characters in range L and R | Java program to print the lexicographically largest String that can be formed from the characters in range L and R ; Function to return the lexicographically largest String ; hash array ; make 0 - based indexing ; iterate and count frequencies of character ; ans String ; iterate in frequency array ; add til all characters are added ; Driver Code
class GFG { static String printLargestString ( String s , int l , int r ) { int freq [ ] = new int [ 26 ] ; l -- ; r -- ; for ( int i = Math . min ( l , r ) ; i <= Math . max ( l , r ) ; i ++ ) { freq [ s . charAt ( i ) - ' a ' ] ++ ; } String ans = " " ; for ( int i = 25 ; i >= 0 ; i -- ) { while ( freq [ i ] > 0 ) { ans += ( char ) ( ' a ' + i ) ; freq [ i ] -- ; } } return ans ; } public static void main ( String [ ] args ) { String s = " striver " ; int l = 3 , r = 5 ; System . out . println ( printLargestString ( s , l , r ) ) ; } }