Open In App

Minimum flips required to generate continuous substrings of 0’s and 1’s

Last Updated : 26 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary string S of length N, the task is to find the minimum number of bit flips required to convert the given string such that it contains only continuous substrings of 0’s and 1’s such that the final string is in the form of 000..000, 111..111, 111…000 or 000…111.

Examples: 

Input: S = 000100101, N = 9 
Output:
Explanation: 
000100101 -> 000000001

Input: S = 01100, N = 5 
Output:
Explanation: 
01100 -> 11100

Approach: 
The minimum number of flips can be calculated efficiently in two linear traversals. 
In the first traversal, we will calculate what can be the minimum number of flips required in the worst case, as it can be equal to the number of total 0’s initially
In the second traversal, at every step, the total number of flips required will be the sum of total 1’s before that point and the total 0’s after that point. We will take a minimum of all values calculated at every step. 

Hence, to solve the problem, follow the steps below: 

  • Initialize variables count0 = 0, count1 = 0 and res = 0. where, count0 stores count of 0 and count1 stores count of 1 and res stores the bit flips required.
  • Traverse the input string, calculate 0’s and store it in res variable.
  • Traverse the input string and subtract the count of 0 if character 0 is found and store the count of character 1 in variable count1 and update the res as min(res, count0+count1).

Below is the implementation of the above approach.

C++




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
int minChanges(string str, int N)
{
    int res;
    int count0 = 0, count1 = 0;
 
    // Traverse input string
    // and store the count of 0
    for (char x : str) {
        count0 += (x == '0');
    }
    res = count0;
 
    // Traverse the input string again
    // to find minimum number of flips
    for (char x : str) {
        count0 -= (x == '0');
        count1 += (x == '1');
        res = min(res, count1 + count0);
    }
 
    return res;
}
 
// Driver code
int main()
{
    int N = 9;
    string str = "000101001";
 
    cout << minChanges(str, N);
    return 0;
}


Java




// Java implementation of the above approach
import java.io.*;
 
class GFG{
 
static int minChanges(String str, int N)
{
    int res;
    int count0 = 0, count1 = 0;
 
    // Traverse input string
    // and store the count of 0
    for(char x : str.toCharArray())
    {
       if (x == '0')
           count0++;
    }
    res = count0;
 
    // Traverse the input string again
    // to find minimum number of flips
    for(char x : str.toCharArray())
    {
       if (x == '0')
           count0--;
       if (x == '1')
           count1++;
            
       res = Math.min(res, count1 + count0);
    }
    return res;
}
 
// Driver code
public static void main(String[] args)
{
    int N = 9;
    String str = "000101001";
 
    System.out.println(minChanges(str, N));
}
}
 
// This code is contributed by offbeat


Python3




# Python3 implementation of the above approach
def minChanges(str, N):
     
    count0 = 0
    count1 = 0
     
    # Traverse input string
    # and store the count of 0
    for x in str:
        count0 += (x == '0')
 
    res = count0
             
    # Traverse the input string again
    # to find minimum number of flips
    for x in str:
        count0 -= (x == '0')
        count1 += (x == '1')
        res = min(res, count1 + count0)
         
    return res
 
 
# Driver code
N = 9
str = "000101001"
 
print(minChanges(str, N))
 
# This code is contributed by shubhamsingh10


C#




// C# implementation of the above approach
using System;
 
class GFG{
 
static int minChanges(String str, int N)
{
    int res;
    int count0 = 0, count1 = 0;
 
    // Traverse input string
    // and store the count of 0
    for(int i = 0; i < str.Length; i++)
    {
        if (str[i] == '0')
            count0++;
    }
    res = count0;
 
    // Traverse the input string again
    // to find minimum number of flips
    for(int i = 0; i< str.Length; i++)
    {
        if (str[i] == '0')
            count0--;
        if (str[i] == '1')
            count1++;
                 
        res = Math.Min(res, count1 + count0);
    }
    return res;
}
 
// Driver code
public static void Main()
{
    int N = 9;
    String str = "000101001";
 
    Console.Write(minChanges(str, N));
}
}
 
// This code is contributed by chitranayal


Javascript




<script>
 
// Javascript implementation of the above approach
 
function minChanges(str, N)
{
    var res;
    var count0 = 0, count1 = 0;
 
    // Traverse input string
    // and store the count of 0
    str.split('').forEach(x => {
         
        count0 += (x == '0');
    });
    res = count0;
 
    // Traverse the input string again
    // to find minimum number of flips
    str.split('').forEach(x => {
         
        count0 -= (x == '0');
        count1 += (x == '1');
        res = Math.min(res, count1 + count0);
    });
 
    return res;
}
 
// Driver code
var N = 9;
var str = "000101001";
document.write( minChanges(str, N));
 
</script>


Output: 

2

 

Time complexity: O(k), where, k is the length of the binary string. 
Space complexity: O(1)
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads