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:
- 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 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
- Minimum swaps required to make a binary string alternating You are given a binary string of even length (2N) and an equal number of 0's (N) and 1's (N). What is the minimum number of swaps to make the string alternating? A binary string is alternating if no two consecutive elements are equal. Examples: Input : 000111Output : 1Explanation : Swap index 2 and 11 min read
- Minimum adjacent swaps required to Sort Binary array Given a binary array, the task is to find the minimum number of swaps needed to sort this binary array. We are allowed to swap only adjacent elements.Examples: Input : arr[] = [0, 0, 1, 0, 1, 0, 1, 1]Output : 3Explanation:1st swap : [0, 0, 1, 0, 0, 1, 1, 1]2nd swap : [0, 0, 0, 1, 0, 1, 1, 1]3rd swap 5 min read
- Minimum substring reversals required to make given Binary String alternating Given a binary string S of length N, the task is to count the minimum number substrings of S that is required to be reversed to make the string S alternating. If it is not possible to make string alternating, then print "-1". Examples: Input: S = "10001110"Output: 2Explanation:In the first operation 7 min read
- Minimum swaps required to convert one binary string to another Given two binary string M and N of equal length, the task is to find a minimum number of operations (swaps) required to convert string N to M. Examples: Input: str1 = "1101", str2 = "1110" Output: 1 Swap last and second last element in the binary string, so that it become 1101 Input: str1 = "1110000 5 min read
- Minimum swaps required to make a binary string divisible by 2^k Given a binary string S of length N and an integer K, the task is to find the minimum number of adjacent swaps required to make the binary string divisible by 2K. If it is not possible then print -1. Examples: Input: S = "100111", K = 2 Output: 6 Swapping the right-most zero 3 times to the right, we 6 min read
- Minimum flips or swapping of adjacent characters required to make a string equal to another Given two binary strings A and B of length N, the task is to convert the string A to B by either flipping any character of A or swapping adjacent characters of A minimum number of times. If it is not possible to make both the strings equal, print -1. Examples: Input: A = "10010010", B = "00001000" O 6 min read
- Minimum number of flipping adjacent bits required to make given Binary Strings equal Given two binary strings s1[] and s2[] of the same length N, the task is to find the minimum number of operations to make them equal. Print -1 if it is impossible to do so. One operation is defined as choosing two adjacent indices of one of the binary string and inverting the characters at those pos 7 min read
- Minimum number of flips or swaps of adjacent characters required to make two strings equal Given two binary strings A and B of length N, the task is to count the minimum number of operations required to make the two given strings equal by either swapping adjacent characters or flipping any character of the string A. Examples: Input: A = "100", B = "001"Output: 2Explanation: Flipping chara 12 min read
- Minimum non-adjacent pair flips required to remove all 0s from a Binary String The problem statement asks us to find the minimum number of operations required to remove all 0s from a given binary string S. An operation involves flipping at most two non-adjacent characters (i.e., characters that are not next to each other) in the string. Let's take the first example given: S = 11 min read
- Minimum subarray reversals required to make given binary array alternating Given a binary array arr[] consisting of equal count of 0s and 1s, the task is to count the minimum number of subarray reversal operations required to make the binary array alternating. In each operation reverse any subarray of the given array. Examples: Input: arr[] = { 1, 1, 1, 0, 1, 0, 0, 0 } Out 5 min read