Minimum number of flips with rotation to make binary string alternating

Given a binary string S of 0s and 1s. The task is to make the given string a sequence of alternate characters by using the below operations:

  • Remove some prefix from the start and append it to the end.
  • Flip some or every bit in the given string.

Print the minimum number of bits to be flipped to make the given string alternating.

Examples:

Input: S = “001”
Output: 0
Explanation:
No need to flip any element we can get alternating sequence by using left rotation: 010.

Input: S = “000001100”
Output: 3
Explanation:
Following steps to find minimum flips to get alternating string:
1. After rotating string 6 times towards left we will get: 100000001 
2. Now we can apply flip operation as following: 101000001 -> 101010001 -> 101010101
Thus, minimum flips to make string alternating is 3.



Naive Approach: The naive approach is to take all N possible combinations and calculate the minimum number of bits To flip in each of those strings. Print the minimum count among all such combinations.
Time Complexity: O(N2), where N is the length of the string.
Auxiliary Space: O(N)

Efficient Approach: This can be solved by observing that the final string will be either of type “101010…” or “010101…” such that all 1s will either be at odd positions or at even positions. Follow the below steps to solve the problem:

  1. Create a prefix sum array where pref[i] means a number of changes required until index i.
  2. Create prefix arrays for both the above patterns.
  3. Check for every i, if substring[0, i] is appended at the end how many characters to be flipped required.
  4. Print the minimum number of flips among all the substrings in the above steps.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that finds the minimum
// number of flips to make the
// binary string alternating if
// left circular rotation is allowed
int MinimumFlips(string s, int n)
{
    int a[n];
 
    for(int i = 0; i < n; i++)
    {
        a[i] = (s[i] == '1' ? 1 : 0);
    }
 
    // Initialize prefix arrays to store
    // number of changes required to put
    // 1s at either even or odd position
    int oddone[n + 1];
    int evenone[n + 1];
 
    oddone[0] = 0;
    evenone[0] = 0;
 
    for(int i = 0; i < n; i++)
    {
         
        // If i is odd
        if (i % 2 != 0)
        {
             
            // Update the oddone
            // and evenone count
            oddone[i + 1] = oddone[i] +
                                (a[i] == 1 ? 1 : 0);
            evenone[i + 1] = evenone[i] +
                                  (a[i] == 0 ? 1 : 0);
        }
 
        // Else i is even
        else
        {
             
            // Update the oddone
            // and evenone count
            oddone[i + 1] = oddone[i] +
                                (a[i] == 0 ? 1 : 0);
            evenone[i + 1] = evenone[i] +
                                  (a[i] == 1 ? 1 : 0);
        }
    }
 
    // Initialize minimum flips
    int minimum = min(oddone[n], evenone[n]);
 
    // Check if substring[0, i] is
    // appended at end how many
    // changes will be required
    for(int i = 0; i < n; i++)
    {
        if (n % 2 != 0)
        {
            minimum = min(minimum,
                          oddone[n] -
                          oddone[i + 1] +
                         evenone[i + 1]);
            minimum = min(minimum,
                          evenone[n] -
                          evenone[i + 1] +
                           oddone[i + 1]);
        }
    }
 
    // Return minimum flips
    return minimum;
}
 
// Driver Code
int main()
{
     
    // Given String
    string S = "000001100";
 
    // Length of given string
    int n = S.length();
 
    // Function call
    cout << (MinimumFlips(S, n));
}
 
// This code is contributed by chitranayal

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function that finds the minimum
    // number of flips to make the
    // binary string alternating if
    // left circular rotation is allowed
    static int MinimumFlips(String s, int n)
    {
        int[] a = new int[n];
 
        for (int i = 0; i < n; i++) {
            a[i] = (s.charAt(i) == '1' ? 1 : 0);
        }
 
        // Initialize prefix arrays to store
        // number of changes required to put
        // 1s at either even or odd position
        int[] oddone = new int[n + 1];
        int[] evenone = new int[n + 1];
 
        oddone[0] = 0;
        evenone[0] = 0;
 
        for (int i = 0; i < n; i++) {
 
            // If i is odd
            if (i % 2 != 0) {
 
                // Update the oddone
                // and evenone count
                oddone[i + 1]
                    = oddone[i]
                      + (a[i] == 1 ? 1 : 0);
                evenone[i + 1]
                    = evenone[i]
                      + (a[i] == 0 ? 1 : 0);
            }
 
            // Else i is even
            else {
 
                // Update the oddone
                // and evenone count
                oddone[i + 1]
                    = oddone[i]
                      + (a[i] == 0 ? 1 : 0);
                evenone[i + 1]
                    = evenone[i]
                      + (a[i] == 1 ? 1 : 0);
            }
        }
 
        // Initialize minimum flips
        int minimum = Math.min(oddone[n],
                               evenone[n]);
 
        // Check if substring[0, i] is
        // appended at end how many
        // changes will be required
        for (int i = 0; i < n; i++) {
            if (n % 2 != 0) {
                minimum = Math.min(minimum,
                                   oddone[n]
                                       - oddone[i + 1]
                                       + evenone[i + 1]);
                minimum = Math.min(minimum,
                                   evenone[n]
                                       - evenone[i + 1]
                                       + oddone[i + 1]);
            }
        }
 
        // Return minimum flips
        return minimum;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given String
        String S = "000001100";
 
        // Length of given string
        int n = S.length();
 
        // Function call
        System.out.print(MinimumFlips(S, n));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function that finds the minimum
# number of flips to make the
# binary string alternating if
# left circular rotation is allowed
def MinimumFlips(s, n):
 
    a = [0] * n
 
    for i in range(n):
        a[i] = 1 if s[i] == '1' else 0
 
    # Initialize prefix arrays to store
    # number of changes required to put
    # 1s at either even or odd position
    oddone = [0] * (n + 1)
    evenone = [0] * (n + 1)
 
    for i in range(n):
 
        # If i is odd
        if(i % 2 != 0):
 
            # Update the oddone
            # and evenone count
            if(a[i] == 1):
                oddone[i + 1] = oddone[i] + 1
            else:
                oddone[i + 1] = oddone[i] + 0
 
            if(a[i] == 0):
                evenone[i + 1] = evenone[i] + 1
            else:
                evenone[i + 1] = evenone[i] + 0
 
        # Else i is even
        else:
 
            # Update the oddone
            # and evenone count
            if (a[i] == 0):
                oddone[i + 1] = oddone[i] + 1
            else:
                oddone[i + 1] = oddone[i] + 0
 
            if (a[i] == 1):
                evenone[i + 1] = evenone[i] + 1
            else:
                evenone[i + 1] = evenone[i] + 0
 
    # Initialize minimum flips
    minimum = min(oddone[n], evenone[n])
 
    # Check if substring[0, i] is
    # appended at end how many
    # changes will be required
    for i in range(n):
        if(n % 2 != 0):
            minimum = min(minimum,
                          oddone[n] -
                          oddone[i + 1] +
                         evenone[i + 1])
 
            minimum = min(minimum,
                          evenone[n] -
                          evenone[i + 1] +
                           oddone[i + 1])
 
    # Return minimum flips
    return minimum
 
# Driver Code
 
# Given String
S = "000001100"
 
# Length of given string
n = len(S)
 
# Function call
print(MinimumFlips(S, n))
 
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
class GFG{
 
  // Function that finds the minimum
  // number of flips to make the
  // binary string alternating if
  // left circular rotation is allowed
  static int MinimumFlips(String s, int n)
  {
    int[] a = new int[n];
 
    for (int i = 0; i < n; i++)
    {
      a[i] = (s[i] == '1' ? 1 : 0);
    }
 
    // Initialize prefix arrays to store
    // number of changes required to put
    // 1s at either even or odd position
    int[] oddone = new int[n + 1];
    int[] evenone = new int[n + 1];
 
    oddone[0] = 0;
    evenone[0] = 0;
 
    for (int i = 0; i < n; i++)
    {
 
      // If i is odd
      if (i % 2 != 0)
      {
 
        // Update the oddone
        // and evenone count
        oddone[i + 1] = oddone[i] +
                         (a[i] == 1 ? 1 : 0);
        evenone[i + 1] = evenone[i] +
                          (a[i] == 0 ? 1 : 0);
      }
 
      // Else i is even
      else
      {
 
        // Update the oddone
        // and evenone count
        oddone[i + 1] = oddone[i] +
                         (a[i] == 0 ? 1 : 0);
        evenone[i + 1] = evenone[i] +
                          (a[i] == 1 ? 1 : 0);
      }
    }
 
    // Initialize minimum flips
    int minimum = Math.Min(oddone[n],
                           evenone[n]);
 
    // Check if substring[0, i] is
    // appended at end how many
    // changes will be required
    for (int i = 0; i < n; i++)
    {
      if (n % 2 != 0)
      {
        minimum = Math.Min(minimum, oddone[n] -
                                       oddone[i + 1] +
                                    evenone[i + 1]);
        minimum = Math.Min(minimum, evenone[n] -
                                       evenone[i + 1] +
                                       oddone[i + 1]);
      }
    }
 
    // Return minimum flips
    return minimum;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    // Given String
    String S = "000001100";
 
    // Length of given string
    int n = S.Length;
 
    // Function call
    Console.Write(MinimumFlips(S, n));
  }
}
 
// This code is contributed by Rajput-Ji

chevron_right


Output: 

3


 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.