Open In App

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:

Below is the implementation of above approach: 




// 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 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 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# 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 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++ 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;
}




import java.util.ArrayList;
import java.util.List;
 
public class MinimumSwapsToMakeBinaryStringsEqual {
 
    // Function to calculate min swaps to make binary strings equal
    public static int minSwaps(String s1, String s2) {
        int n = s1.length();
        int diff = 0;
        List<Integer> pos1 = new ArrayList<>();
        List<Integer> pos2 = new ArrayList();
 
        // Count the differences and store their positions
        for (int i = 0; i < n; i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                diff++;
                if (s1.charAt(i) == '0') {
                    pos1.add(i);
                } else {
                    pos2.add(i);
                }
            }
        }
 
        // If the number of differences is odd, it's impossible to make them equal
        if (diff % 2 != 0) {
            return -1;
        }
 
        int swaps = 0;
 
        // Count swaps required for positions with '0' in s1 and '1' in s2
        for (int i = 0; i < pos1.size(); i += 2) {
            if (s2.charAt(pos1.get(i)) == '1') {
                swaps++;
            }
        }
 
        // Count swaps required for positions with '0' in s2 and '1' in s1
        for (int i = 0; i < pos2.size(); i += 2) {
            if (s1.charAt(pos2.get(i)) == '1') {
                swaps++;
            }
        }
 
        return swaps;
    }
 
    public static void main(String[] args) {
        String s1 = "0011";
        String s2 = "1111";
        int ans = minSwaps(s1, s2);
 
        System.out.println(ans);
    }
}




# Function to calculate
# min swaps to make
# binary strings equal
 
 
def min_swaps(s1, s2):
    n = len(s1)
    diff = 0
    pos1, pos2 = [], []
 
    # Count differences and store positions
    for i in range(n):
        if s1[i] != s2[i]:
            diff += 1
            if s1[i] == '0':
                pos1.append(i)
            else:
                pos2.append(i)
 
    # If the number of differences is odd, it's not possible
    if diff % 2 != 0:
        return -1
 
    swaps = 0
    # Count swaps for pos1
    for i in range(0, len(pos1), 2):
        if s2[pos1[i]] == '1':
            swaps += 1
 
    # Count swaps for pos2
    for i in range(0, len(pos2), 2):
        if s1[pos2[i]] == '1':
            swaps += 1
 
    return swaps
 
 
# Driver code
if __name__ == "__main__":
    s1 = "0011"
    s2 = "1111"
    ans = min_swaps(s1, s2)
 
    print(ans)




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to calculate min swaps to make binary strings equal
    static int MinSwaps(string s1, string s2)
    {
        int n = s1.Length;
        int diff = 0;
        List<int> pos1 = new List<int>();
        List<int> pos2 = new List<int>();
 
        // Count the differences and record positions
        for (int i = 0; i < n; i++)
        {
            if (s1[i] != s2[i])
            {
                diff++;
                if (s1[i] == '0')
                {
                    pos1.Add(i);
                }
                else
                {
                    pos2.Add(i);
                }
            }
        }
 
        // If the number of differences is odd, it is not possible to make strings equal
        if (diff % 2 != 0)
        {
            return -1;
        }
 
        int swaps = 0;
 
        // Count swaps for the first set of positions
        for (int i = 0; i < pos1.Count; i += 2)
        {
            if (s2[pos1[i]] == '1')
            {
                swaps++;
            }
        }
 
        // Count swaps for the second set of positions
        for (int i = 0; i < pos2.Count; i += 2)
        {
            if (s1[pos2[i]] == '1')
            {
                swaps++;
            }
        }
 
        return swaps;
    }
 
    // Driver code
    static void Main()
    {
        string s1 = "0011", s2 = "1111";
        int ans = MinSwaps(s1, s2);
 
        Console.WriteLine(ans);
    }
}




// Function to calculate min swaps to make binary strings equal
function minSwaps(s1, s2) {
    const n = s1.length;
    let diff = 0;
    const pos1 = [];
    const pos2 = [];
 
    // Count the differences and store their positions
    for (let i = 0; i < n; i++) {
        if (s1[i] !== s2[i]) {
            diff++;
            if (s1[i] === '0') {
                pos1.push(i);
            } else {
                pos2.push(i);
            }
        }
    }
 
    // If the number of differences is not even, it's impossible to make them equal
    if (diff % 2 !== 0) {
        return -1;
    }
 
    let swaps = 0;
 
    // Calculate the number of swaps required to make the strings equal
    for (let i = 0; i < pos1.length; i += 2) {
        if (s2[pos1[i]] === '1') {
            swaps++;
        }
    }
 
    for (let i = 0; i < pos2.length; i += 2) {
        if (s1[pos2[i]] === '1') {
            swaps++;
        }
    }
 
    return swaps;
}
 
// Driver code
const s1 = "0011";
const s2 = "1111";
const ans = minSwaps(s1, s2);
 
console.log(ans);

Output
1





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


Article Tags :