Convert string X to an anagram of string Y with minimum replacements | JavaScript program to convert string X to string Y which minimum number of changes . ; Function that converts string X into lexicographically smallest anagram of string Y with minimal changes ; Counting frequency of characters in each string . ; We maintain two more counter arrays ctrx [ ] and ctry [ ] Ctrx [ ] maintains the count of extra elements present in string X than string Y Ctry [ ] maintains the count of characters missing from string X which should be present in string Y . ; This means that we cannot edit the current character as it 's frequency  in string X is equal to or less  than the frequency in string Y.  Thus, we go to the next position ; Here , we try to find that character , which has more frequency in string Y and less in string X . We try to find this character in lexicographical order so that we get lexicographically smaller string ; This portion deals with the lexicographical property . Now , we put a character in string X when either this character has smaller value than the character present there right now or if this is the last position for it to exchange , else we fix the character already present here in this position . ; Driver code
const MAX = 26 ; function printAnagramAndChanges ( X , Y ) { var countx = new Array ( MAX ) . fill ( 0 ) ; var county = new Array ( MAX ) . fill ( 0 ) ; var ctrx = new Array ( MAX ) . fill ( 0 ) ; var ctry = new Array ( MAX ) . fill ( 0 ) ; var change = 0 ; var l = X . length ; for ( var i = 0 ; i < l ; i ++ ) { countx [ X [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; county [ Y [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; } for ( var i = 0 ; i < MAX ; i ++ ) { if ( countx [ i ] > county [ i ] ) { ctrx [ i ] += countx [ i ] - county [ i ] ; } else if ( countx [ i ] < county [ i ] ) { ctry [ i ] += county [ i ] - countx [ i ] ; } change += Math . abs ( county [ i ] - countx [ i ] ) ; } for ( var i = 0 ; i < l ; i ++ ) { if ( ctrx [ X [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] === 0 ) { continue ; } var j ; for ( j = 0 ; j < MAX ; j ++ ) { if ( ctry [ j ] > 0 ) { break ; } } if ( countx [ X [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] === ctrx [ X [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] || X [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) > j ) { countx [ X [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] -- ; ctrx [ X [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] -- ; ctry [ j ] -- ; X [ i ] = String . fromCharCode ( " " . charCodeAt ( 0 ) + j ) ; } else { countx [ X [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] -- ; } } document . write ( " " + X . join ( " " ) + " " ) ; document . write ( " " + change / 2 ) ; } var x = " " , y = " " ; printAnagramAndChanges ( x . split ( " " ) , y . split ( " " ) ) ;