Greatest number less than equal to B that can be formed from the digits of A | Function to return the greatest number not gtreater than B that can be formed with the digits of A ; To store size of A ; To store the required answer ; Traverse from leftmost digit and place a smaller digit for every position . ; Keep all digits in A ; To avoid leading zeros ; For all possible values at ith position from largest value to smallest ; Take largest possible digit ; Keep duplicate of string a ; Remove the taken digit from s2 ; Sort all the remaining digits of s2 ; Add s2 to current s1 ; If s1 is less than B then it can be included in the answer . Note that int ( ) converts a string to integer ; change A to s2 ; Return the required answer ; Driver Code
def permuteDigits ( a : str , b : int ) -> str : NEW_LINE INDENT n = len ( a ) NEW_LINE ans = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = set ( list ( a ) ) NEW_LINE if i == 0 : NEW_LINE INDENT temp . discard ( 0 ) NEW_LINE DEDENT for j in reversed ( list ( temp ) ) : NEW_LINE INDENT s1 = ans + j NEW_LINE s2 = list ( a ) . copy ( ) NEW_LINE s2 . remove ( j ) NEW_LINE s2 = ' ' . join ( sorted ( list ( s2 ) ) ) NEW_LINE s1 += s2 NEW_LINE if int ( s1 ) <= b : NEW_LINE INDENT ans += j NEW_LINE a = ' ' . join ( list ( s2 ) ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = "123" NEW_LINE b = 222 NEW_LINE print ( permuteDigits ( a , b ) ) NEW_LINE DEDENT