Minimum adjacent swaps required to make a binary string alternating (original) (raw)

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 3and 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:

Below is theimplementation 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

`

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

Similar Reads