Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Minimize Suffix flip to make Binary String non decreasing

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a binary string str, the task is to find the minimum operations required to convert the binary string in a non-decreasing manner such that in each operation an index i is chosen and all bits right to it are flipped.

Examples:

Input: str = “100010”
Output: 3
Explanation: On flipping at index 0 it becomes 111101. 
On flipping at the index at index 3 it becomes 111110. 
On flipping at index 4 it becomes 111111, i.e., non-decreasing 
So the minimum operations required are 3.

Input: str = “00001111”
Output: 0
Explanation: The string is already in non-decreasing order so 0 operations are required.

Naive Approach: This problem can be solved using the following idea:

At index i, where previous character at index i-1 is different, there will be having two choices: 

  • Change all the right bits from i to n-1 and increase the count of operations.
  • Ignoring this bit and iterate further.

Follow the steps mentioned below to solve the problem:

  • Initialize a variable res =0 to count the minimum operation.
  • Iterate through the string and check if the character at index i is equal to the previous character or not.
    • If not, either flip all the right bits from that index i or ignore that index and iterate further.
    • If all the right bits are flipped, increment the res.
  • Return the res.

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

Efficient Approach: This can be solved using the following idea:

At index i, where previous character at index i – 1 is different,  just maintain a flag to check whether flip has occurred or not before and increase the count of operations. 

Follow the steps mentioned below to solve the problem:

  • Initialize a variable res = 0 to count the minimum operations and flag = 0 to check if the flip has occurred before.
  • Iterate through the string and check if the character at index i is equal to the previous character or not.
    • If not, and flag = 0 and the current character is ‘0’, it means it is a decreasing sequence and it needs to be flipped.
    • So make the flag = 1 and increment the res.
    • Else if flag = 1 there is a flip before and so the result should be incremented since the present and previous are not equal.
  • Return the res.

Below is the implementation of the above approach.

C++

// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function to count minimum operations
int minOperations(string str)
{
    // Initialize res = 0 to store the minimum
    // operations required
    int res = 0;

    // Initialize a flag to check flip
    // has occurred or not before
    bool flag = 0;

    for (int i = 1; i < str.length(); i++) {

        // If two adjacent are not equal
        if (str[i] != str[i - 1]) {

            // If it is decreasing and flag = 0
            // then  make flag = 1 and flip by
            // incrementing operations
            if (flag == 0 && str[i] == '0') {
                flag = 1;
                res++;
            }

            // If it is already flipped before
            // increment the operations since
            // two adjacent are not same
            else if (flag == 1) {
                res++;
            }
        }
    }

    // Return the minimum operations required
    return res;
}

// Driver code
int main()
{
    string str = "100010";

    // Function call
    cout << minOperations(str);

    return 0;
}

Java

// Java code to implement the approach
import java.io.*;

class GFG 
{
  
  // Function to count minimum operations
  public static int minOperations(String str)
  {
    
    // Initialize res = 0 to store the minimum
    // operations required
    int res = 0;

    // Initialize a flag to check flip
    // has occurred or not before
    int flag = 0;

    for (int i = 1; i < str.length(); i++) {

      // If two adjacent are not equal
      if (str.charAt(i) != str.charAt(i - 1)) {

        // If it is decreasing and flag = 0
        // then  make flag = 1 and flip by
        // incrementing operations
        if (flag == 0 && str.charAt(i) == '0') {
          flag = 1;
          res++;
        }

        // If it is already flipped before
        // increment the operations since
        // two adjacent are not same
        else if (flag == 1) {
          res++;
        }
      }
    }

    // Return the minimum operations required
    return res;
  }

  // Driver Code
  public static void main(String[] args)
  {
    String str = "100010";

    // Function call
    System.out.print(minOperations(str));
  }
}

// This code is contributed by Rohit Pradhan

Python3

# Python code to implement the approach

# Function to count minimum operations
def minOperations(str):
  
    # Initialize res = 0 to store the minimum
    # operations required
    res = 0

    # Initialize a flag to check flip
    # has occurred or not before
    flag = 0

    for i in range(1, len(str)):
      
        # If two adjacent are not equal
        if(str[i] != str[i-1]):
          
            # If it is decreasing and flag = 0
            # then  make flag = 1 and flip by
            # incrementing operations
            if(flag == 0 and str[i] == '0'):
                flag = 1
                res += 1
                
            # If it is already flipped before
            # increment the operations since
            # two adjacent are not same
            elif(flag == 1):
                res += 1

    # return the minimum operations required
    return res

str = "100010"

# Function call
print(minOperations(str))

# This code is contributed by lokesh

C#

// C# code to implement the approach
using System;

public class GFG{
    
    // Function to count minimum operations
public static int minOperations(string str)
{
    
    // Initialize res = 0 to store the minimum
    // operations required
    int res = 0;

    // Initialize a flag to check flip
    // has occurred or not before
    int flag = 0;

    for (int i = 1; i < str.Length; i++) {

    // If two adjacent are not equal
    if (str[i] != str[i - 1]) {

        // If it is decreasing and flag = 0
        // then make flag = 1 and flip by
        // incrementing operations
        if (flag == 0 && str[i] == '0') {
        flag = 1;
        res++;
        }

        // If it is already flipped before
        // increment the operations since
        // two adjacent are not same
        else if (flag == 1) {
        res++;
        }
    }
    }

    // Return the minimum operations required
    return res;
}

    
    // Driver Code
    static public void Main (){
        string str = "100010";

    // Function call
    Console.WriteLine(minOperations(str));
    }
}

// This code is contributed by Pushpesh Raj.

Javascript

        // JavaScript code to implement the approach

        // Function to count minimum operations
        const minOperations = (str) => {
        
            // Initialize res = 0 to store the minimum
            // operations required
            let res = 0;

            // Initialize a flag to check flip
            // has occurred or not before
            let flag = 0;

            for (let i = 1; i < str.length; i++) {

                // If two adjacent are not equal
                if (str[i] != str[i - 1]) {

                    // If it is decreasing and flag = 0
                    // then make flag = 1 and flip by
                    // incrementing operations
                    if (flag == 0 && str[i] == '0') {
                        flag = 1;
                        res++;
                    }

                    // If it is already flipped before
                    // increment the operations since
                    // two adjacent are not same
                    else if (flag == 1) {
                        res++;
                    }
                }
            }

            // Return the minimum operations required
            return res;
        }

        // Driver code
        str = "100010";

        // Function call
        console.log(minOperations(str));

        // This code is contributed by rakeshsahni
Output

3

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


My Personal Notes arrow_drop_up
Last Updated : 13 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials