Minimum number of operations required to obtain a given Binary String

Given a binary strings S of length N, the task is to obtain S from a string, say T, of length N consisting only of zeroes, by minimum number of operations. Each operation involves choosing any index i from string S and flipping all the bits at indices [i, N – 1] of the string T
Examples: 
 

Input: S = “101” 
Output:
Explanation: 
“000” -> “111” -> “100” -> “101”. 
Therefore, the minimum number of steps required is 3.
Input: S = “10111” 
Output:
Explanation: 
“00000” -> “11111” -> “10000” -> “10111”. 
Therefore, the minimum number of steps required is 3. 
 

 

Approach: 
The idea is to find the first occurrence of 1 in the given string S and perform the given operation at that index. After this step, for every mismatch in the character of S and T at a particular index, repeat the opertion. 
Follow the steps below: 
 

  1. Iterate over S and mark the first occurrence of 1.
  2. Initialize two variables, say last and ans, where last stores the character (0 or 1) for which the last operation was performed and ans keeps count of the minimum number of steps required.
  3. Iterate from the first occurrence of 1 till the end of the string.
  4. If the current character is 0 and last = 1, then increment the count of ans, and set last = 0.
  5. Otherwise, if last = 0 and the current character is 1, then set last = 1.
  6. Return the final value of ans.

 



Below is the implementation of the above approach:

 

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum
// number of operations required
// to obtain the string s
int minOperations(string s)
{
    int n = s.size();
    int pos = -1;
 
    // Iterate the string s
    for (int i = 0; i < s.size(); i++) {
 
        // If first occurrence of 1
        // is found
        if (s[i] == '1') {
 
            // Mark the index
            pos = i;
            break;
        }
    }
 
    // Base case: If no 1 occurred
    if (pos == -1) {
 
        // No operations required
        return 0;
    }
 
    // Stores the character
    // for which last operation
    // was performed
    int last = 1;
 
    // Stores minimum number
    // of operations
    int ans = 1;
 
    // Iterate from pos to n
    for (int i = pos + 1; i < n; i++) {
 
        // Check if s[i] is 0
        if (s[i] == '0') {
 
            // Check if last operation was
            // performed because of 1
            if (last == 1) {
                ans++;
 
                // Set last to 0
                last = 0;
            }
        }
        else {
 
            if (last == 0) {
 
                // Check if last operation was
                // performed because of 0
                ans++;
 
                // Set last to 1
                last = 1;
            }
        }
    }
 
    // Return the answer
    return ans;
}
 
// Driver Code
int main()
{
    string s = "10111";
 
    cout << minOperations(s);
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement the
// above approach
import java.util.*;
 
class GFG{
 
// Function to find the minimum
// number of operations required
// to obtain the string s
static int minOperations(String s)
{
    int n = s.length();
    int pos = -1;
 
    // Iterate the string s
    for(int i = 0; i < s.length(); i++)
    {
         
        // If first occurrence of 1
        // is found
        if (s.charAt(i) == '1')
        {
             
            // Mark the index
            pos = i;
            break;
        }
    }
 
    // Base case: If no 1 occurred
    if (pos == -1)
    {
 
        // No operations required
        return 0;
    }
 
    // Stores the character
    // for which last operation
    // was performed
    int last = 1;
 
    // Stores minimum number
    // of operations
    int ans = 1;
 
    // Iterate from pos to n
    for(int i = pos + 1; i < n; i++)
    {
         
        // Check if s[i] is 0
        if (s.charAt(i) == '0')
        {
 
            // Check if last operation was
            // performed because of 1
            if (last == 1)
            {
                ans++;
 
                // Set last to 0
                last = 0;
            }
        }
        else
        {
            if (last == 0)
            {
 
                // Check if last operation was
                // performed because of 0
                ans++;
 
                // Set last to 1
                last = 1;
            }
        }
    }
     
    // Return the answer
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String s = "10111";
     
    System.out.println(minOperations(s));
}
}
 
// This code is contributed by offbeat
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to find the minimum
# number of operations required
# to obtain the string s
def minOperations(s):
 
    n = len(s)
    pos = -1
 
    # Iterate the string s
    for i in range(len(s)):
 
        # If first occurrence of 1
        # is found
        if (s[i] == '1'):
 
            # Mark the index
            pos = i
            break
 
    # Base case: If no 1 occurred
    if (pos == -1):
 
        # No operations required
        return 0
 
    # Stores the character
    # for which last operation
    # was performed
    last = 1
 
    # Stores minimum number
    # of operations
    ans = 1
 
    # Iterate from pos to n
    for i in range(pos + 1, n):
 
        # Check if s[i] is 0
        if (s[i] == '0'):
 
            # Check if last operation was
            # performed because of 1
            if (last == 1):
                ans += 1
 
                # Set last to 0
                last = 0
         
        else:
 
            if (last == 0):
 
                # Check if last operation was
                # performed because of 0
                ans += 1
 
                # Set last to 1
                last = 1
 
    # Return the answer
    return ans
 
# Driver Code
if __name__ == "__main__":
     
    s = "10111"
 
    print(minOperations(s))
 
# This code is contributed by chitranayal
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement the
// above approach
using System;
class GFG{
  
// Function to find the minimum
// number of operations required
// to obtain the string s
static int minOperations(String s)
{
    int n = s.Length;
    int pos = -1;
  
    // Iterate the string s
    for(int i = 0; i < s.Length; i++)
    {
          
        // If first occurrence of 1
        // is found
        if (s[i] == '1')
        {
              
            // Mark the index
            pos = i;
            break;
        }
    }
  
    // Base case: If no 1 occurred
    if (pos == -1)
    {
  
        // No operations required
        return 0;
    }
  
    // Stores the character
    // for which last operation
    // was performed
    int last = 1;
  
    // Stores minimum number
    // of operations
    int ans = 1;
  
    // Iterate from pos to n
    for(int i = pos + 1; i < n; i++)
    {
          
        // Check if s[i] is 0
        if (s[i] == '0')
        {
  
            // Check if last operation was
            // performed because of 1
            if (last == 1)
            {
                ans++;
  
                // Set last to 0
                last = 0;
            }
        }
        else
        {
            if (last == 0)
            {
  
                // Check if last operation was
                // performed because of 0
                ans++;
  
                // Set last to 1
                last = 1;
            }
        }
    }
      
    // Return the answer
    return ans;
}
  
// Driver code
public static void Main(string[] args)
{
    String s = "10111";
      
    Console.Write(minOperations(s));
}
}
  
// This code is contributed by rock_cool
chevron_right

Output: 
3


 

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.




Article Tags :