Get the best out of our app
GFG App
Open App
Browser
Continue

# Minimum non-adjacent pair flips required to remove all 0s from a Binary String

The problem statement asks us to find the minimum number of operations required to remove all 0s from a given binary string S. An operation involves flipping at most two non-adjacent characters (i.e., characters that are not next to each other) in the string.

Let’s take the first example given: S = “110010”. The initial string contains three 0s at indices 3, 4, and 5. We need to perform a series of operations to flip some characters in the string to eventually remove all the 0s.

One possible sequence of operations to achieve this goal is:

Step 1: Flip the characters at indices 2 and 5 to get “111011”
Step 2: Flip the character at index 3 to get “111111”

After these two operations, we have removed all the 0s from the string. Note that we could have performed the operations in a different order, or used different indices to flip the characters, but this particular sequence of operations gives us the minimum number of flips required, which is 2.

For the second example, S = “110”, we can remove the 0 at index 2 with just one operation: flip the character at index 1 to get “100”. Therefore, the minimum number of operations required is 1.

I hope this explanation helps! Let me know if you have any further questions.

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`

## Javascript

 ``

Output:

`2`

Time Complexity: O(N) “The time complexity of the given implementation is O(n), where n is the length of the input string s. This is because the algorithm processes each character in the string once.”
Auxiliary Space: O(1) “The auxiliary space used by the implementation is O(1), which is constant. This is because the implementation only uses a few integer variables to store the state of the algorithm, and these variables do not depend on the length of the input string.”

Space Complexity: O(n) “The space complexity of the implementation is also O(n), since the input string is stored in memory and its length can be at most n. However, this is the input space required by the problem, and it is not an additional space requirement imposed by the algorithm itself.”

In summary, the time complexity of the algorithm is O(n), the auxiliary space used is O(1), and the space complexity is O(n) due to the input space required by the problem.

My Personal Notes arrow_drop_up
Similar Reads
Related Tutorials