Lexicographically smallest string after M operations | Function to find the lexicographical smallest string after performing M operations ; Size of the given string ; Declare an array a ; For each i , a [ i ] contain number of operations to update s [ i ] to 'a ; Check if m >= ar [ i ] , then update s [ i ] to ' a ' decrement k by a [ i ] ; Form a cycle of 26 ; Return the answer ; Driver code
def smallest_string ( s , m ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE l = list ( s ) NEW_LINE a = [ 0 ] * n ; NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT distance = ord ( s [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( distance == 0 ) : NEW_LINE INDENT a [ i ] = 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] = 26 - distance ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( m >= a [ i ] ) : NEW_LINE INDENT l [ i ] = ' a ' ; NEW_LINE m = m - a [ i ] ; NEW_LINE DEDENT DEDENT m = m % 26 ; NEW_LINE for i in range ( len ( l ) - 1 ) : NEW_LINE INDENT print ( l [ i ] , end = " " ) NEW_LINE DEDENT print ( chr ( ord ( l [ n - 1 ] ) + m ) ) NEW_LINE DEDENT str = " aazzx " ; NEW_LINE m = 6 ; NEW_LINE smallest_string ( str , m ) ; NEW_LINE