Thursday, July 4, 2024
HomeData ModellingData Structure & AlgorithmMinimum number of swaps to make two binary string equal

Minimum number of swaps to make two binary string equal

Given two binary strings of equal length, the task is to find the minimum number of swaps to make them equal. Swapping between two characters from two different strings is only allowed, return -1 if strings can’t be made equal.

 Examples:

Input: s1 = “0011”, s2 = “1111” 
Output: 1
Explanation:
Swap s1[0] and s2[1].After swap
s1 = 1011 and s2 = 1011 

Input: s1 = “00011”, s2 = “01001”
Output: 2
Explanation:
Swap s1[1] and s2[1]. After swap
s1 = 01011, s2 = 00001 
Swap s1[3] and s2[1]. After swap,
s1 = 01001, s2 = 01001

Approach:

  • Swapping of s1[i] and s2[j] is allowed, so we need to find in which positions two strings are different. If s1[i] and s2[i] are the same, we do not swap them.
  • If s1[i] and s2[i] are not the same then we can find 3 patterns:
    1. 00 and 11, we can perform a diagonal swap and the result will be 01 01 or 10 10. In the case of the diagonal swap, we need to form pairs to solve the disproportion of this type. Swap required to restore a single pair is 1.
    2. 11 and 00, we can perform a diagonal swap and the result will be 01 01 or 10 10. In the case of the diagonal swap, we need to form pairs to solve the disproportion of this type. Swap required to restore a single pair is 1.
    3. 10 and 01, we can perform a vertical swap and the result will be 00 11 or 11 00 and this type will be transformed into type 1 or type 2 problem and another diagonal swap to make them equal. we need to form pair to solve disproportion of this type. Swap required to restore a single pair is 2.
  • From the above observation, we can follow the below greedy method:
    1. Count the positions where s1[i] = 0, and s2[i] = 1 (count0). We need (count0)/2 number of diagonal swaps in each pair of type 1.
    2. Count the positions where s1[i] =1, and s2[i] = 0 (count1). We need (count1)/2 number of diagonal swaps in each pair of type 2.
    3. If both count0 and count1 are even we can output the answer = ((count0) + (count1))/2. If both count0 and count1 is odd, we can have one single pair of type 3 disproportion, so we need 2 extra swaps. Output the answer as ((count0) + (count1))/2 + 2. If one of the count0 and count1 is odd, we can not make two strings equal. As in all cases we need to form pairs, odd count means a single position will be left alone making 2 strings unequal.

Below is the implementation of above approach: 

C++




// C++ program for
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate
// min swaps to make
// binary strings equal
int minSwaps(string& s1, string& s2)
{
 
    int c0 = 0, c1 = 0;
 
    for (int i = 0; i < s1.size(); i++) {
        // Count of zero's
        if (s1[i] == '0' && s2[i] == '1') {
            c0++;
        }
        // Count of one's
        else if (s1[i] == '1' && s2[i] == '0') {
            c1++;
        }
    }
 
    // As discussed
    // above
    int ans = c0 / 2 + c1 / 2;
 
    if (c0 % 2 == 0 && c1 % 2 == 0) {
        return ans;
    }
    else if ((c0 + c1) % 2 == 0) {
        return ans + 2;
    }
    else {
        return -1;
    }
}
 
// Driver code
int main()
{
 
    string s1 = "0011", s2 = "1111";
    int ans = minSwaps(s1, s2);
 
    cout << ans << '\n';
 
    return 0;
}


Java




// Java program for the above approach
 
class GFG
{
 
    // Function to calculate
    // min swaps to make
    // binary strings equal
    static int minSwaps(String s1, String s2)
    {
     
        int c0 = 0, c1 = 0;
     
        for (int i = 0; i < s1.length(); i++)
        {
            // Count of zero's
            if (s1.charAt(i) == '0' && s2.charAt(i) == '1')
            {
                c0++;
            }
             
            // Count of one's
            else if (s1.charAt(i) == '1' && s2.charAt(i) == '0')
            {
                c1++;
            }
        }
     
        // As discussed
        // above
        int ans = c0 / 2 + c1 / 2;
     
        if (c0 % 2 == 0 && c1 % 2 == 0)
        {
            return ans;
        }
        else if ((c0 + c1) % 2 == 0)
        {
            return ans + 2;
        }
        else
        {
            return -1;
        }
    }
     
    // Driver code
    public static void main (String[] args)
    {
     
        String s1 = "0011", s2 = "1111";
        int ans = minSwaps(s1, s2);
     
        System.out.println(ans);
     
    }
 
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 program for
# the above approach
 
# Function to calculate
# min swaps to make
# binary strings equal
def minSwaps(s1, s2) :
 
    c0 = 0; c1 = 0;
 
    for i in range(len(s1)) :
         
        # Count of zero's
        if (s1[i] == '0' and s2[i] == '1') :
            c0 += 1;
     
        # Count of one's
        elif (s1[i] == '1' and s2[i] == '0') :
            c1 += 1;
 
    # As discussed above
    ans = c0 // 2 + c1 // 2;
 
    if (c0 % 2 == 0 and c1 % 2 == 0) :
        return ans;
     
    elif ((c0 + c1) % 2 == 0) :
        return ans + 2;
 
    else :
        return -1;
 
# Driver code
if __name__ == "__main__" :
 
    s1 = "0011"; s2 = "1111";
     
    ans = minSwaps(s1, s2);
 
    print(ans);
 
# This code is contributed by AnkitRai01


C#




// C# program for the above approach
using System;
 
class GFG
{
 
    // Function to calculate
    // min swaps to make
    // binary strings equal
    static int minSwaps(string s1, string s2)
    {
     
        int c0 = 0, c1 = 0;
     
        for (int i = 0; i < s1.Length; i++)
        {
            // Count of zero's
            if (s1[i] == '0' && s2[i] == '1')
            {
                c0++;
            }
             
            // Count of one's
            else if (s1[i] == '1' && s2[i] == '0')
            {
                c1++;
            }
        }
     
        // As discussed
        // above
        int ans = c0 / 2 + c1 / 2;
     
        if (c0 % 2 == 0 && c1 % 2 == 0)
        {
            return ans;
        }
        else if ((c0 + c1) % 2 == 0)
        {
            return ans + 2;
        }
        else
        {
            return -1;
        }
    }
     
    // Driver code
    public static void Main ()
    {
     
        string s1 = "0011", s2 = "1111";
        int ans = minSwaps(s1, s2);
     
        Console.WriteLine(ans);
     
    }
 
}
 
// This code is contributed by AnkitRai01


Javascript




// Javascript program for the above approach
 
// Function to calculate
// min swaps to make
// binary strings equal
function minSwaps(s1, s2)
{
 
    let c0 = 0;
    let c1 = 0;
 
    for (let i = 0; i < s1.length; i++) {
        // Count of zero's
        if (s1[i] == '0' && s2[i] == '1') {
            c0++;
        }
        // Count of one's
        else if (s1[i] == '1' && s2[i] == '0') {
            c1++;
        }
    }
 
    // As discussed
    // above
    let ans = c0 / 2 + c1 / 2;
 
    if (c0 % 2 == 0 && c1 % 2 == 0) {
        return ans;
    }
    else if ((c0 + c1) % 2 == 0) {
        return ans + 2;
    }
    else {
        return -1;
    }
}
 
// Driver code
let s1 = "0011";
let s2 = "1111";
let ans = minSwaps(s1, s2);
 
console.log(ans);
 
// This code is contributed by Samim Hossain Mondal.


Output:

1

Time Complexity: O(n)
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Another Approach:

  1. Initialize two empty vectors pos1 and pos2.
  2. Initialize an integer variable diff to 0.
  3. Traverse both strings s1 and s2 from index 0 to n-1, where n is the length of the strings.
  4. If the characters at index i in s1 and s2 are not equal, increment diff by 1 and do the following:
    a. If the character at index i in s1 is ‘0’, append i to the pos1 vector.
    b. Else, append i to the pos2 vector.
  5. If diff is odd, return -1.
  6. Initialize a swaps variable to 0.
  7. Traverse the pos1 vector from index 0 to pos1.size()-1, incrementing i by 2 in each iteration.
  8. If the character at index pos1[i] in s2 is ‘1’, increment swaps by 1.
  9. Traverse the pos2 vector from index 0 to pos2.size()-1, incrementing i by 2 in each iteration.
  10. If the character at index pos2[i] in s1 is ‘1’, increment swaps by 1.
  11. Return the swaps variable.

Below is the implementation of the above approach:

C++




// C++ program for
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate
// min swaps to make
// binary strings equal
int minSwaps(string s1, string s2) {
    int n = s1.length();
    int diff = 0;
    vector<int> pos1, pos2;
    for (int i = 0; i < n; i++) {
        if (s1[i] != s2[i]) {
            diff++;
            if (s1[i] == '0') {
                pos1.push_back(i);
            } else {
                pos2.push_back(i);
            }
        }
    }
    if (diff % 2 != 0) {
        return -1;
    }
    int swaps = 0;
    for (int i = 0; i < pos1.size(); i += 2) {
        if (s2[pos1[i]] == '1') {
            swaps++;
        }
    }
    for (int i = 0; i < pos2.size(); i += 2) {
        if (s1[pos2[i]] == '1') {
            swaps++;
        }
    }
    return swaps;
}
 
// Driver code
int main()
{
 
    string s1 = "0011", s2 = "1111";
    int ans = minSwaps(s1, s2);
 
    cout << ans << '\n';
 
    return 0;
}


Output

1

Time complexity: O(n)
Auxiliary Space: O(n)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments