Related Articles
Minimum non-adjacent pair flips required to remove all 0s from a Binary String
• Difficulty Level : Medium
• Last Updated : 30 Sep, 2020

Given a binary string S, the task is to find the minimum number of operations of flipping at most two non-adjacent characters from the binary string required to remove all 0s.

Examples:

Input: S = “110010”
Output: 2
Explanation:
Step 1: Flip indices 2 and 5. The string is modified to “111011”
Step 2: Flip only index 3. The string is modified to “111111”.
Therefore, minimum operations required is 2.

Input: S= “110”
Output:

Naive Approach: The simplest approach is to traverse the given string. For all characters of the string found to be ‘0’, traverse its right to find the next ‘0‘ which is not adjacent to the current character. Flip both the characters and increment answer by 1. If no ‘0’ to the right, flip the current character and increment the answer by 1.

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The idea is to store the index of previous characters those need to be flipped. Below is the illustration with the help of steps:

• Initialize two variables to maintain the index of previously found 0s in the string with -1.
• Traverse the string and check if the last two found indices are not adjacent, then increment the counter by 1. Also, update the position of the last two previously found indices.
• Finally, after completing the traversal, increment the counter by 2 if both the last found indices are not -1. Otherwise, increment the counter by 1 if one of the last found indices is not -1.

Below is the implementation of the above approach:

## C++

 `// C++ program for ` `// the above approach` `#include` `using` `namespace` `std;`   `// Function to find minimum flips` `// required to remove all 0s from` `// a given binary string` `int` `minOperation(string s)` `{` `  ``// Length of given string` `  ``int` `n = s.length();`   `  ``// Stores the indices of` `  ``// previous 0s` `  ``int` `temp1 = -1, temp2 = -1;`   `  ``// Stores the minimum operations` `  ``int` `ans = 0;`   `  ``// Traverse string to find minimum` `  ``// operations to obtain required string` `  ``for` `(``int` `i = 0; i < n; i++) ` `  ``{` `    ``// Current character` `    ``int` `curr = s[i];`   `    ``// If current character is '0'` `    ``if` `(curr == ``'0'``) ` `    ``{` `      ``// Update temp1 with current` `      ``// index, if both temp` `      ``// variables are empty` `      ``if` `(temp1 == -1 && temp2 == -1) ` `      ``{` `        ``temp1 = i;` `      ``}`   `      ``// Update temp2 with current` `      ``// index, if temp1 contains` `      ``// prev index but temp2 is empty` `      ``else` `if` `(temp1 != -1 && temp2 == -1 && ` `               ``i - temp1 == 1) ` `      ``{` `        ``temp2 = i;` `      ``}`   `      ``// If temp1 is not empty` `      ``else` `if` `(temp1 != -1) ` `      ``{` `        ``// Reset temp1 to -1` `        ``temp1 = -1;`   `        ``// Increase ans` `        ``ans++;` `      ``}`   `      ``// If temp2 is not empty but` `      ``// temp1 is empty` `      ``else` `if` `(temp1 == -1 && temp2 != -1 && ` `               ``i - temp2 != 1) ` `      ``{` `        ``// Reset temp2 to -1` `        ``temp2 = -1;`   `        ``// Increase ans` `        ``ans++;` `      ``}` `    ``}` `  ``}`   `  ``// If both temp variables ` `  ``// are not empty` `  ``if` `(temp1 != -1 && temp2 != -1) ` `  ``{` `    ``ans += 2;` `  ``}` `  ``// Otherwise` `  ``else` `if` `(temp1 != -1 || temp2 != -1) ` `  ``{` `    ``ans += 1;` `  ``}`   `  ``// Return the answer` `  ``return` `ans;` `}`   `// Driver Code` `int` `main()` `{` `  ``string s = ``"110010"``;` `  ``cout << (minOperation(s));` `}`   `// This code is contributed by gauravrajput1`

## Java

 `// Java program for above approach`   `import` `java.util.*;`   `class` `GFG {`   `    ``// Function to find minimum flips` `    ``// required to remove all 0s from` `    ``// a given binary string` `    ``static` `int` `minOperation(String s)` `    ``{` `        ``// Length of given string` `        ``int` `n = s.length();`   `        ``// Stores the indices of` `        ``// previous 0s` `        ``int` `temp1 = -``1``, temp2 = -``1``;`   `        ``// Stores the minimum operations` `        ``int` `ans = ``0``;`   `        ``// Traverse string to find minimum` `        ``// operations to obtain required string` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``// Current character` `            ``int` `curr = s.charAt(i);`   `            ``// If current character is '0'` `            ``if` `(curr == ``'0'``) {` `                ``// Update temp1 with current` `                ``// index, if both temp` `                ``// variables are empty` `                ``if` `(temp1 == -``1` `&& temp2 == -``1``) {` `                    ``temp1 = i;` `                ``}`   `                ``// Update temp2 with current` `                ``// index, if temp1 contains` `                ``// prev index but temp2 is empty` `                ``else` `if` `(temp1 != -``1` `&& temp2 == -``1` `                         ``&& i - temp1 == ``1``) {` `                    ``temp2 = i;` `                ``}`   `                ``// If temp1 is not empty` `                ``else` `if` `(temp1 != -``1``) {` `                    ``// Reset temp1 to -1` `                    ``temp1 = -``1``;`   `                    ``// Increase ans` `                    ``ans++;` `                ``}`   `                ``// If temp2 is not empty but` `                ``// temp1 is empty` `                ``else` `if` `(temp1 == -``1` `&& temp2 != -``1` `                         ``&& i - temp2 != ``1``) {` `                    ``// Reset temp2 to -1` `                    ``temp2 = -``1``;`   `                    ``// Increase ans` `                    ``ans++;` `                ``}` `            ``}` `        ``}`   `        ``// If both temp variables are not empty` `        ``if` `(temp1 != -``1` `&& temp2 != -``1``) {` `            ``ans += ``2``;` `        ``}` `        ``// Otherwise` `        ``else` `if` `(temp1 != -``1` `|| temp2 != -``1``) {` `            ``ans += ``1``;` `        ``}`   `        ``// Return the answer` `        ``return` `ans;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args)` `    ``{`   `        ``String s = ``"110010"``;` `        ``System.out.println(minOperation(s));` `    ``}` `}`

## Python3

 `# Python3 program for above approach`   `# Function to find minimum flips` `# required to remove all 0s from` `# a given binary string` `def` `minOperation(s):`   `    ``# Length of given string` `    ``n ``=` `len``(s)`   `    ``# Stores the indices of` `    ``# previous 0s` `    ``temp1 ``=` `-``1` `    ``temp2 ``=` `-``1`   `    ``# Stores the minimum operations` `    ``ans ``=` `0`   `    ``# Traverse string to find minimum` `    ``# operations to obtain required string` `    ``for` `i ``in` `range``(n):` `        `  `        ``# Current character` `        ``curr ``=` `s[i]`   `        ``# If current character is '0'` `        ``if` `(curr ``=``=` `'0'``):` `            `  `            ``# Update temp1 with current` `            ``# index, if both temp` `            ``# variables are empty` `            ``if` `(temp1 ``=``=` `-``1` `and` `temp2 ``=``=` `-``1``):` `                ``temp1 ``=` `i`   `            ``# Update temp2 with current` `            ``# index, if temp1 contains` `            ``# prev index but temp2 is empty` `            ``elif` `(temp1 !``=` `-``1` `and` `temp2 ``=``=` `-``1` `and` `                               ``i ``-` `temp1 ``=``=` `1``):` `                ``temp2 ``=` `i` `                `  `            ``# If temp1 is not empty` `            ``elif` `(temp1 !``=` `-``1``):` `                `  `                ``# Reset temp1 to -1` `                ``temp1 ``=` `-``1`   `                ``# Increase ans` `                ``ans ``+``=` `1`   `            ``# If temp2 is not empty but` `            ``# temp1 is empty` `            ``elif` `(temp1 ``=``=` `-``1` `and` `temp2 !``=` `-``1` `and` `                              ``i ``-` `temp2 !``=` `1``):` `                                  `  `                ``# Reset temp2 to -1` `                ``temp2 ``=` `-``1`   `                ``# Increase ans` `                ``ans ``+``=` `1` `                `  `    ``# If both temp variables are not empty` `    ``if` `(temp1 !``=` `-``1` `and` `temp2 !``=` `-``1``):` `        ``ans ``+``=` `2`   `    ``# Otherwise` `    ``elif` `(temp1 !``=` `-``1` `or` `temp2 !``=` `-``1``):` `        ``ans ``+``=` `1`   `    ``# Return the answer` `    ``return` `ans`   `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:` `    `  `    ``s ``=` `"110010"` `    `  `    ``print``(minOperation(s))`   `# This code is contributed by mohit kumar 29`

## C#

 `// C# program for ` `// the above approach` `using` `System;` `class` `GFG{`   `// Function to find minimum flips` `// required to remove all 0s from` `// a given binary string` `static` `int` `minOperation(String s)` `{` `  ``// Length of given string` `  ``int` `n = s.Length;`   `  ``// Stores the indices of` `  ``// previous 0s` `  ``int` `temp1 = -1, temp2 = -1;`   `  ``// Stores the minimum operations` `  ``int` `ans = 0;`   `  ``// Traverse string to find minimum` `  ``// operations to obtain required string` `  ``for` `(``int` `i = 0; i < n; i++) ` `  ``{` `    ``// Current character` `    ``int` `curr = s[i];`   `    ``// If current character is '0'` `    ``if` `(curr == ``'0'``) ` `    ``{` `      ``// Update temp1 with current` `      ``// index, if both temp` `      ``// variables are empty` `      ``if` `(temp1 == -1 && temp2 == -1) ` `      ``{` `        ``temp1 = i;` `      ``}`   `      ``// Update temp2 with current` `      ``// index, if temp1 contains` `      ``// prev index but temp2 is empty` `      ``else` `if` `(temp1 != -1 && ` `               ``temp2 == -1 && ` `               ``i - temp1 == 1) ` `      ``{` `        ``temp2 = i;` `      ``}`   `      ``// If temp1 is not empty` `      ``else` `if` `(temp1 != -1) ` `      ``{` `        ``// Reset temp1 to -1` `        ``temp1 = -1;`   `        ``// Increase ans` `        ``ans++;` `      ``}`   `      ``// If temp2 is not empty but` `      ``// temp1 is empty` `      ``else` `if` `(temp1 == -1 && ` `               ``temp2 != -1 && ` `               ``i - temp2 != 1) ` `      ``{` `        ``// Reset temp2 to -1` `        ``temp2 = -1;`   `        ``// Increase ans` `        ``ans++;` `      ``}` `    ``}` `  ``}`   `  ``// If both temp variables ` `  ``// are not empty` `  ``if` `(temp1 != -1 && temp2 != -1) ` `  ``{` `    ``ans += 2;` `  ``}` `  `  `  ``// Otherwise` `  ``else` `if` `(temp1 != -1 || temp2 != -1) ` `  ``{` `    ``ans += 1;` `  ``}`   `  ``// Return the answer` `  ``return` `ans;` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{` `  ``String s = ``"110010"``;` `  ``Console.WriteLine(minOperation(s));` `}` `}`   `// This code is contributed by Rajput-Ji`

Output:

```2

```

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

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
Recommended Articles
Page :