Lexicographically smallest string possible by performing K operations on a given string | Function to find the lexicographically smallest possible string by performing K operations on string S ; Store the size of string , s ; Check if k >= n , if true , convert every character to 'a ; Iterate in range [ 0 , n - 1 ] using i ; When k reaches 0 , break the loop ; If current character is ' a ' , continue ; Otherwise , iterate in the range [ i + 1 , n - 1 ] using j ; Check if s [ j ] > s [ i ] ; If true , set s [ j ] = s [ i ] and break out of the loop ; Check if j reaches the last index ; Update S [ i ] ; Decrement k by 1 ; Print string ; Driver Code ; Given String , s ; Given k ; Function Call
def smallestlexicographicstring ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( k >= n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT s [ i ] = ' a ' ; NEW_LINE DEDENT print ( s , end = ' ' ) NEW_LINE return ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( s [ j ] > s [ i ] ) : NEW_LINE INDENT s [ j ] = s [ i ] ; NEW_LINE break ; NEW_LINE DEDENT elif ( j == n - 1 ) : NEW_LINE INDENT s [ j ] = s [ i ] ; NEW_LINE DEDENT DEDENT s [ i ] = ' a ' ; NEW_LINE k -= 1 NEW_LINE DEDENT print ( ' ' . join ( s ) , end = ' ' ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = list ( " geeksforgeeks " ) ; NEW_LINE k = 6 ; NEW_LINE smallestlexicographicstring ( s , k ) ; NEW_LINE DEDENT