Convert string X to an anagram of string Y with minimum replacements
Given two strings X and Y, we need to convert string X into an anagram of string Y with minimum replacements. If we have multiple ways of achieving the target, we go for the lexicographically smaller string where the length of each string
Input : X = "CDBABC" Y = "ADCABD" Output : Anagram : ADBADC Number of changes made: 2 Input : X = "PJPOJOVMAK" Y = "FVACRHLDAP" Output : Anagram : ACPDFHVLAR Number of changes made: 7
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Approach used :
We have to convert string X into a lexicographically smallest anagram of string Y doing minimum replacements in the original string X. We maintain two counter arrays that store the count/frequency of each character in the two strings. Let counters of the two strings be and . Now, anagrams by definition mean that the frequency of the characters in two anagrams is always equal. Thus, to convert string X into an anagram of string Y, the frequency of characters should be equal. Therefore, the total number of alteration we need to make in total to convert string X into an anagram of string Y is
, where we iterate for each character i.
Half the job is done as we know how many replacements are to be done. We now need the lexicographically smaller string. Now, for a specific position, we look for all possible characters from ‘A’ to ‘Z’ and check for each character whether it could be fit in this position or now. For a better understanding, we iterate for each position in the string. Check if is there is a character that is there in string Y and not in string X (or the frequency of character is more in string Y and less in string X). Now, if there is one, we check that the character at the current position in X, is it unnecessary? i.e. does it have more frequency in string X and less frequency in string Y. Now, if all the boxes are ticked, we further check if we insert the character in this position, as we need to generate the lexicographically smaller string. If all the conditions are true, we replace the character in string X with the character in string Y. After all such replacements, we can print the altered string X as the output.
Anagram : ADBADC Number of changes made : 2
The overall time complexity is and as we ignore constants, the complexity is