Lexicographically smallest permutation of a string that contains all substrings of another string | Java program for the above approach ; Function to reorder the String B to contain all the subStrings of A ; Find length of Strings ; Initialize array to count the frequencies of the character ; Counting frequencies of character in B ; Find remaining character in B ; Declare the reordered String ; Loop until freq [ j ] > 0 ; Decrement the value from freq array ; Check if A [ j ] > A [ 0 ] ; Check if A [ j ] < A [ 0 ] ; Append the remaining characters to the end of the result ; Push all the values from frequency array in the answer ; Return the answer ; Driver Code ; Given Strings A and B ; Function Call
class GFG { static String reorderString ( char [ ] A , char [ ] B ) { int size_a = A . length ; int size_b = B . length ; int freq [ ] = new int [ 300 ] ; for ( int i = 0 ; i < size_b ; i ++ ) freq [ B [ i ] ] ++ ; for ( int i = 0 ; i < size_a ; i ++ ) freq [ A [ i ] ] -- ; for ( int j = ' a ' ; j <= ' z ' ; j ++ ) { if ( freq [ j ] < 0 ) return " - 1" ; } String answer = " " ; for ( int j = ' a ' ; j < A [ 0 ] ; j ++ ) while ( freq [ j ] > 0 ) { answer += j ; freq [ j ] -- ; } int first = A [ 0 ] ; for ( int j = 0 ; j < size_a ; j ++ ) { if ( A [ j ] > A [ 0 ] ) break ; if ( A [ j ] < A [ 0 ] ) { answer += String . valueOf ( A ) ; A = new char [ A . length ] ; break ; } } while ( freq [ first ] > 0 ) { answer += String . valueOf ( ( char ) first ) ; -- freq [ first ] ; } answer += String . valueOf ( A ) ; for ( int j = ' a ' ; j <= ' z ' ; j ++ ) while ( freq [ j ] -- > 0 ) answer += ( ( char ) j ) ; return answer ; } public static void main ( String [ ] args ) { String A = " aa " ; String B = " ababab " ; System . out . print ( reorderString ( A . toCharArray ( ) , B . toCharArray ( ) ) ) ; } }