Lexicographically smallest string after M operations | Java 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
class GFG { static void smallest_String ( char [ ] s , int m ) { int n = s . length ; int [ ] a = new int [ 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 ] = ( char ) ( s [ n - 1 ] + m ) ; System . out . print ( String . valueOf ( s ) ) ; } public static void main ( String [ ] args ) { String str = " aazzx " ; int m = 6 ; smallest_String ( str . toCharArray ( ) , m ) ; } }