Segregate 1s and 0s in separate halves of a Binary String
Last Updated :
25 Jun, 2021
Given a binary string str of even length, consisting of equal number of 0s and 1s, the task is to segregate all 1s and 0s into separate halves by repeatedly reversing a substring. Print the minimum count of reversals required.
Examples:
Input: str = “01011100”
Output: 2
Explanation: The operations performed are as follows:
- “01011100″ -> “11101000”
- “11101000″ -> “11110000”
Input: str = “101010”
Output: 2
Explanation: The operations performed are as follows:
- “101010″ -> “110100”
- “110100″ -> “111000”
Approach: The idea is to count the number of instances in which any two consecutive characters of the string are unequal. Follow the steps below to solve the problem:
- Initialize a variable, say ans, to count the number of adjacent unequal pair of characters.
- Now, after reversing any substring, the count reduces by 2.
- If the value of ans is odd, then the required answer will be (ans – 1)/2, as the final string will contain one such pair at the center of the string.
- Otherwise, the required answer is ans/2.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
void minOps(string s, int N)
{
int ans = 0;
for ( int i = 1; i < N; i++)
{
if (s[i] != s[i - 1])
{
ans++;
}
}
if (ans % 2 == 1)
{
cout << (ans - 1) / 2 << endl;
return ;
}
cout<<(ans / 2);
}
int main()
{
string str = "01011100" ;
int N = str.size();
minOps(str, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void minOps(String s, int N)
{
int ans = 0 ;
for ( int i = 1 ; i < N; i++) {
if (s.charAt(i) != s.charAt(i - 1 )) {
ans++;
}
}
if (ans % 2 == 1 ) {
System.out.print((ans - 1 ) / 2 );
return ;
}
System.out.print(ans / 2 );
}
public static void main(String[] args)
{
String str = "01011100" ;
int N = str.length();
minOps(str, N);
}
}
|
Python3
def minOps(s, N) :
ans = 0
for i in range ( 1 , N):
if (s[i] ! = s[i - 1 ]) :
ans + = 1
if (ans % 2 = = 1 ) :
print ((ans - 1 ) / / 2 )
return
print (ans / / 2 )
str = "01011100"
N = len ( str )
minOps( str , N)
|
C#
using System;
public class GFG
{
static void minOps(String s, int N)
{
int ans = 0;
for ( int i = 1; i < N; i++)
{
if (s[i] != s[i - 1])
{
ans++;
}
}
if (ans % 2 == 1)
{
Console.Write((ans - 1) / 2);
return ;
}
Console.Write(ans / 2);
}
public static void Main(String[] args)
{
String str = "01011100" ;
int N = str.Length;
minOps(str, N);
}
}
|
Javascript
<script>
function minOps( s , N)
{
var ans = 0;
for (i = 1; i < N; i++) {
if (s.charAt(i) != s.charAt(i - 1)) {
ans++;
}
}
if (ans % 2 == 1) {
document.write((ans - 1) / 2);
return ;
}
document.write(ans / 2);
}
var str = "01011100" ;
var N = str.length;
minOps(str, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...