Minimum Number of Steps to Make Two Strings Anagram in C++

Suppose we have two equal-size strings s and t. In one step we can choose any character of t and replace it with another character. We have to find the minimum number of steps required to make t an anagram of s. Note: An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

So if the input is like - “yxy” and “xyx”, then the output will be 1, as only one character is needed to be replaced.

To solve this, we will follow these steps −

  • n := size of characters in s

  • make a map m, and fill this with the frequency of each character present in s, make another map m2, and fill this with the frequency of each character present in t

  • ret := n

  • for each key-value pair it in m

    • x := minimum of value of it, and value of m2[value of it]

    • decrease ret by 1

  • return ret

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   int minSteps(string s, string t) {
      int n = s.size();
      map <char, int> m1;
      for(int i = 0; i < s.size(); i++){
      int ret = n;
      map <char, int> m2;
      for(int i = 0; i < t.size(); i++){
      map <char, int> :: iterator it = m1.begin();
      while(it != m1.end()){
         //cout << it->first << " " << it->second << " " << m2[it->first] << endl;
         int x = min(it->second, m2[it->first]);
         ret -= x;
      return ret;
   Solution ob;
   cout << (ob.minSteps("yxy", "xyx"));





Updated on: 29-Apr-2020


Kickstart Your Career

Get certified by completing the course

Get Started