Lexicographic smallest permutation of a String containing the second String as a Substring | Function to print 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
def findSmallestString ( str1 , str2 ) : NEW_LINE INDENT freq1 = [ 0 ] * 26 NEW_LINE freq2 = [ 0 ] * 26 NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT freq1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT freq2 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT freq1 [ i ] -= freq2 [ i ] NEW_LINE DEDENT res = " " NEW_LINE minIndex = ord ( str2 [ 0 ] ) - ord ( ' a ' ) NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT for j in range ( freq1 [ i ] ) : NEW_LINE INDENT res += chr ( i + ord ( ' a ' ) ) NEW_LINE DEDENT if i == minIndex : NEW_LINE INDENT res += str2 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT str1 = " geeksforgeeksfor " NEW_LINE str2 = " for " NEW_LINE print ( findSmallestString ( str1 , str2 ) ) NEW_LINE