Lexicographically smallest string whose hamming distance from given string is exactly K | Java program to find Lexicographically smallest string whose hamming distance from given string is exactly K ; function to find Lexicographically smallest string with hamming distance k ; If k is 0 , output input string ; Copying input string into output string ; Traverse all the character of the string ; If current character is not ' a ' ; copy character ' a ' to output string ; str2 [ i ] = ' a ' ; ; If hamming distance became k , break ; ; If k is less than p ; Traversing string in reverse order ; Driven Program
class GFG { static void findString ( String str , int n , int k ) { if ( k == 0 ) { System . out . println ( str ) ; ; return ; } String str2 = str ; int p = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str2 . charAt ( i ) != ' a ' ) { str2 = str2 . substring ( 0 , i ) + ' a ' + str2 . substring ( i + 1 ) ; p ++ ; if ( p == k ) break ; } } if ( p < k ) { for ( int i = n - 1 ; i >= 0 ; i -- ) if ( str . charAt ( i ) == ' a ' ) { str2 = str2 . substring ( 0 , i ) + ' b ' + str2 . substring ( i + 1 ) ; p ++ ; if ( p == k ) break ; } } System . out . println ( str2 ) ; } public static void main ( String [ ] args ) { String str = " pqrs " ; int n = str . length ( ) ; int k = 2 ; findString ( str , n , k ) ; } }