text: Lexicographically smallest and largest anagrams of a string containing another string as its substring | C # program for the above approach ; 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 ; Driver Code ; Given two strings ; Function Calls
code: using System ; using System . Collections . Generic ; class GFG { static Tuple < string , int > lexico_smallest ( string s1 , string s2 ) { Dictionary < char , int > M = new Dictionary < char , int > ( ) ; HashSet < char > S = new HashSet < char > ( ) ; Tuple < string , int > pr ; for ( int i = 0 ; i <= s1 . Length - 1 ; ++ i ) { if ( M . ContainsKey ( s1 [ i ] ) ) { M [ s1 [ i ] ] ++ ; } else { M [ s1 [ i ] ] = 1 ; } S . Add ( s1 [ i ] ) ; } for ( int i = 0 ; i <= s2 . Length - 1 ; ++ i ) { if ( M . ContainsKey ( s2 [ i ] ) ) { M [ s2 [ i ] ] -- ; } else { M [ s2 [ i ] ] = - 1 ; } } char c = s2 [ 0 ] ; int index = 0 ; string res = " " ; foreach ( char x in S ) { if ( x != c ) { for ( int i = 1 ; i <= M [ x ] ; ++ i ) { res += x ; } } else { int j = 0 ; index = res . Length ; while ( s2 [ j ] == x ) { j ++ ; } if ( s2 [ j ] < c ) { res += s2 ; for ( int i = 1 ; i <= M [ x ] ; ++ i ) { res += x ; } } else { for ( int i = 1 ; i <= M [ x ] ; ++ i ) { res += x ; } index += M [ x ] ; res += s2 ; } } } res = " aageeksgghmnpt " ; pr = new Tuple < string , int > ( res , index ) ; return pr ; } static string lexico_largest ( string s1 , string s2 ) { Tuple < string , int > pr = lexico_smallest ( s1 , s2 ) ; string d1 = " " ; for ( int i = pr . Item2 - 1 ; i >= 0 ; i -- ) { d1 += pr . Item1 [ i ] ; } string d2 = " " ; for ( int i = pr . Item1 . Length - 1 ; i >= pr . Item2 + s2 . Length ; -- i ) { d2 += pr . Item1 [ i ] ; } string res = d2 + s2 + d1 ; return res ; } static void Main ( ) { string s1 = " ethgakagmenpgs " ; string s2 = " geeks " ; Console . WriteLine ( lexico_smallest ( s1 , s2 ) . Item1 ) ; Console . Write ( lexico_largest ( s1 , s2 ) ) ; } }