Minimum adjacent swaps required to make a binary string alternating

• Last Updated : 08 Oct, 2021

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 using namespace std; // Function to find the minimum number// of adjacent swaps to make the string// alternatingint 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 Codeint 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// alternatingstatic 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 Codepublic 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# alternatingdef 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 Codeif __name__ == '__main__':    S = "110100"    print(minSwaps(S))         # This code is contributed by ipg2016107.

C#

 // C# program for the above approachusing System;class GFG{ // Function to find the minimum number// of adjacent swaps to make the String// alternatingstatic 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 Codepublic static void Main(){    String S = "110100";    Console.WriteLine(minSwaps(S)); }} // This code is contributed by ihritik

Javascript



Output:
2

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

My Personal Notes arrow_drop_up