Open In App

Minimize flips to make binary string as all 1s by flipping characters in substring of size K repeatedly

Last Updated : 29 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 = 3
Output: 3
Explanation:
Below are the operations performed:

  1. Consider the substring S[0, 2] which is of size K(= 3) and flipping those characters modifies the string to “11110110”.
  2. Consider the substring S[4, 6] which is of size K(= 3) and flipping those characters modifies the string to “11111000”.
  3. Consider the substring S[5, 7] which is of size K(= 3) and flipping those characters modifies the string to “11111111”.

After the above operations, all the 0s are converted to 1s, and the minimum number of operations required is 3.

Input: S = “01010”, K = 4
Output: -1

Approach: The given problem can be solved using the Greedy Approach. Follow the below steps to solve the problem:

  • Initialize a variable, say minOperations as 0 that stores the count of the minimum number of operations required.
  • Traverse the string S using the variable i and if the characters S[i] is ‘0’ and the value of (i + K) is at most K, then flip all the characters of the substring S[i, i + K] and increment the value of minOperations by 1.
  • After the above operations, traverse the string S and if there exists any character ‘0’ then print “-1” and break out of the loop.
  • If all the characters of the string S are 1s, then print the minOperations as the resultant minimum number of operations.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number
// of operations required to convert all
// the characters to 1 by flipping the
// substrings of size K
void minOperation(string S, int K, int N)
{
 
    // Stores the minimum number of
    // operations required
    int min = 0;
 
    int i;
 
    // Traverse the string S
    for (i = 0; i < N; i++) {
 
        // If the character is 0
        if (S[i] == '0' && i + K <= N) {
 
            // Flip the substrings of
            // size K starting from i
            for (int j = i; j < i + K; j++) {
                if (S[j] == '1')
                    S[j] = '0';
                else
                    S[j] = '1';
            }
 
            // Increment the minimum count
            // of operations required
            min++;
        }
    }
 
    // After performing the operations
    // check if string S contains any 0s
    for (i = 0; i < N; i++) {
        if (S[i] == '0')
            break;
    }
 
    // If S contains only 1's
    if (i == N)
        cout << min;
    else
        cout << -1;
}
 
// Driver Code
int main()
{
 
    string S = "00010110";
    int K = 3;
    int N = S.length();
    minOperation(S, K, N);
 
    return 0;
}


Java




// Java program for the above approach
public class GFG
{
 
// Function to find the minimum number
// of operations required to convert all
// the characters to 1 by flipping the
// substrings of size K
static void minOperation(String S, int K, int N)
{
 
    // Stores the minimum number of
    // operations required
    int min = 0;
 
    int i;
 
    // Traverse the string S
    for (i = 0; i < N; i++) {
 
        // If the character is 0
        if (S.charAt(i) == '0' && i + K <= N) {
 
            // Flip the substrings of
            // size K starting from i
            for (int j = i; j < i + K; j++) {
                if (S.charAt(j) == '1')
                    S = S.substring(0, j) + '0' + S.substring(j + 1);
                else
                   S = S.substring(0, j) + '1' + S.substring(j + 1);
            }
 
            // Increment the minimum count
            // of operations required
            min++;
        }
    }
 
    // After performing the operations
    // check if string S contains any 0s
    for (i = 0; i < N; i++) {
        if (S.charAt(i) == '0')
            break;
    }
 
    // If S contains only 1's
    if (i == N)
      System.out.println(min);
    else
      System.out.println(-1);
}
 
// Driver Code
public static void main(String []args)
{
 
    String S = "00010110";
    int K = 3;
    int N = S.length();
    minOperation(S, K, N);
}
}
 
// This code is contributed by AnkThon


Python3




# Function to find the minimum number
# of operations required to convert all
# the characters to 1 by flipping the
# substrings of size K
def minOperation(St, K, N):
    S = list(St)
 
    # Stores the minimum number of
    # operations required
    min = 0
 
    i = 0
 
    # Traverse the string S
    for i in range(0, N):
 
        # If the character is 0
        if (S[i] == '0' and i + K <= N):
 
            # Flip the substrings of
            # size K starting from i
            j = i
            while(j < i + K):
                if (S[j] == '1'):
                    S[j] = '0'
                else:
                    S[j] = '1'
                j += 1
 
            # Increment the minimum count
            # of operations required
            min += 1
 
    # After performing the operations
    # check if string S contains any 0s
    temp = 0
 
    for i in range(0, N):
        temp += 1
        if (S[i] == '0'):
            break
 
    # If S contains only 1's
    if (temp == N):
        print(min)
    else:
        print(-1)
 
# Driver Code
S = "00010110"
K = 3
N = len(S)
minOperation(S, K, N)
 
# This code is contributed by gfgking


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the minimum number
// of operations required to convert all
// the characters to 1 by flipping the
// substrings of size K
static void minOperation(string S, int K, int N)
{
 
    // Stores the minimum number of
    // operations required
    int min = 0;
 
    int i;
 
    // Traverse the string S
    for (i = 0; i < N; i++) {
 
        // If the character is 0
        if (S[i] == '0' && i + K <= N) {
 
            // Flip the substrings of
            // size K starting from i
            for (int j = i; j < i + K; j++) {
                if (S[j] == '1')
                    S = S.Substring(0, j) + '0' + S.Substring(j + 1);
                else
                   S = S.Substring(0, j) + '1' + S.Substring(j + 1);
            }
 
            // Increment the minimum count
            // of operations required
            min++;
        }
    }
 
    // After performing the operations
    // check if string S contains any 0s
    for (i = 0; i < N; i++) {
        if (S[i] == '0')
            break;
    }
 
    // If S contains only 1's
    if (i == N)
      Console.Write(min);
    else
      Console.Write(-1);
}
 
// Driver Code
public static void Main()
{
 
    string S = "00010110";
    int K = 3;
    int N = S.Length;
    minOperation(S, K, N);
}
}
 
// This code is contributed by SURENDRA_GANGWAR.


Javascript




<script>
 
// Function to find the minimum number
// of operations required to convert all
// the characters to 1 by flipping the
// substrings of size K
function minOperation(St, K, N)
{
    S = St.split('');
 
    // Stores the minimum number of
    // operations required
    let min = 0;
 
    let i;
 
    // Traverse the string S
    for (i = 0; i < N; i++) {
 
        // If the character is 0
        if (S[i] == '0' && i + K <= N) {
 
            // Flip the substrings of
            // size K starting from i
            for (let j = i; j < i + K; j++) {
                if (S[j] == '1')
                    S[j] = '0';
                else
                    S[j] = '1';
            }
 
            // Increment the minimum count
            // of operations required
            min++;
        }
    }
 
    // After performing the operations
    // check if string S contains any 0s
    for (i = 0; i < N; i++) {
        if (S[i] == '0')
            break;
    }
 
    // If S contains only 1's
    if (i == N)
        document.write(min);
    else
        document.write(-1);
}
 
// Driver Code
        let S = "00010110";
    let K = 3;
    let N = S.length;
    minOperation(S, K, N);
 
// This code is contributed by sanjoy_62.   
</script>


 
 

Output: 

3

 

 

Time Complexity: O(N*K)
Auxiliary Space: O(1)

 



Similar Reads

Minimize cost to make all characters of a Binary String equal to '1' by reversing or flipping characters of substrings
Given a binary string S, and two integers A, which denotes the cost of reversing a substring, and B, which denotes the cost of flipping all characters of a substring, the task is to find the minimum cost to reduce the string S to 1s only. Examples: Input: S = "01100", A = 1, B = 5Output: 6Explanation: One possible way to make all characters equal t
8 min read
Maximum length of a substring required to be flipped repeatedly to make all characters of binary string equal to 0
Given a binary string S, the task is to find the maximum length of substrings required to be flipped repeatedly to make all the characters of a binary string equal to '0'. Examples: Input: S = "010"Output: 2Explanation:Following are the order of flipping of substring of at least K for the value of K as 2: Flip the substring S[0, 2] of length 3(&gt;
6 min read
Minimize operations to make given binary string as all 1s by repeatedly converting K consecutive characters to 1
Given a binary string str of N characters an integer K, the task is to find the minimum moves required to convert all characters of the string to 1's where at each move, K consecutive characters can be converted to 1. Example: Input: str="0010", K=3Output: 2Explanation:Move 1: Select the substring from 0 to 2 and replace it with all 1.Move 2: Selec
4 min read
Minimum flips required in a binary string such that all K-size substring contains 1
Given a binary string str of size N and a positive integer K, the task is to find the minimum number of flips required to make all substring of size K contain at least one '1'.Examples: Input: str = "0001", K = 2 Output: 1 Explanation: Flipping the bit at index 1 modifies str to "0101". All substrings of size 2 are "01", "10", and "01". Each substr
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
Minimize a binary string by repeatedly removing even length substrings of same characters
Given a binary string str of size N, the task is to minimize the length of given binary string by removing even length substrings consisting of sam characters, i.e. either 0s or 1s only, from the string any number of times. Finally, print the modified string. Examples: Input: str ="101001"Output: "10"Explanation: The string can be minimized in the
8 min read
Minimize cost of flipping or swaps to make a Binary String balanced
Given a binary string S of size N(where N is even), the task is to find the minimum cost of making the given binary string balanced by flipping one of the adjacent different characters at the cost of 1 unit or swap the characters at indices i and j such that (i &lt; j) at the cost of (j - i) unit. If it is impossible to make the string balanced, th
6 min read
Minimize flipping of bits in given Binary string to make count of 10 equal to 01
Given binary string str, the task is to choose any index and change into 0 or 1, and do this in minimum steps such that the count of substring 01 is equal to 10. Examples: Input: str = "01101"Output: 01100Explanation: 01 as a substring repeat 2 times in a string, 10 as a substring repeat 1 times in a string. So, change last char 1 into 0 then count
5 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 flips to make substrings of size K same and alternative
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, andThe first K bits in T are 0
9 min read