Covert 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 length of each string \in [1, 100000]


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

Approach used :
We have to convert string X into lexicographically smallest anagram of string Y doing minimum replacements in the original string X. We maintain two counter arrays which store the count/frequency of each character in the two strings. Let counters of the two strings be Count_{x} and Count_{y}. 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
(\sum |Count_{x_{i}} - Count_{y_{i}}|)/2, where we iterate for each character i.
Half 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 which 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 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 the 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.






// C++ program to convert string X to
// string Y which minimum number of changes.
#include <bits/stdc++.h>
using namespace std;
#define MAX 26
// Function that converts string X
// into lexicographically smallest
// anagram of string Y with minimal changes
void printAnagramAndChanges(string X, string Y)
    int countx[MAX] = {0}, county[MAX] = {0},
        ctrx[MAX] = {0}, ctry[MAX] = {0};
    int change = 0;
    int l = X.length();
    // Counting frequency of characters
    // in each string.
    for (int i = 0; i < l; i++) {
        countx[X[i] - 'A']++;
        county[Y[i] - 'A']++;
    // 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.
    for (int 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 += abs(county[i] - countx[i]);
    for (int i = 0; i < l; i++) {
        // 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
        if (ctrx[X[i] - 'A'] == 0)
        // 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
        int j;
        for (j = 0; j < MAX; j++)
            if ((ctry[j]) > 0)
        // 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.
        if (countx[X[i] - 'A'] == ctrx[X[i] - 'A']
            || X[i] - 'A' > j) {
            countx[X[i] - 'A']--;
            ctrx[X[i] - 'A']--;
            X[i] = 'A' + j;
            countx[X[i] - 'A']--;
    cout << "Anagram : " << X << endl;
    cout << "Number of changes made : " << change / 2;
// Driver program
int main()
    string x = "CDBABC", y = "ADCABD";
    printAnagramAndChanges(x, y);
    return 0;



Anagram : ADBADC
Number of changes made : 2

The overall time complexity is O(len*26) and as we ignore constants, the complexity is O(len)

My Personal Notes arrow_drop_up

Waba Laba Dub Dub

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.