you are given two strings which are anagram of each other return minimum number of swaps to make two strings equal code example

Example 1: what do you mean by smallest anagram of a string

#include<iostream>
#include<algorithm>

using namespace std;

int main(){
string s,p;
int t;
cin>>t;
while(t--){
int j=0,i=0;
cin>>s>>p;

 while (i<s.length())
 {
    if(p[j]==s[i]){
    s.erase(s.begin()+i);
    j++;
    i=0;
    
  
    

  }
  else
  {
    i++;
  }
  
   
 }
 

int k=-1;
sort(s.begin(),s.end());
for (int i = 0; i < s.length(); i++)
{
  if(p[0]>=s[i])
  k=i;
}
s.insert(k+1,p);
cout<<s<<endl;
}
return 0;
}

Example 2: what do you mean by smallest anagram of a string

#include<bits/stdc++.h>
using namespace std;
int main(){
   int t;
   cin>>t;
   while(t--)
   {
       string s,p;
       cin>>s;
       cin>>p;

       map<char,int> ms,mp;
       for(int i=0;i<s.length();i++)
         ms[s[i]]++;
       for(int i=0;i<p.length();i++)
         mp[p[i]]++;
       for(auto it=mp.begin();it!=mp.end();it++)
       {
           ms[it->first]-=it->second;
       }
       string temp="";
       for(auto it=ms.begin();it!=ms.end();it++)
       {
           if(it->first!=p[0]){
           while(ms[it->first]>0)
           {
               temp+=it->first;
               ms[it->first]--;
           }
           
           }
           else
           {
               break;
           }
       }
       if(p[0]<p[1]){
       while(ms[p[0]]>0)
         {
           temp+=p[0];
           ms[p[0]]--;
         }
       }
       // cout<<temp;
      
       temp+=p;
       for(auto it=ms.begin();it!=ms.end();it++)
       {
           while(ms[it->first]>0){
              temp+=it->first;
              ms[it->first]--;}
       }
       cout<<temp<<endl;
   }
}

Tags:

Cpp Example