# Minimum Swaps to Make Strings Equal in C++

Suppose we have two strings s1 and s2 of equal length consisting of letters only "x" and "y". Our task is to make these two strings equal to each other. We can swap any two characters that belong to different strings, which means − swap s1[i] and s2[j]. We have to find the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so. So if the strings are s1 = “xy” and s2 = “yx”, then the output will be 2. If we swap s1[0] and s2[0], s1 = "yy", s2 = "xx". Then swap s1[0] and s2[1], s1 = "xy", s2 = "xy".

To solve this, we will follow these steps −

• Set x1, x2, y1 and y2 as 0
• for i in range 0 to size of s1
• a := s1[i] and b := s2[i]
• if a is not same as b, then
• if a = ‘x’ then increase x1, otherwise increase y1 by 1
• if b = ‘x’ then increase x2, otherwise increase y2 by 1
• if (x1 + x2) is odd or (y1 + y2) is odd, then return -1
• return x1/2 + y1/2 + (x1 mod 2) * 2

## Example(C++)

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

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minimumSwap(string s1, string s2) {
int x1 = 0, x2 = 0, y1 = 0, y2 = 0;
for(int i = 0; i < s1.size(); i++){
char a = s1[i];
char b = s2[i];
if(a != b){
if(a == 'x')x1++;
else y1++;
if(b == 'x')x2++;
else y2++;
}
}
if ((x1 + x2) & 1 || (y1 + y2) & 1)return -1;
return x1/2 + y1/2 + (x1 % 2) * 2;
}
};
main(){
Solution ob;
cout <<ob.minimumSwap("xy", "yx");
}

## Input

"xy"
"yx"

## Output

2

Updated on: 30-Apr-2020

401 Views