Friday, July 5, 2024
HomeData ModellingData Structure & AlgorithmMinimum flips required to keep all 1s together in a Binary string

Minimum flips required to keep all 1s together in a Binary string

Given binary string str, the task is to find the minimum number of flips required to keep all 1s together in the given binary string, i.e. there must not be any 0 between 1s in the string.

Examples:  

Input: str = “0011111100” 
Output:
Explanation: We dont need to flip any bits because all the ones are grouped together and there is no zero between any two ones.

Input: str = “11100111000101” 
Output:
Explanation: We can flip the 4th and 5th bit to make them 1 and flip 12th and 14th bit to make them 0. So the resulting string is “11111111000000” with 4 possible flips. 
 

Approach: To solve the problem mentioned above we will implement the dynamic programming approach where we will have the following states:  

  • The first state is dp[i][0] which signifies the number of flips required to make all zeroes up to the ith bit.
  • Second state dp[i][1] which signifies the number of flips required to make the current bit 1 such that the conditions given in the question are satisfied.

So the required answer will be minimum flips for making the current bit 1 + minimum flips for making all bits after the current bit 0 for all values of i. But if all the bits in the given string are 0 then we don’t have to change anything, so we can check the minimum between our answer and the number of flips required to make the string with all zeroes. So we can compute the answer by iterating over all the characters in the string where, 

answer = min ( answer, dp[i][1] + dp[n-1][0] – dp[i][0])
where
dp[i][1] = Minimum number of flips to set current bit to 1
dp[n-1][0] – dp[i][0] = Minimum number of flips required to make all bits after i as 0

Below is the implementation of the above approach: 

C++




//cpp implementation for Minimum number of
//flips required in a binary string such
//that all the 1’s are together
#include <bits/stdc++.h>
using namespace std;
int minFlip(string a)
{
     //Length of the binary string
    int n = a.size();
 
    vector<vector<int>> dp(n + 1,vector<int>(2, 0));
 
    //Initial state of the dp
    //dp[0][0] will be 1 if the current
    //bit is 1 and we have to flip it
    dp[0][0] = (a[0] == '1');
 
    //Initial state of the dp
    //dp[0][1] will be 1 if the current
    //bit is 0 and we have to flip it
    dp[0][1] = (a[0] == '0');
 
 
    for (int i = 1; i < n; i++)
    {
        //dp[i][0] = Flips required to
        //make all previous bits zero
        //+ Flip required to make current bit zero
        dp[i][0] = dp[i - 1][0] + (a[i] == '1');
 
 
        //dp[i][1] = minimum flips required
        //to make all previous states 0 or make
        //previous states 1 satisfying the condition
        dp[i][1] = min(dp[i - 1][0],
                       dp[i - 1][1]) + (a[i] == '0');
 
    }
    int answer = INT_MAX;
    for (int i=0;i<n;i++)
    {
        answer = min(answer, dp[i][1] +
                             dp[n - 1][0] - dp[i][0]);
     }
 
    //Minimum of answer and flips
    //required to make all bits 0
    return min(answer, dp[n - 1][0]);
}
 
//Driver Code
int main()
{
  string s = "1100111000101";
  cout<<(minFlip(s));
}
 
// This code is contributed by Mohit kumar 29


Java




// Java implementation for
// Minimum number of flips
// required in a binary string
// such that all the 1’s are together
import java.io.*;
import java.util.*;
class GFG{
     
static int minFlip(String a)
{
  // Length of the binary string
  int n = a.length();
 
  int dp[][] = new int[n + 1][2];
 
  // Initial state of the dp
  // dp[0][0] will be 1 if
  // the current bit is 1
  // and we have to flip it
  if(a.charAt(0) == '1')
  {
    dp[0][0] = 1 ;
  }
  else dp[0][0] = 0;
 
  // Initial state of the dp
  // dp[0][1] will be 1 if
  // the current bit is 0
  // and we have to flip it
  if(a.charAt(0) == '0')
    dp[0][1] = 1;
  else dp[0][1] = 0;
 
  for (int i = 1; i < n; i++)
  {
    // dp[i][0] = Flips required to
    // make all previous bits zero
    // Flip required to make current
    // bit zero
    if(a.charAt(i) == '1')
    {
      dp[i][0] = dp[i - 1][0] + 1;
    }
    else dp[i][0] = dp[i - 1][0];
 
    // dp[i][1] = minimum flips
    // required to make all previous
    // states 0 or make previous states
    // 1 satisfying the condition
    if(a.charAt(i) == '0')
    {
      dp[i][1] = Math.min(dp[i - 1][0],
                          dp[i - 1][1]) + 1;
    }
    else dp[i][1] = Math.min(dp[i - 1][0],
                             dp[i - 1][1]);
  }
 
  int answer = Integer.MAX_VALUE;
  for (int i = 0; i < n; i++)
  {
    answer = Math.min(answer, dp[i][1] +
                      dp[n - 1][0] -
                      dp[i][0]);
  }
 
  //Minimum of answer and flips
  //required to make all bits 0
  return Math.min(answer,
                  dp[n - 1][0]);
}
   
// Driver code
public static void main (String[] args)
{
  String s = "1100111000101";
  System.out.println(minFlip(s));
}
}
 
// This code is contributed by satvikshrivas26


Python3




# Python implementation for Minimum number of
# flips required in a binary string such
# that all the 1’s are together
 
def minFlip(a):
     
     # Length of the binary string
    n = len(a)
     
    dp =[[0, 0] for i in range(n)]
     
    # Initial state of the dp
    # dp[0][0] will be 1 if the current
    # bit is 1 and we have to flip it
    dp[0][0]= int(a[0]=='1')
     
    # Initial state of the dp
    # dp[0][1] will be 1 if the current
    # bit is 0 and we have to flip it
    dp[0][1]= int(a[0]=='0')
     
 
    for i in range(1, n):
         
         
        # dp[i][0] = Flips required to
        # make all previous bits zero
        # + Flip required to make current bit zero
        dp[i][0]= dp[i-1][0]+int(a[i]=='1')
         
         
        # dp[i][1] = minimum flips required
        # to make all previous states 0 or make
        # previous states 1 satisfying the condition
        dp[i][1]= min(dp[i-1])+int(a[i]=='0')
         
     
 
    answer = 10**18
     
    for i in range(n):
        answer = min(answer,
                     dp[i][1]+dp[n-1][0]-dp[i][0])
     
    # Minimum of answer and flips
    # required to make all bits 0
    return min(answer, dp[n-1][0])
     
 
# Driver code
s = "1100111000101"
 
print(minFlip(s))


C#




// C# implementation for
// Minimum number of
// flips required in
// a binary string such
// that all the 1’s are together
using System;
class GFG{
  
static int minFlip(string a)
{
  //Length of the binary string
  int n = a.Length;
 
  int [,]dp=new int[n + 1, 2];
 
  //Initial state of the dp
  //dp[0][0] will be 1 if the current
  //bit is 1 and we have to flip it
  dp[0, 0] = (a[0] == '1' ? 1 : 0);
 
  //Initial state of the dp
  //dp[0][1] will be 1 if the current
  //bit is 0 and we have to flip it
  dp[0, 1] = (a[0] == '0' ? 1 : 0);
 
  for (int i = 1; i < n; i++)
  {
    //dp[i][0] = Flips required to
    //make all previous bits zero
    //+ Flip required to make current bit zero
    dp[i, 0] = dp[i - 1, 0] +
                 (a[i] == '1' ? 1 : 0);
 
    //dp[i][1] = minimum flips required
    //to make all previous states 0 or make
    //previous states 1 satisfying the condition
    dp[i, 1] = Math.Min(dp[i - 1, 0],
                        dp[i - 1, 1]) +
                       (a[i] == '0' ? 1 : 0);
 
  }
  int answer = int.MaxValue;
   
  for (int i = 0; i < n; i++)
  {
    answer = Math.Min(answer, dp[i, 1] +
                      dp[n - 1, 0] - dp[i, 0]);
  }
 
  //Minimum of answer and flips
  //required to make all bits 0
  return Math.Min(answer, dp[n - 1, 0]);
}
  
// Driver code
public static void Main(string[] args)
{
  string s = "1100111000101";
  Console.Write(minFlip(s));
}
}
 
// This code is contributed by Rutvik_56


Javascript




<script>
// Javascript implementation for
// Minimum number of flips
// required in a binary string
// such that all the 1’s are together
function minFlip(a)
{
 
    // Length of the binary string
    let n = a.length;
    let dp = new Array(n + 2).fill(0).map((t) => new Array(2).fill(0))
 
    // Initial state of the dp
    // dp[0][0] will be 1 if
    // the current bit is 1
    // and we have to flip it
    if (a.charAt(0) == '1') {
        dp[0][0] = 1;
    }
    else dp[0][0] = 0;
 
    // Initial state of the dp
    // dp[0][1] will be 1 if
    // the current bit is 0
    // and we have to flip it
    if (a.charAt(0) == '0')
        dp[0][1] = 1;
    else dp[0][1] = 0;
 
    for (let i = 1; i < n; i++)
    {
     
        // dp[i][0] = Flips required to
        // make all previous bits zero
        // Flip required to make current
        // bit zero
        if (a.charAt(i) == '1') {
            dp[i][0] = dp[i - 1][0] + 1;
        }
        else dp[i][0] = dp[i - 1][0];
 
        // dp[i][1] = minimum flips
        // required to make all previous
        // states 0 or make previous states
        // 1 satisfying the condition
        if (a.charAt(i) == '0') {
            dp[i][1] = Math.min(dp[i - 1][0],
                dp[i - 1][1]) + 1;
        }
        else dp[i][1] = Math.min(dp[i - 1][0],
            dp[i - 1][1]);
    }
 
    let answer = Number.MAX_SAFE_INTEGER;
    for (let i = 0; i < n; i++) {
        answer = Math.min(answer, dp[i][1] +
            dp[n - 1][0] -
            dp[i][0]);
    }
 
    // Minimum of answer and flips
    // required to make all bits 0
    return Math.min(answer,
        dp[n - 1][0]);
}
 
// Driver code
let s = "1100111000101";
document.write(minFlip(s));
 
// This code is contributed by _saurabh_jaiswal.
</script>


Output: 

4

 

Time Complexity: O(N)

Auxiliary Space: O(N), where N is the length of the string. 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Thapelo Manthata
I’m a desktop support specialist transitioning into a SharePoint developer role by day and Software Engineering student by night. My superpowers include customer service, coding, the Microsoft office 365 suite including SharePoint and power platform.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments