Skip to content
Related Articles

Related Articles

Improve Article

Find Binary string by converting all 01 or 10 to 11 after M iterations

  • Difficulty Level : Medium
  • Last Updated : 08 Sep, 2021
Geek Week

Given a binary string str[] of size N and an integer M. This binary string can be modified by flipping all the 0’s to 1 which have exactly one 1 as a neighbour. The task is to find the final state of the binary string after M such iterations.
Note: 2≤N≤103, 1≤M≤109

Examples:

Input: str=”01100″, M=1
Output: 11110
Explanation: After First Iteration: 11110

Input: str = “0110100”, M=3
Output: 1110111
Explanation: After First Iteration: 1110110, After Second Iteration: 1110111, After Third Iteration:  Remains the same.

Approach: The solution is based on the observation that the modification can go on for no more than N iterations, because even if in each iteration, atleast one 0 is flipped, then it would go on for maximum N times and, if no zero is flipped in an iteration, then this would mean that the binary string remain in the same state as on the previous step and the simulation is over. Hence, the total number of iterations will be a minimum of N and M. Follow the steps below to solve the problem:

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 modified
// binary string after M iterations
void findString(string str, int M)
{
    int N = str.length();
 
    // Set the value of M to the minimum
    // of N or M.
    M = min(M, N);
 
    // Declaration of current string state
    string s1 = "";
 
    // Loop over M iterations
    while (M != 0) {
 
        // Set the current state as null
        // before each iteration
        s1 = "";
 
        for (int i = 0; i < N; i++) {
 
            if (str[i] == '0') {
 
                // Check if this zero has exactly
                // one 1 as neighbour
                if ((str[i - 1] == '1'
                     && str[i + 1] != '1')
                    || (str[i - 1] != '1'
                        && str[i + 1] == '1'))
 
                    // Flip the zero
                    s1 += '1';
 
                else
                    s1 += '0';
            }
            else
                s1 += '1';
        }
 
        // If there is no change,
        // then no need for
        // further iterations.
        if (str == s1)
            break;
 
        // Set the current state
        // as the new previous state
        str = s1;
        M--;
    }
 
    cout << s1;
}
 
// Driver Code
int main()
{
    // Given String
    string str = "0110100";
 
    // Number of Iterations
    int M = 3;
 
    // Function Call
    findString(str, M);
 
    return 0;
}

Java




// Java program for the above approach.
import java.io.*;
import static java.lang.Math.min;
import java.lang.*;
 
class GFG
{
   
// Function to find the modified
// binary string after M iterations
public static void findString(String str, int M)
{
    int N = str.length();
 
    // Set the value of M to the minimum
    // of N or M.
    M = Math.min(M, N);
 
    // Declaration of current string state
    String s1 = "";
 
    // Loop over M iterations
    while (M != 0) {
 
        // Set the current state as null
        // before each iteration
        s1 = "";
 
        for (int i = 0; i < N; i++) {
 
            if (str.charAt(i) == '0') {
 
                // Check if this zero has exactly
                // one 1 as neighbour
                if ((str.charAt(i) == '1'
                     && str.charAt(i) != '1')
                    || (str.charAt(i) == '1'
                        && str.charAt(i) == '1'))
 
                    // Flip the zero
                    s1 += '1';
 
                else
                    s1 += '0';
            }
            else
                s1 += '1';
        }
 
        // If there is no change,
        // then no need for
        // further iterations.
        if (str == s1)
            break;
 
        // Set the current state
        // as the new previous state
        str = s1;
        M--;
    }
 
    System.out.print(s1);
}
 
// Driver Code
public static void main (String[] args)
{
   
    // Given String
    String str = "0110100";
 
    // Number of Iterations
    int M = 3;
 
    // Function Call
    findString(str, M);
 
}
}
 
// This code is contributed by shivanisinghss2110

Python3




# Python 3 program for the above approach.
 
# Function to find the modified
# binary string after M iterations
def findString(str,M):
    N = len(str)
 
    # Set the value of M to the minimum
    # of N or M.
    M = min(M, N)
 
    # Declaration of current string state
    s1 = ""
 
    # Loop over M iterations
    while (M != 0):
       
        # Set the current state as null
        # before each iteration
        s1 = ""
 
        for i in range(N-1):
            if (str[i] == '0'):
               
                # Check if this zero has exactly
                # one 1 as neighbour
                if ((str[i - 1] == '1' and str[i + 1] != '1') or (str[i - 1] != '1' and str[i + 1] == '1')):
                    # Flip the zero
                    s1 += '1'
 
                else:
                    s1 += '0'
            else:
                s1 += '1'
 
        # If there is no change,
        # then no need for
        # further iterations.
        if (str == s1):
            break
        s1 += '1'
 
        # Set the current state
        # as the new previous state
        str = s1
        M -= 1
 
    print(s1)
 
# Driver Code
if __name__ == '__main__':
   
    # Given String
    str = "0110100"
 
    # Number of Iterations
    M = 3
 
    # Function Call
    findString(str, M)
     
    # This code is contributed by ipg2016107.

C#




// C# program for the above approach.
using System;
class GFG {
     
    // Function to find the modified
    // binary string after M iterations
    static void findString(string str, int M)
    {
        int N = str.Length;
      
        // Set the value of M to the minimum
        // of N or M.
        M = Math.Min(M, N);
      
        // Declaration of current string state
        string s1 = "";
      
        // Loop over M iterations
        while (M != 0) {
      
            // Set the current state as null
            // before each iteration
            s1 = "";
      
            for (int i = 0; i < N; i++) {
                 
                if (str[i] == '0')
                {                                                       
                    // Check if this zero has exactly
                    // one 1 as neighbour
                    if (((i>0 && str[i - 1] == '1') && (i<N-1 && str[i + 1] != '1')) || ((i>0 && str[i - 1] != '1') && (i<N-1 && str[i + 1] == '1')))
                    {
                        // Flip the zero
                        s1 += '1';
                    }
                    else
                    {
                         
                        if(i==0 || i==N-1)
                        {
                            s1 += '1';   
                        }
                        else
                        {
                            s1 += '0';
                        }
                         
                    }
                }
                else
                {
                    s1 += '1';
                }
            }
      
            // If there is no change,
            // then no need for
            // further iterations.
            if (str == s1)
                break;
      
            // Set the current state
            // as the new previous state
            //str = s1;
            M--;
        }
      
        Console.WriteLine(s1);
    }
 
  static void Main() {
    // Given String
    string str = "0110100";
  
    // Number of Iterations
    int M = 3;
  
    // Function Call
    findString(str, M);
  }
}
 
// This code is contributed by divyesh072019.

Javascript




<script>
// Javascript program for the above approach
 
// Function to find the modified
// binary let after M iterations
function findlet(str, M)
{
    let N = str.length;
 
    // Set the value of M to the minimum
    // of N or M.
    M = Math.min(M, N);
 
    // Declaration of current let state
    let s1 = "";
 
    // Loop over M iterations
    while (M != 0) {
 
        // Set the current state as null
        // before each iteration
        s1 = "";
 
        for (let i = 0; i < N; i++) {
 
            if (str[i] == '0') {
 
                // Check if this zero has exactly
                // one 1 as neighbour
                if ((str[i - 1] == '1'
                     && str[i + 1] != '1')
                    || (str[i - 1] != '1'
                        && str[i + 1] == '1'))
 
                    // Flip the zero
                    s1 += '1';
 
                else
                    s1 += '0';
            }
            else
                s1 += '1';
        }
 
        // If there is no change,
        // then no need for
        // further iterations.
        if (str == s1)
            break;
 
        // Set the current state
        // as the new previous state
        str = s1;
        M--;
    }
 
    document.write(s1);
}
 
 
// Driver Code
 
     // Given let
    let str = "0110100";
 
    // Number of Iterations
    let M = 3;
 
    // Function Call
    findlet(str, M);
 
// This code is contributed by splevel62.
</script>
Output
1110111

Time Complexity: O(min(M, N)*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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :