Minimum operations required to convert a binary string to all 0s or all 1s
Last Updated :
22 Dec, 2022
Given a binary string str, the task is to find the minimum number of operations required to make all the characters of the string same i.e. either the resultant string contains all 0s or all 1s. In a single operation, any block of consecutive 0s can be converted to a block of consecutive 1s of the same length and vice versa.
Examples:
Input: str = “000111”
Output: 1
In a single operation, either change all 0s to 1s
or change all 1s to 0s.
Input: str = “0011101010”
Output: 3
All the 1s can be converted to 0s in 3 operations.
Approach: The problem is to convert all the characters into a single one. Now since converting a whole consecutive group of characters counts as a single step. You can calculate the number of different groups as separated by each other due to the presence of other characters in between them. Now the number of steps would be simply the minimum of both numbers. Hence, the answer will be the minimum of the count of consecutive blocks of 0s or the count of consecutive blocks of 1s.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minOperations(string str, int n)
{
int count = 0;
for ( int i = 0; i < n - 1; i++) {
if (str[i] != str[i + 1])
count++;
}
return (count + 1) / 2;
}
int main()
{
string str = "000111" ;
int n = str.length();
cout << minOperations(str, n);
return 0;
}
|
Java
class GFG
{
static int minOperations(String str, int n)
{
int count = 0 ;
for ( int i = 0 ; i < n - 1 ; i++)
{
if (str.charAt(i) != str.charAt(i + 1 ))
count++;
}
return (count + 1 ) / 2 ;
}
public static void main(String[] args)
{
String str = "000111" ;
int n = str.length();
System.out.println(minOperations(str, n));
}
}
|
Python3
def minOperations( str , n):
count = 0
for i in range (n - 1 ):
if ( str [i] ! = str [i + 1 ]):
count + = 1
return (count + 1 ) / / 2
str = "000111"
n = len ( str )
print (minOperations( str , n))
|
C#
using System;
class GFG
{
static int minOperations( string str, int n)
{
int count = 0;
for ( int i = 0; i < n - 1; i++)
{
if (str[(i)] != str[(i + 1)])
count++;
}
return (count + 1) / 2;
}
public static void Main()
{
string str = "000111" ;
int n = str.Length;
Console.WriteLine(minOperations(str, n));
}
}
|
Javascript
<script>
function minOperations(str, n)
{
var count = 0;
for ( var i = 0; i < n - 1; i++) {
if (str[i] != str[i + 1])
count++;
}
return (count + 1) / 2;
}
var str = "000111" ;
var n = str.length;
document.write(minOperations(str, n));
</script>
|
Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...