An optimized version that uses reverse instead of sort for finding the next permutation A utility function to reverse a string str [ l . . h ]
def reverse ( str , l , h ) : NEW_LINE INDENT while ( l < h ) : NEW_LINE INDENT str [ l ] , str [ h ] = str [ h ] , str [ l ] NEW_LINE l += 1 NEW_LINE h -= 1 NEW_LINE DEDENT return str NEW_LINE DEDENT