Open In App

Minimize flips to make substrings of size K same and alternative

Last Updated : 06 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary string S of length N, the task is to minimize the count of operations required to find a binary string T of the same length N such that:

  • In one operation, it is allowed to flip any bit, i.e. convert 0 to 1 or vice versa.
  • In the binary string T, choose a number K, such that: 
    • N is perfectly divisible by K, and
    • The first K bits in T are 0, the next K are 1, the next K are 0, and so on.

Examples: 

Input: S = 1011011
Output: 4
Explanation: 
If we choose K = 1, then required string S=0101010, Moves required 4
If we choose K = 7, then required string S=0000000, Moves required 5
Values of K= 2, 3, 4, 5, 6 is not allowed because, it is not perfectly divide N = 7.
Choose K = 1. So, Final String is 0101010, Flip the first, second, third and seventh bit. Print 4 because string S satisfies all conditions after performing 4 moves.

Input: S = 000001
Output: 1
Explanation: 
If we choose K=1, then required string S=010101, Moves required 2
If we choose K=2, then required string S=001100, Moves required 3
If we choose K=3, then required string S=000111, Moves required 2
If we choose K=6, then required string S=000000, Moves required 1
So, Select K=6, So, output will be1.

 

Approach: The approach is based on the following observation:

It is mentioned in the problem statement itself that we have to choose K such that N is divisible by K, so we can break our problem into subproblem to find all the divisors of N and then find number of operations required for each of the divisor and choose the minimum number of operation between all of them.

Based on the above observation, follow the steps below to implement this approach:

  • Find all the divisor of N (size of given string).
  • For each divisor, Traverse the String and for each iteration: 
    • Count the number of changes required in given string if we choose the K = current divisor.
    • If current changes required is less than the previous result then update it with the current result. 
  • Return the minimum changes required.

Below is the implementation of the above approach:

C++




// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find all divisors
// of given string length n.
void findAllDivisors(int n, vector<int>& v)
{
    for (int i = 1; i <= sqrt(n); i++) {
 
        // Check whether the given number
        // is divisible by current number or not
        if (n % i == 0) {
 
            // Check if divisors are equal
            if (n / i == i)
                v.push_back(i);
            else {
                v.push_back(n / i);
            }
        }
    }
}
 
// Function to find the minimum
// number of operation require to make
// given substring alternative of size K
int findMinOperations(string& S)
{
    int n = S.length(), result = n;
 
    // Find and store all divisors of n.
    vector<int> v;
    findAllDivisors(n, v);
 
    // For each divisor,
    // calculate minimum changes required.
    for (int i = 0; i < v.size(); i++) {
 
        // Count of operations required
        int count = 0;
 
        bool flag = false;
        for (int j = 0; j < n; j += v[i]) {
            for (int k = j; k < j + v[i] && k < n; k++) {
                if (flag && S[k] == '0')
                    count++;
                if (!flag && S[k] == '1')
                    count++;
            }
 
            flag = (flag == false);
        }
 
        // If current changes required
        // is less than previous result
        // then update result
        if (count < result)
            result = count;
    }
    return result;
}
 
// Driver code
int main()
{
    string S = "101101";
    cout << findMinOperations(S);
    return 0;
}


Java




// Java code to implement above approach
 
import java.util.*;
 
class GFG {
 
    // Function to find all divisors
    // of given string length n.
    static void findAllDivisors(int n, Vector<Integer> v)
    {
        for (int i = 1; i <= Math.sqrt(n); i++) {
 
            // Check whether the given number
            // is divisible by current number or not
            if (n % i == 0) {
 
                // Check if divisors are equal
                if (n / i == i)
                    v.add(i);
                else {
                    v.add(n / i);
                }
            }
        }
    }
 
    // Function to find the minimum
    // number of operation require to make
    // given substring alternative of size K
    static int findMinOperations(String S)
    {
        int n = S.length();
        int result = n;
 
        // Find and store all divisors of n.
        Vector<Integer> v = new Vector<Integer>();
        findAllDivisors(n, v);
 
        // For each divisor,
        // calculate minimum changes required.
        for (int i = 0; i < v.size(); i++) {
 
            // Count of operations required
            int count = 0;
 
            boolean flag = false;
            for (int j = 0; j < n; j += v.get(i)) {
                for (int k = j; k < j + v.get(i) && k < n;
                     k++) {
                    if (flag && S.charAt(k) == '0')
                        count++;
                    if (!flag && S.charAt(k) == '1')
                        count++;
                }
 
                flag = (flag == false);
            }
 
            // If current changes required
            // is less than previous result
            // then update result
            if (count < result)
                result = count;
        }
        return result;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String S = "101101";
        System.out.print(findMinOperations(S));
    }
}
 
// This code is contributed by hrithikgarg03188.


Python3




# Python3 program to implement the above approach
 
# function to find all divisors of
# given string length n
 
 
def findAllDivisors(n, v):
    for i in range(1, 1 + int(n ** 0.5)):
        # check whether the given number
        # is divisible by the current number or not
        if n % i == 0:
            # check if divisors are equal
            if (n // i) == i:
                v.append(i)
            else:
                v.append(n // i)
    return v
 
# function to find the minimum
# number of opertations required to make
# given substring alternative of size K
 
 
def findMinOperations(S):
    n = len(S)
    result = n
    # find and store all divisors of n
    v = []
    v = findAllDivisors(n, v)
    for i in range(len(v)):
        # count of operations required
        count = 0
        flag = False
        for j in range(0, n, v[i]):
            for k in range(j, min(j + v[i], n), 1):
                if (flag and S[k]) == "0":
                    count += 1
                if (not flag and S[k]) == "1":
                    count += 1
            flag = bool(flag == False)
        # if current changes required
        # is less than the previous result,
        # then, update the result
        if count < result:
            result = count
 
    return result
 
 
# Driver Code
S = "101101"
print(findMinOperations(S))
 
# this code was contributed by phasing17


C#




// C# code to implement above approach
using System;
using System.Collections;
 
public class GFG{
 
  // Function to find all divisors
  // of given string length n.
  static void findAllDivisors(int n, ArrayList v)
  {
    for (int i = 1; i <= Math.Sqrt(n); i++) {
 
      // Check whether the given number
      // is divisible by current number or not
      if (n % i == 0) {
 
        // Check if divisors are equal
        if (n / i == i)
          v.Add(i);
        else {
          v.Add(n / i);
        }
      }
    }
  }
 
  // Function to find the minimum
  // number of operation require to make
  // given substring alternative of size K
  static int findMinOperations(String S)
  {
    int n = S.Length;
    int result = n;
 
    // Find and store all divisors of n.
    ArrayList  v = new ArrayList();
    findAllDivisors(n, v);
 
    // For each divisor,
    // calculate minimum changes required.
    for (int i = 0; i < v.Count; i++) {
 
      // Count of operations required
      int count = 0;
 
      bool flag = false;
      for (int j = 0; j < n; j += (int)v[i]) {
        for (int k = j; k < j + (int)v[i] && k < n;
             k++) {
          if (flag && S[k] == '0')
            count++;
          if (!flag && S[k] == '1')
            count++;
        }
 
        flag = (flag == false);
      }
 
      // If current changes required
      // is less than previous result
      // then update result
      if (count < result)
        result = count;
    }
    return result;
  }
 
  // Driver code
  static public void Main (){
 
    string S = "101101";
    Console.Write(findMinOperations(S));
  }
}
 
// This code is contributed by hrithikgarg03188.


Javascript




// JavaScript code to implement above approach
 
// Function to find all divisors
// of given string length n.
function findAllDivisors(n, v)
{
    for (var i = 1; i <= Math.floor(Math.sqrt(n)); i++) {
 
        // Check whether the given number
        // is divisible by current number or not
        if (n % i == 0) {
 
            // Check if divisors are equal
            if (Math.floor(n / i) == i)
                v.push(i);
            else {
                v.push(Math.floor(n / i));
            }
        }
    }
    return v;
}
 
// Function to find the minimum
// number of operation require to make
// given substring alternative of size K
function findMinOperations(S)
{
    var n = S.length;
    var result = n;
 
    // Find and store all divisors of n.
    var v = [];
    v = findAllDivisors(n, v);
 
    // For each divisor,
    // calculate minimum changes required.
    for (var i = 0; i < v.length; i++) {
 
        // Count of operations required
        var count = 0;
 
        var flag = false;
        for (var j = 0; j < n; j += v[i]) {
            for (var k = j; k < j + v[i] && k < n; k++) {
                if (flag && S[k] == '0')
                    count++;
                if (!flag && S[k] == '1')
                    count++;
            }
 
            flag = (flag == false);
        }
 
        // If current changes required
        // is less than previous result
        // then update result
        if (count < result)
            result = count;
    }
    return result;
}
 
// Driver code
var S = "101101";
document.write(findMinOperations(S));
 
//This code is contributed by phasing17


Output

3

Time Complexity: O(N*sqrt(N)), O(sqrt(N)) to find all divisors and O(N) to find all operations for each divisor.
Auxiliary Space: O(sqrt(N)), for storing all divisors.



Similar Reads

Minimize flips to make binary string as all 1s by flipping characters in substring of size K repeatedly
Given a binary string S of size N and an integer K, the task is to find the minimum number of operations required to make all characters as 1s in the binary string by flipping characters in the substring of size K. If it is not possible to do so, then print "-1". Examples: Input: S = "00010110 ", K = 3Output: 3Explanation:Below are the operations p
7 min read
Minimize String length by deleting Substring of same character when K flips are allowed
Given a binary string consisting of '0' and '1' only and an integer K, the task is to minimize the string as far as possible by deleting a substring of the same character, when you can flip at most K characters. Examples: Input: S = "0110", K = 2Output: 0Explanation: We can make two '0' s into '1' or vice versa. So we can delete all the four charac
12 min read
Minimize bit flips such that each continuous segment of same bit has even length
Given a binary string S of even size that contains only 0s and 1s, the task is to find the minimum flips (that is 0 to 1 or 1 to 0) such that every contiguous subsegment that contains the same bit is of even size. Examples: Input: S = "1110011000 "Output: 3Explanation: Change S[2], S[5] and S[6] to '0'. After that S becomes "1100000000", it can be
8 min read
Minimize flips required to make all shortest paths from top-left to bottom-right of a binary matrix equal to S
Given a binary matrix mat[][] having dimensions N * M and a binary string S of length N + M - 1 , the task is to find the minimum number of flips required to make all shortest paths from the top-left cell to the bottom-right cell equal to the given string S. Examples: Input: mat[][] = [[1, 0, 1, 1], [1, 1, 1, 0]], S = "10010"Output: 3 Explanation:
6 min read
Minimize count of flips required to make sum of the given array equal to 0
Given an array arr[] consisting of N integers, the task is to minimize the count of elements required to be multiplied by -1 such that the sum of array elements is 0. If it is not possible to make the sum 0, print "-1". Examples: Input: arr[] = {2, 3, 1, 4}Output: 2Explanation: Multiply arr[0] by -1. Therefore, the array modifies to {-2, 3, 1, 4}.
20 min read
Minimize flips on K-length subarrays required to make all array elements equal to 1
Given a binary array arr[] of size N and a positive integer K, the task is to find the minimum number of times any subarray of size K from the given array arr[] is required to be flipped to make all array elements equal to 1. If it is not possible to do so, then print "-1". Examples: Input: arr[] = {0, 1, 0}, K = 1Output: 2Explanation:Perform the o
17 min read
Minimum Group Flips to Make Binary Array Elements Same
The problem statement asks us to find the minimum number of group flips required to convert a given binary array into an array that either contains all 1s or all 0s. A group flip is defined as flipping a continuous sequence of elements in the array. For example, consider the binary array {1, 1, 0, 0, 0, 1}. We have two choices - we can either make
11 min read
Min flips of continuous characters to make all characters same in a string
Given a string consisting only of 1's and 0's. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: Input : 00011110001110Output : 2We need to convert 1's sequenceso string consist of all 0's.Input : 010101100011Output : 4Method 1 (Change in value
8 min read
Minimum flips to make mean of all k size sub-arrays less than 1
Given an array A of size N, having each element either 0 or 1 and an integer K. Find the minimum number of elements that need to be flipped, such that no sub-array of size greater than or equal to K has an arithmetic mean of 1. Examples: Input: N = 5, A = {1, 1, 1, 1, 1}, K = 5Output: 1Explanation: Initially, mean of only sub-array of size 5 is (1+
11 min read
Minimum flips required to generate continuous substrings of 0’s and 1’s
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: 2 Explanation: 000100101
5 min read