Traverse from end and swap spaces
i = len ( s ) - 1 ; NEW_LINE for j in range ( i , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ j ] != ' ▁ ' ) : NEW_LINE INDENT s = swap ( s , i , j ) ; NEW_LINE i -= 1 ; NEW_LINE DEDENT DEDENT return s ; NEW_LINE def swap ( c , i , j ) : NEW_LINE c = list ( c ) NEW_LINE c [ i ] , c [ j ] = c [ j ] , c [ i ] NEW_LINE return ' ' . join ( c ) NEW_LINE