Lexicographic smallest permutation of a String containing the second String as a Substring | Function to prlet 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
function findSmallestString ( str1 , str2 ) { let freq1 = Array . from ( { length : 26 } , ( _ , i ) => 0 ) ; let freq2 = Array . from ( { length : 26 } , ( _ , i ) => 0 ) ; let n1 = str1 . length ; let n2 = str2 . length ; for ( let i = 0 ; i < n1 ; ++ i ) { freq1 [ str1 [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] ++ ; } for ( let i = 0 ; i < n2 ; ++ i ) { freq2 [ str2 [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] ++ ; } for ( let i = 0 ; i < 26 ; ++ i ) { freq1 [ i ] -= freq2 [ i ] ; } let res = " " ; let minIndex = str2 [ 0 ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ; for ( let i = 0 ; i < 26 ; ++ i ) { for ( let j = 0 ; j < freq1 [ i ] ; ++ j ) { res += String . fromCharCode ( i + ' ' . charCodeAt ( ) ) ; } if ( i == minIndex ) { res += str2 ; } } return res ; } let str1 = " " ; let str2 = " " ; document . write ( findSmallestString ( str1 , str2 ) ) ;