Convert given Binary String to Another in Minimum Operations by Flipping all Bits Except any 1


In this problem, we need to convert one binary string to another binary string by flipping the characters of the string. We can hold any set bit and flip other bits, and we need to count the total operation to achieve another string by doing it.

We can solve the problem based on the total number of ‘01’ and ‘10’ pairs in the given strings.

Problem statement − We have given two strings named str1 and str2 of the same length containing ‘0’ and ‘1’ characters, representing the binary string. We need to convert the string str1 to str2 by performing the below operations.

  • We can choose any set bit and flip all other bits. Flipping the bits means converting ‘0’ to ‘1’ and ‘1’ to ‘0’.

  • If it is not possible to convert str1 to str2, print −1.

Sample examples

Input

str1 = "001001111", str2 = "011111000";

Output

3

Explanation

  • In the first operation, we keep ‘1’ of the 2nd index as it is and flip all other characters in str1. So, str1 will be 111110000.

  • In the second operation, we keep ‘1’ of the 0th index as it is and flip all other characters. So, str1 will be 100001111.

  • In the last operation, we hold the ‘1’ at the 5th index. So, str1 will become 011111000.

Input

 str1 = "0000", str2 = "1111";

Output

-1

Explanation − It is not possible to convert str1 to str2 as str1 doesn’t contain any ‘1’ character to hold.

Input

 str1 = "0111", str2 = "1000";

Output

-1

Explanation − It is not possible to convert str1 to str2.

Approach 1

We can solve the problem by observation. The observation is that we can get the same string when we hold any single set bit and perform 2 operations. So, we need to choose the different indexes of 1’s to make changes in the string.

Also, we need to perform 2 operations to convert 01 pair to 10. For example, hold the ‘1’ in ‘01’. So, we get ‘11’. After that, hold the ‘1’ at the 0th index in ‘11’ so we will get ‘10’.

To get the answer, the pair of 01 ( 0 −> str1, 1 −> str2) and 10 ( 1 −> str1, 0 −> str2) should be the same. Otherwise, we can say that answer doesn’t exist.

Our main goal is to minimize the ‘01’ and ‘10’ pairs as we can convert ‘01’ to ‘10’ in 2 operations.

Algorithm

Step 1 − Define the totalOperatrions() function to count the number of operations required to convert str1 to str2.

Step 1.2 − Initialize the count10 and count01 variables to store the ‘01’ and ‘10’ pairs in strings.

Step 1.3 − Traverse the string and count 01 and 10 pairs in both strings.

Step 1.4 − If count10 and count01 are the same, return 2*count10. Else return −1.

Step 2 − Define the minimumOperations() function to count the minimum operations required to convert str1 to str2.

Step 3 − Initialize the ‘ans’ with maximum value.

Step 4 − Invoke the totalOperations() function with the original string, and store the result in the ‘operation1’ variable. If the returned value does not equal −1, store the minimum value in the ans from ans and operation1.

Step 5 − Now, we will modify the string to minimize the pairs of 01 and 10. So, Define the stringModification() function.

Step 5.1 − In the function, we find the first pair ‘1ch’ in the strings, and ‘ch’ is passed as a parameter which can be ‘0’ or ‘1’. So, the pair should be like 1 −> str1 and ch −> str.

Step 5.2 − If the ‘1ch’ pair is not found, return false.

Step 5.3 − If the ‘1ch’ pair is found, keep the pairs as it is and flip the other characters of str1.

Step 6 − Execute the stringModification function to keep the ‘11’ pair as it is and flip other characters. After that, call the totalOperations() function again to find the operations required to convert str1 to str2.

Step 7 − If operation2 is not equal to the −1, store the minimum value in ‘ans’ from ‘ans’ or ‘1 + operation2’. Here, we added the 1 because we have modified the string using one operation.

Step 8 − Modify the string by keeping the first ‘10’ pair as it is, and count operations. Again assign minimum value to ‘ans’.

Step 9 − Return −1 if ‘ans’ equals INT_MAX. Otherwise, return ans.

Example

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

// counting 01 and 10 pairs
int totalOperations(string str1, string str2) {
    int len = str1.size();
    int count10 = 0, count01 = 0;
    for (int p = 0; p < len; p++) {
        // If characters at p index are not same
        if (str1[p] != str2[p]) {
            // Increase count01 if 0(str1)-1(str2), else count10 if 1(str1)-0(str2)
            if (str1[p] == '0')
                count01++;
            else
                count10++;
        }
    }
    // If we have euqal number of 01 and 10 pairs, we need 2 operations to flip one pair.
    if (count01 == count10)
        return 2 * count01;
    return -1;
}
bool StringModification(string &temp1, string &temp2, char ch) {
    int len = temp1.size();
    int index = -1;
    // Find the pair of 1c character. (1 -> temp1, c -> temp2)
    for (int p = 0; p < len; p++) {
        if (temp1[p] == '1' && temp2[p] == ch) {
            index = p;
            break;
        }
    }
    // return 0 if pair is not found
    if (index == -1)
        return false;
    // Flip other characters in both strings
    for (int p = 0; p < len; p++) {
        if (p != index) {
            if (temp1[p] == '1')
                temp1[p] = '0';
            else
                temp1[p] = '1';
        }
    }
    return true;
}
// finding minimum operations
int minimumOperations(string str1, string str2) {
    int ans = INT_MAX;
    // first case with initial strings
    int operation1 = totalOperations(str1, str2);
    if (operation1 != -1)
        ans = min(ans, operation1);
    string temp1 = str1, temp2 = str2;
    // Case 2, modification for 11 pair
    if (StringModification(temp1, temp2, '1')) {
        // get operations after modification
        int operation2 = totalOperations(temp1, temp2);
        // adding 1 to operation2 as we have done one modification initially
        if (operation2 != -1)
            ans = min(ans, 1 + operation2);
    }
    // Case 3 modification for 10 pair
    temp1 = str1, temp2 = str2;
    if (StringModification(temp1, temp2, '0')) {
        int operation3 = totalOperations(temp1, temp2);
        if (operation3 != -1)
            ans = min(ans, 1 + operation3);
    }
    if (ans == INT_MAX)
        return -1;
    else
        return ans;
}
int main() {
    string str1 = "001001111";
    string str2 = "011111000";
    int ans = minimumOperations(str1, str2);
    if (ans == -1){
        cout << "S1 to S2 conversion is not possible";
    }
    else{
        cout << "Minimum number of operations required are: " << ans << "\n";
    }
    return 0;
}

Output

Minimum number of operations required are: 3

Time complexity− O(N), as we traverse the string in the stringModification() and totalOperations() function.

Space complexity − O(1), as we modify the same string without using any extra space.

In the code, our main purpose is to decrease the number of pairs of 01 and 10 in the given string after modifying the string to minimize the operations. Programmers can use various inputs and try to understand the answer.

Updated on: 14-Aug-2023

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements