Lexicographically smaller string by swapping at most one character pair | Function that finds whether is it possible to make string A lexicographically smaller than string B ; Condition if string A is already smaller than B ; Sorting temp string ; Condition for first changed character of string A and temp ; Condition if string A is already sorted ; Finding first changed character from last of string A ; Swap the two characters ; Condition if string A is smaller than B ; Driver Code
def IsLexicographicallySmaller ( A , B ) : NEW_LINE INDENT if ( A < B ) : NEW_LINE INDENT return True NEW_LINE DEDENT temp = A NEW_LINE temp = ' ' . join ( sorted ( temp ) ) NEW_LINE index = - 1 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] != temp [ i ] ) : NEW_LINE INDENT index = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( index == - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT j = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] == temp [ index ] ) : NEW_LINE INDENT j = i NEW_LINE DEDENT DEDENT A = list ( A ) NEW_LINE A [ index ] , A [ j ] = A [ j ] , A [ index ] NEW_LINE A = ' ' . join ( A ) NEW_LINE if ( A < B ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT A = " AGAIN " NEW_LINE B = " ACTION " NEW_LINE if ( IsLexicographicallySmaller ( A , B ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT