Lexicographically smallest permutation of a string that contains all substrings of another string | 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
function reorderString ( A , B ) { let size_a = A . length ; let size_b = B . length ; let freq = new Array ( 300 ) ; for ( let i = 0 ; i < 300 ; i ++ ) { freq [ i ] = 0 ; } for ( let i = 0 ; i < size_b ; i ++ ) freq [ B [ i ] . charCodeAt ( 0 ) ] ++ ; for ( let i = 0 ; i < size_a ; i ++ ) freq [ A [ i ] . charCodeAt ( 0 ) ] -- ; for ( let j = ' ' . charCodeAt ( 0 ) ; j <= ' ' . charCodeAt ( 0 ) ; j ++ ) { if ( freq [ j ] < 0 ) return " " ; } let answer = " " ; for ( let j = ' ' . charCodeAt ( 0 ) ; j < A [ 0 ] . charCodeAt ( 0 ) ; j ++ ) while ( freq [ j ] > 0 ) { answer += j ; freq [ j ] -- ; } let first = A [ 0 ] ; for ( let j = 0 ; j < size_a ; j ++ ) { if ( A [ j ] > A [ 0 ] ) break ; if ( A [ j ] < A [ 0 ] ) { answer += ( A ) . join ( " " ) ; A = new Array ( A . length ) ; break ; } } while ( freq [ first ] > 0 ) { answer += ( String . fromCharCode ( first ) ) ; -- freq [ first ] ; } answer += ( A ) . join ( " " ) ; for ( let j = ' ' . charCodeAt ( 0 ) ; j <= ' ' . charCodeAt ( 0 ) ; j ++ ) while ( freq [ j ] -- > 0 ) answer += String . fromCharCode ( j ) ; return answer ; } let A = " " ; let B = " " ; document . write ( reorderString ( A . split ( " " ) , B . split ( " " ) ) ) ;