text: Lexicographically smallest and largest anagrams of a string containing another string as its substring | Java program for the above approach ; Function to find the lexicographically smallest anagram of string which contains another string ; Initializing the map and set ; Iterating over s1 ; Storing the frequency of characters present in s1 ; Storing the distinct characters present in s1 ; Decreasing the frequency of characters from M that are already present in s2 ; Traversing alphabets in sorted order ; If current character of set is not equal to current character of s2 ; If element is equal to current character of s2 ; Checking for second distinct character in s2 ; s2 [ j ] will store second distinct character ; Return the answer ; Function to find the lexicographically largest anagram of string which contains another string ; Getting the lexicographically smallest anagram ; d1 stores the prefix ; d2 stores the suffix ; Return the result ; Driver Code ; Given two strings ; Function Calls
code: import java . lang . * ; import java . io . * ; import java . util . * ; class GFG { static String [ ] lexico_smallest ( String s1 , String s2 ) { Map < Character , Integer > M = new HashMap < > ( ) ; Set < Character > S = new TreeSet < > ( ) ; for ( int i = 0 ; i <= s1 . length ( ) - 1 ; ++ i ) { if ( ! M . containsKey ( s1 . charAt ( i ) ) ) M . put ( s1 . charAt ( i ) , 1 ) ; else M . replace ( s1 . charAt ( i ) , M . get ( s1 . charAt ( i ) ) + 1 ) ; S . add ( s1 . charAt ( i ) ) ; } for ( int i = 0 ; i <= s2 . length ( ) - 1 ; ++ i ) { if ( M . containsKey ( s2 . charAt ( i ) ) ) M . replace ( s2 . charAt ( i ) , M . get ( s2 . charAt ( i ) ) - 1 ) ; } char c = s2 . charAt ( 0 ) ; int index = 0 ; String res = " " ; Iterator < Character > it = S . iterator ( ) ; while ( it . hasNext ( ) ) { char x = it . next ( ) ; if ( x != c ) { for ( int i = 1 ; i <= M . get ( x ) ; ++ i ) { res += x ; } } else { int j = 0 ; index = res . length ( ) ; while ( s2 . charAt ( j ) == x ) { j ++ ; } if ( s2 . charAt ( j ) < c ) { res += s2 ; for ( int i = 1 ; i <= M . get ( x ) ; ++ i ) { res += x ; } } else { for ( int i = 1 ; i <= M . get ( x ) ; ++ i ) { res += x ; } index += M . get ( x ) ; res += s2 ; } } } String pr [ ] = { res , index + " " } ; return pr ; } return pr ; } static String lexico_largest ( String s1 , String s2 ) { String pr [ ] = lexico_smallest ( s1 , s2 ) ; String d1 = " " ; for ( int i = Integer . valueOf ( pr [ 1 ] ) - 1 ; i >= 0 ; i -- ) { d1 += pr [ 0 ] . charAt ( i ) ; } String d2 = " " ; for ( int i = pr [ 0 ] . length ( ) - 1 ; i >= Integer . valueOf ( pr [ 1 ] ) + s2 . length ( ) ; -- i ) { d2 += pr [ 0 ] . charAt ( i ) ; } String res = d2 + s2 + d1 ; return res ; } public static void main ( String [ ] args ) { String s1 = " ethgakagmenpgs " ; String s2 = " geeks " ; System . out . println ( lexico_smallest ( s1 , s2 ) [ 0 ] ) ; System . out . println ( lexico_largest ( s1 , s2 ) ) ; } }