- Related Questions & Answers
- Add minimum number to an array so that the sum becomes even in C programming
- Print triplets with sum less than or equal to k in C Program
- Comparing Strings with (possible) null values in java?
- How to check if two dates are equal in Java 8?
- How many ways to make an object eligible for GC in Java?
- Can we make static reference to non-static fields in java?
- In how many ways we can concatenate Strings in Java?
- Can we make Array volatile using volatile keyword in Java?
- Prim’s (Minimum Spanning Tree) MST Algorithm
- Kruskal’s (Minimum Spanning Tree) MST Algorithm
- How do you find continuous sub array whose sum is equal to a given number in Java?
- How to find all pairs of elements in Java array whose sum is equal to a given number?
- How to make a singleton enum in Java?
- How to make a specific text on TextView bold in Android?
- How to make an object completely encapsulated in java?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

Let us see the following implementation to get better understanding −

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; } };

"xy" "yx"

2

Advertisements