Lexicographically smallest string possible by performing K operations on a given string | Java program to implement the above approach ; 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
public class GFG { static void smallestlexicographicstring ( char [ ] s , int k ) { int n = s . length ; if ( k >= n ) { for ( int i = 0 ; i < n ; i ++ ) { s [ i ] = ' a ' ; } System . out . print ( s ) ; return ; } for ( int i = 0 ; i < n ; i ++ ) { if ( k == 0 ) { break ; } if ( s [ i ] == ' a ' ) continue ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( s [ j ] > s [ i ] ) { s [ j ] = s [ i ] ; break ; } else if ( j == n - 1 ) s [ j ] = s [ i ] ; } s [ i ] = ' a ' ; k -- ; } System . out . print ( s ) ; } public static void main ( String [ ] args ) { char [ ] s = ( " geeksforgeeks " ) . toCharArray ( ) ; int k = 6 ; smallestlexicographicstring ( s , k ) ; } }