Lexicographically smallest string which differs from given strings at exactly K indices | javascript 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
var arr = [ ' ' , ' ' , ' ' ] ; function findString ( n , k , s1 , s2 ) { var s3 = s2 ; var d = 0 ; for ( i = 0 ; i < s1 . length ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) d ++ ; } if ( ( d + 1 ) / 2 > k ) { document . write ( " " + " " ) ; return ; } else { if ( k <= d ) { var X = d - k ; var T = 2 * k - d ; for ( i = 0 ; i < s3 . length ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) { if ( T > 0 ) { for ( 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 -- ; } } } document . write ( s3 . join ( ' ' ) + " " ) ; } else { for ( i = 0 ; i < s1 . length ; i ++ ) { if ( s1 [ i ] != s3 [ i ] ) { for ( j = 0 ; j < 3 ; j ++ ) { if ( arr [ j ] != s1 [ i ] && arr [ j ] != s3 [ i ] ) { s3 [ i ] = arr [ j ] ; k -- ; break ; } } } } for ( i = 0 ; i < s1 . length ; i ++ ) { if ( s1 [ i ] == s3 [ i ] && k > 0 ) { for ( j = 0 ; j < 3 ; j ++ ) { if ( arr [ j ] != s1 [ i ] && arr [ j ] != s3 [ i ] ) { s3 [ i ] = arr [ j ] ; k -- ; break ; } } } } document . write ( s3 . join ( ' ' ) + " " ) ; } } } var N = 4 , k = 2 ; var S1 = " " ; var S2 = " " ; findString ( N , k , S1 . split ( ' ' ) , S2 . split ( ' ' ) ) ;