Lexicographically smallest string formed by appending a character from the first K characters of a given string | Function to find the new string thus formed by removing characters ; new string ; Remove characters until the string is empty ; Traverse to find the smallest character in the first k characters ; append the smallest character ; removing the lexicographically smallest character from the string ; Driver Code
def newString ( s , k ) : NEW_LINE INDENT X = " " NEW_LINE while ( len ( s ) > 0 ) : NEW_LINE INDENT temp = s [ 0 ] NEW_LINE i = 1 NEW_LINE while ( i < k and i < len ( s ) ) : NEW_LINE INDENT if ( s [ i ] < temp ) : NEW_LINE INDENT temp = s [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT X = X + temp NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( s [ i ] == temp ) : NEW_LINE INDENT s = s [ 0 : i ] + s [ i + 1 : ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT return X NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " gaurang " NEW_LINE k = 3 NEW_LINE print ( newString ( s , k ) ) NEW_LINE DEDENT