text: Lexicographically smallest and largest anagrams of a string containing another string as its substring | 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 ; Given two strings ; Function Calls
code: function lexico_smallest ( s1 , s2 ) { let M = new Map ( ) ; let S = new Set ( ) ; let pr ; for ( let i = 0 ; i <= s1 . length - 1 ; ++ i ) { if ( M . has ( s1 [ i ] ) ) { M [ s1 [ i ] ] ++ ; } else { M [ s1 [ i ] ] = 1 ; } S . add ( s1 [ i ] ) ; } for ( let i = 0 ; i <= s2 . length - 1 ; ++ i ) { if ( M . has ( s2 [ i ] ) ) { M [ s2 [ i ] ] -- ; } else { M [ s2 [ i ] ] = - 1 ; } } let c = s2 [ 0 ] ; let index = 0 ; let res = " " ; S . forEach ( function ( x ) { if ( x != c ) { for ( let i = 1 ; i <= M [ x ] ; ++ i ) { res += x ; } } else { let j = 0 ; index = res . length ; while ( s2 [ j ] == x ) { j ++ ; } if ( s2 [ j ] < c ) { res += s2 ; for ( let i = 1 ; i <= M [ x ] ; ++ i ) { res += x ; } } else { for ( let i = 1 ; i <= M [ x ] ; ++ i ) { res += x ; } index += M [ x ] ; res += s2 ; } } } ) res = " " ; pr = [ res , index ] ; return pr ; } function lexico_largest ( s1 , s2 ) { let pr = lexico_smallest ( s1 , s2 ) ; let d1 = " " ; for ( let i = pr [ 1 ] - 1 ; i >= 0 ; i -- ) { d1 += pr [ 0 ] [ i ] ; } let d2 = " " ; for ( let i = pr [ 0 ] . length - 1 ; i >= pr [ 1 ] + s2 . length ; -- i ) { d2 += pr [ 0 ] [ i ] ; } let res = d2 + s2 + d1 ; return res ; } let s1 = " " ; let s2 = " " ; document . write ( lexico_smallest ( s1 , s2 ) [ 0 ] + " " ) ; document . write ( lexico_largest ( s1 , s2 ) ) ;