Lexicographic smallest permutation of a String containing the second String as a Substring | Java program to implement the above approach ; Function to print the desired lexicographic smaller String ; Calculate length of the String ; Stores the frequencies of characters of String str1 ; Stores the frequencies of characters of String str2 ; Decrease the frequency of second String from that of of the first String ; To store the resultant String ; To find the index of first character of the String str2 ; Append the characters in lexicographical order ; Append all the current character ( i + ' a ' ) ; If we reach first character of String str2 append str2 ; Return the resultant String ; Driver Code
import java . util . * ; class GFG { static String findSmallestString ( String str1 , String str2 ) { int [ ] freq1 = new int [ 26 ] ; int [ ] freq2 = new int [ 26 ] ; Arrays . fill ( freq1 , 0 ) ; Arrays . fill ( freq2 , 0 ) ; int n1 = str1 . length ( ) ; int n2 = str2 . length ( ) ; for ( int i = 0 ; i < n1 ; ++ i ) { freq1 [ str1 . charAt ( i ) - ' a ' ] ++ ; } for ( int i = 0 ; i < n2 ; ++ i ) { freq2 [ str2 . charAt ( i ) - ' a ' ] ++ ; } for ( int i = 0 ; i < 26 ; ++ i ) { freq1 [ i ] -= freq2 [ i ] ; } String res = " " ; int minIndex = str2 . charAt ( 0 ) - ' a ' ; for ( int i = 0 ; i < 26 ; ++ i ) { for ( int j = 0 ; j < freq1 [ i ] ; ++ j ) { res += ( char ) ( i + ' a ' ) ; } if ( i == minIndex ) { res += str2 ; } } return res ; } public static void main ( String [ ] args ) { String str1 = " geeksforgeeksfor " ; String str2 = " for " ; System . out . print ( findSmallestString ( str1 , str2 ) ) ; } }