Lexicographically smallest string after M operations | C ++ implementation to find the lexicographical smallest string after performing 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 ; update last element of string with the value s [ i ] + ( k % 26 ) ; Return the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void smallest_string ( string s , int m ) { int n = s . size ( ) ; int a [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int distance = s [ i ] - ' a ' ; if ( distance == 0 ) a [ i ] = 0 ; else a [ i ] = 26 - distance ; } for ( int i = 0 ; i < n ; i ++ ) { if ( m >= a [ i ] ) { s [ i ] = ' a ' ; m = m - a [ i ] ; } } m = m % 26 ; s [ n - 1 ] = s [ n - 1 ] + m ; cout << s ; } int main ( ) { string str = " aazzx " ; int m = 6 ; smallest_string ( str , m ) ; return 0 ; }