Convert given Binary String to another in minimum operations by flipping all bits except any 1
Given two binary strings s1 and s2, the task is to count the minimum operations to convert string s1 to s2. In one operation a set bit can be chosen and all other bits except that is flipped. If it is not possible to convert s1-> s2 print -1.
Input: s1 = “100010111” s2 = “101101100”
In the first operation hold 1 at 6 th index and convert remaining to logical NOT: 100010111→011101100 .
In the second operation hold 1 at 1st index and convert remaining to logical NOT: 011101100→110010011.
In the third operation hold 1 at 0th index and convert remaining to logical NOT: 110010011→101101100.
So 3 operations.
Input: s1=”11111″ s2 = “00000”
Approach: It can be seen choosing the same index of 1 after two operations string remains the same as the original. So different index should be chosen for each operation on doing so “10” in string s1 can be converted to a string “01” in string s2 with two operations. So the answer is dependent on minimizing the number of “10” and “01” in strings s1 and s2. If at any index “0(s1) – 1(s2) “ && “1(s1) – 0(s2)” are equal in number then there is an answer else -1.
“01” (on choosing 1 at index1) -> “11”(on choosing 1 at index2) -> “10”
Using this conclusion:
It can be even possible that minimum “0(s1) – 1(s2) ” && “1(s1) – 0(s2)” pairs can be obtained by doing 1 operation initially. In the cases where 1 (s1)-> 1(s2) or 1(s1) -> 0(s2).
Follow these steps to solve this problem:
- Initialize the variable res = INT_MAX
- Initialize the variable ops1= -1 to store the operations required to convert string s1 to s2 without any modification.
- Now check if it is possible to minimize operations by doing 1 initial modification in case of (1(s1)-> 1(s2)).
- Store the operations in ops2 variable and store the minimum in the res by doing min(res,ops2).
- Now check if it is possible to minimize operations by doing 1 initial modification in case of (1(s1)-> 0(s2)).
- Store the operations in ops3 variable and store the minimum in the res by doing min(res,ops3).
- If res is equal to INT_MAX it means it is not possible to convert string s1 -> s2 so print -1.
- Else print the res.
Below is the implementation of the above approach:
Time Complexity: O(N) where N is the length of the string.
Space Complexity: O(N)