Lexicographically smallest string which differs from given strings at exactly K indices | Java program for the above approach ; Function to find the String which differ at exactly K positions ; Initialise s3 as s2 ; Number of places at which s3 differ from s2 ; Minimum possible value is Math . ceil ( d / 2 ) if it is not possible then - 1 ; Case 2 when K is less equal d ; X show the modification such that this position only differ from only one String ; modify the position such that this differ from both S1 & S2 & decrease the T at each step ; Finding the character which is different from both S1 and S2 ; After we done T start modification to meet our requirement for X type ; Resultant String ; Case 1 when K > d In first step , modify all the character which are not same in S1 and S3 ; Finding character which is different from both S1 and S2 ; Our requirement not satisfied by performing step 1. We need to modify the position which matches in both String ; Finding the character which is different from both S1 and S2 ; Resultant String ; Driver Code ; Given two Strings ; Function Call
import java . util . * ; class GFG { static char arr [ ] = { ' a ' , ' b ' , ' c ' } ; static void findString ( int n , int k , char [ ] s1 , char [ ] s2 ) { char [ ] s3 = s2 ; int d = 0 ; for ( int i = 0 ; i < s1 . length ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) d ++ ; } if ( ( d + 1 ) / 2 > k ) { System . out . print ( " - 1" + "NEW_LINE"); return ; } else { if ( k <= d ) { int X = d - k ; int T = 2 * k - d ; for ( int i = 0 ; i < s3 . length ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) { if ( T > 0 ) { for ( int j = 0 ; j < 3 ; j ++ ) { if ( arr [ j ] != s1 [ i ] && arr [ j ] != s2 [ i ] ) { s3 [ i ] = arr [ j ] ; T -- ; break ; } } } else if ( X > 0 ) { s3 [ i ] = s1 [ i ] ; X -- ; } } } System . out . print ( new String ( s3 ) + "NEW_LINE"); } else { for ( int i = 0 ; i < s1 . length ; i ++ ) { if ( s1 [ i ] != s3 [ i ] ) { for ( int j = 0 ; j < 3 ; j ++ ) { if ( arr [ j ] != s1 [ i ] && arr [ j ] != s3 [ i ] ) { s3 [ i ] = arr [ j ] ; k -- ; break ; } } } } for ( int i = 0 ; i < s1 . length ; i ++ ) { if ( s1 [ i ] == s3 [ i ] && k > 0 ) { for ( int j = 0 ; j < 3 ; j ++ ) { if ( arr [ j ] != s1 [ i ] && arr [ j ] != s3 [ i ] ) { s3 [ i ] = arr [ j ] ; k -- ; break ; } } } } System . out . print ( new String ( s3 ) + "NEW_LINE"); } } } public static void main ( String [ ] args ) { int N = 4 , k = 2 ; String S1 = " zzyy " ; String S2 = " zxxy " ; findString ( N , k , S1 . toCharArray ( ) , S2 . toCharArray ( ) ) ; } }