Open In App

Minimum adjacent swaps required to make a binary string alternating

Last Updated : 08 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary string S of size N, the task is to find the number of minimum adjacent swaps required to make the string alternate. If it is not possible to do so, then print -1.

Examples: 

Input: S = “10011”
Output: 1
Explanation:
Swap index 2 and index 3 and the string becomes 10101 .

Input: S = “110100”
Output: 2
Explanation: 
First, swap index 1 and index 2 and the string becomes 101100 . 
Second, swap index 3 and index 4 and the string becomes 101010 .

 

Approach: For making the string alternating either get “1” or “0” at the first position. When the length of the string is even, the string must be starting with “0” or “1”. When the length of the string is odd, there are two possible cases – if the no. of 1’s in the string is greater than no of 0’s in the string, the string must start with “1″. Otherwise if the no. of 0’s is greater than no of 1’s, the string must start with “0”. So, check for both the cases where the binary string starts with “1” at the first position and  “0” at the first position. Follow the steps below to solve the problem:

  • Initialize the variables ones and zeros as 0 to count the number of zeros and ones in the string.
  • Iterate over the range [0, N) using the variable i and count the number of 0’s and 1’s in the binary string.
  • Check for the base cases, i.e, if N is even then if zeros are equal to ones or not. And if N is odd, then the difference between them should be 1. If the base cases don’t satisfy, then return -1.
  • Initialize the variable ans_1 as 0 to store the answer when the string starts with 1 and j as 0.
  • Iterate over the range [0, N) using the variable i and if s[i] equals 1, then add the value of abs(j-i) to the variable ans_1 and increase the value of j by 2.
  • Similarly, initialize the variable ans_0 as 0 to store the answer when the string starts with 1 and k as 0.
  • Iterate over the range [0, N) using the variable i and if s[i] equals 0, then add the value of abs(k – i) to the variable ans_0 and increase the value of k by 2.
  • If N is even, then print the minimum of ans_1 or ans_0 as the result. Otherwise, if zeros is greater than ones, then print ans_0. Otherwise, print ans_1.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number
// of adjacent swaps to make the string
// alternating
int minSwaps(string s)
{
    // Count the no of zeros and ones
    int ones = 0, zeros = 0;
    int N = s.length();
 
    for (int i = 0; i < N; i++) {
        if (s[i] == '1')
            ones++;
        else
            zeros++;
    }
 
    // Base Case
    if ((N % 2 == 0 && ones != zeros)
        || (N % 2 == 1
            && abs(ones - zeros) != 1)) {
        return -1;
    }
 
    // Store no of min swaps when
    // string starts with "1"
    int ans_1 = 0;
 
    // Keep track of the odd positions
    int j = 0;
 
    // Checking for when the string
    // starts with "1"
    for (int i = 0; i < N; i++) {
        if (s[i] == '1') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_1 += abs(j - i);
            j += 2;
        }
    }
 
    // Store no of min swaps when string
    // starts with "0"
    int ans_0 = 0;
 
    // Keep track of the odd positions
    int k = 0;
 
    // Checking for when the string
    // starts with "0"
    for (int i = 0; i < N; i++) {
        if (s[i] == '0') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_0 += abs(k - i);
            k += 2;
        }
    }
 
    // Returning the answer based on
    // the conditions when string
    // length is even
    if (N % 2 == 0)
        return min(ans_1, ans_0);
 
    // When string length is odd
    else {
 
        // When no of ones is greater
        // than no of zeros
        if (ones > zeros)
            return ans_1;
 
        // When no of ones is greater
        // than no of zeros
        else
            return ans_0;
    }
}
 
// Driver Code
int main()
{
    string S = "110100";
    cout << minSwaps(S);
 
    return 0;
}


Java




// Java program for the above approach
 
import java.util.*;
 
class GFG{
 
// Function to find the minimum number
// of adjacent swaps to make the String
// alternating
static int minSwaps(String s)
{
    // Count the no of zeros and ones
    int ones = 0, zeros = 0;
    int N = s.length();
 
    for (int i = 0; i < N; i++) {
        if (s.charAt(i) == '1')
            ones++;
        else
            zeros++;
    }
 
    // Base Case
    if ((N % 2 == 0 && ones != zeros)
        || (N % 2 == 1
            && Math.abs(ones - zeros) != 1)) {
        return -1;
    }
 
    // Store no of min swaps when
    // String starts with "1"
    int ans_1 = 0;
 
    // Keep track of the odd positions
    int j = 0;
 
    // Checking for when the String
    // starts with "1"
    for (int i = 0; i < N; i++) {
        if (s.charAt(i) == '1') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_1 += Math.abs(j - i);
            j += 2;
        }
    }
 
    // Store no of min swaps when String
    // starts with "0"
    int ans_0 = 0;
 
    // Keep track of the odd positions
    int k = 0;
 
    // Checking for when the String
    // starts with "0"
    for (int i = 0; i < N; i++) {
        if (s.charAt(i) == '0') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_0 += Math.abs(k - i);
            k += 2;
        }
    }
 
    // Returning the answer based on
    // the conditions when String
    // length is even
    if (N % 2 == 0)
        return Math.min(ans_1, ans_0);
 
    // When String length is odd
    else {
 
        // When no of ones is greater
        // than no of zeros
        if (ones > zeros)
            return ans_1;
 
        // When no of ones is greater
        // than no of zeros
        else
            return ans_0;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "110100";
    System.out.print(minSwaps(S));
 
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python 3 program for the above approach
 
# Function to find the minimum number
# of adjacent swaps to make the string
# alternating
def minSwaps(s):
   
    # Count the no of zeros and ones
    ones = 0
    zeros = 0
    N = len(s)
 
    for i in range(N):
        if s[i] == '1':
            ones += 1
        else:
            zeros += 1
 
    # Base Case
    if ((N % 2 == 0 and ones != zeros) or (N % 2 == 1 and abs(ones - zeros) != 1)):
        return -1
 
    # Store no of min swaps when
    # string starts with "1"
    ans_1 = 0
 
    # Keep track of the odd positions
    j = 0
 
    # Checking for when the string
    # starts with "1"
    for i in range(N):
        if (s[i] == '1'):
            # Adding the no of swaps to
            # fix "1" at odd positions
            ans_1 += abs(j - i)
            j += 2
 
    # Store no of min swaps when string
    # starts with "0"
    ans_0 = 0
 
    # Keep track of the odd positions
    k = 0
 
    # Checking for when the string
    # starts with "0"
    for i in range(N):
        if(s[i] == '0'):
 
            # Adding the no of swaps to
            # fix "1" at odd positions
            ans_0 += abs(k - i)
            k += 2
 
    # Returning the answer based on
    # the conditions when string
    # length is even
    if (N % 2 == 0):
        return min(ans_1, ans_0)
 
    # When string length is odd
    else:
 
        # When no of ones is greater
        # than no of zeros
        if (ones > zeros):
            return ans_1
 
        # When no of ones is greater
        # than no of zeros
        else:
            return ans_0
 
# Driver Code
if __name__ == '__main__':
    S = "110100"
    print(minSwaps(S))
     
    # This code is contributed by ipg2016107.


C#




// C# program for the above approach
using System;
class GFG{
 
// Function to find the minimum number
// of adjacent swaps to make the String
// alternating
static int minSwaps(String s)
{
    // Count the no of zeros and ones
    int ones = 0, zeros = 0;
    int N = s.Length;
 
    for (int i = 0; i < N; i++) {
        if (s[i] == '1')
            ones++;
        else
            zeros++;
    }
 
    // Base Case
    if ((N % 2 == 0 && ones != zeros)
        || (N % 2 == 1
            && Math.Abs(ones - zeros) != 1)) {
        return -1;
    }
 
    // Store no of min swaps when
    // String starts with "1"
    int ans_1 = 0;
 
    // Keep track of the odd positions
    int j = 0;
 
    // Checking for when the String
    // starts with "1"
    for (int i = 0; i < N; i++) {
        if (s[i] == '1') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_1 += Math.Abs(j - i);
            j += 2;
        }
    }
 
    // Store no of min swaps when String
    // starts with "0"
    int ans_0 = 0;
 
    // Keep track of the odd positions
    int k = 0;
 
    // Checking for when the String
    // starts with "0"
    for (int i = 0; i < N; i++) {
        if (s[i] == '0') {
 
            // Adding the no of swaps to
            // fix "1" at odd positions
            ans_0 += Math.Abs(k - i);
            k += 2;
        }
    }
 
    // Returning the answer based on
    // the conditions when String
    // length is even
    if (N % 2 == 0)
        return Math.Min(ans_1, ans_0);
 
    // When String length is odd
    else {
 
        // When no of ones is greater
        // than no of zeros
        if (ones > zeros)
            return ans_1;
 
        // When no of ones is greater
        // than no of zeros
        else
            return ans_0;
    }
}
 
// Driver Code
public static void Main()
{
    String S = "110100";
    Console.WriteLine(minSwaps(S));
 
}
}
 
// This code is contributed by ihritik


Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
        // Function to find the minimum number
        // of adjacent swaps to make the string
        // alternating
        function minSwaps(s)
        {
         
            // Count the no of zeros and ones
            let ones = 0, zeros = 0;
            let N = s.length;
 
            for (let i = 0; i < N; i++) {
                if (s.charAt(i) == '1')
                    ones++;
                else
                    zeros++;
            }
 
            // Base Case
            if ((N % 2 == 0 && ones != zeros)
                || (N % 2 == 1
                    && Math.abs(ones - zeros) != 1)) {
                return -1;
            }
 
            // Store no of min swaps when
            // string starts with "1"
            let ans_1 = 0;
 
            // Keep track of the odd positions
            let j = 0;
 
            // Checking for when the string
            // starts with "1"
            for (let i = 0; i < N; i++) {
                if (s.charAt(i) == '1') {
 
                    // Adding the no of swaps to
                    // fix "1" at odd positions
                    ans_1 += Math.abs(j - i);
                    j += 2;
                }
            }
 
            // Store no of min swaps when string
            // starts with "0"
            let ans_0 = 0;
 
            // Keep track of the odd positions
            let k = 0;
 
            // Checking for when the string
            // starts with "0"
            for (let i = 0; i < N; i++) {
                if (s.charAt(i) == '0') {
 
                    // Adding the no of swaps to
                    // fix "1" at odd positions
                    ans_0 += Math.abs(k - i);
                    k += 2;
                }
            }
 
            // Returning the answer based on
            // the conditions when string
            // length is even
            if (N % 2 == 0)
                return Math.min(ans_1, ans_0);
 
            // When string length is odd
            else {
 
                // When no of ones is greater
                // than no of zeros
                if (ones > zeros)
                    return ans_1;
 
                // When no of ones is greater
                // than no of zeros
                else
                    return ans_0;
            }
        }
 
        // Driver Code
        let S = "110100";
        document.write(minSwaps(S));
 
     // This code is contributed by Potta Lokesh
 
    </script>


 
 

Output: 

2

 

 

Time Complexity: O(N)
Auxiliary Space: O(1)

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads