Minimum prefixes required to be flipped to convert a Binary String to another
Last Updated :
28 May, 2021
Given two binary strings A and B of length N, the task is to convert the string from A to string B by repeatedly flipping all the bits of a prefix of A, i.e. convert all the 0s in the prefix to 1s and vice-versa and print the minimum number of prefix flips required and the length of respective prefixes.
Examples:
Input: A = “001”, B = “000”
Output:
2
3 2
Explanation:
Flipping the prefix “001” modifies the string to “110”.
Flipping the prefix “11” modifies the string to “000”.
Input: A = “1000”, B = “1011”
Output:
2
4 2
Explanation:
Flipping the prefix “1000” modifies the string to “0111”.
Flipping the prefix “01” modifies the string to “1011”.
Naive Approach: The simplest approach is to traverse the string A in reverse and for every ith character obtained such that A[i] is not equal to B[i], flip the characters present in A from indices [0, i] and increment the number of operations by 1. After complete traversal of the string, print the count of operations and the prefix length chosen in each operation.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The idea is to fix one bit at a time by traversing the string A in reverse. Maintain a boolean variable, say invert, initially set to false, to denote whether the current bits in A are flipped or not. While traversing, perform the following:
- If the iáµ—Ê° bit in A is not equal to the iáµ—Ê° bit in B and invert is false, then increment the count of operations and set invert to true.
- Otherwise, if the iáµ—Ê° bit in A is equal to the iáµ—Ê° bit in B and invert is true, then increment the count of operations and set invert to false.
Follow the steps below to solve the problem:
- Initialize a boolean variable, say invert as false, to denote whether the bits in A are flipped or not.
- Initialize an empty array, say res, to store the prefix length in each operation.
- Iterate in the range [N – 1, 0] using the variable i and perform the following steps:
- If A[i] != B[i] and invert is false, then the current bit is required to be flipped. Therefore. insert (i + 1) into the array res and update invert to true.
- Otherwise, check if A[i] == B[i] and invert is true, then insert (i + 1) to res, and update invert to false.
- Print the size of the array res as the number of operations required to make the two strings equal.
- Then, print the values stored in res to denote the prefix length in each operation.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findOperations(string A,
string B, int N)
{
int operations = 0;
vector< int > ops;
bool invert = false ;
for ( int i = N - 1; i >= 0; i--) {
if (A[i] != B[i]) {
if (!invert) {
operations++;
ops.push_back(i + 1);
invert = true ;
}
}
else {
if (invert) {
operations++;
ops.push_back(i + 1);
invert = false ;
}
}
}
cout << operations << endl;
if (operations != 0) {
for ( auto x : ops)
cout << x << " " ;
}
}
int main()
{
string A = "001" , B = "000" ;
int N = A.size();
findOperations(A, B, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void findOperations(String A,
String B, int N)
{
int operations = 0 ;
Vector<Integer> ops = new Vector<>();
boolean invert = false ;
for ( int i = N - 1 ; i >= 0 ; i--) {
if (A.charAt(i) != B.charAt(i)) {
if (!invert) {
operations++;
ops.add(i + 1 );
invert = true ;
}
}
else {
if (invert) {
operations++;
ops.add(i + 1 );
invert = false ;
}
}
}
System.out.print(operations + "\n" );
if (operations != 0 ) {
for ( int x : ops)
System.out.print(x+ " " );
}
}
public static void main(String[] args)
{
String A = "001" , B = "000" ;
int N = A.length();
findOperations(A, B, N);
}
}
|
Python3
def findOperations(A, B, N):
operations = 0
ops = []
invert = False
for i in range (N - 1 , - 1 , - 1 ):
if (A[i] ! = B[i]):
if ( not invert):
operations + = 1
ops.append(i + 1 )
invert = True
else :
if (invert):
operations + = 1
ops.append(i + 1 )
invert = False
print (operations)
if (operations ! = 0 ):
for x in ops:
print (x, end = " " )
if __name__ = = '__main__' :
A, B = "001" , "000"
N = len (A)
findOperations(A, B, N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void findOperations(String A,
String B, int N)
{
int operations = 0;
List< int > ops = new List< int >();
bool invert = false ;
for ( int i = N - 1; i >= 0; i--)
{
if (A[i] != B[i])
{
if (!invert)
{
operations++;
ops.Add(i + 1);
invert = true ;
}
}
else
{
if (invert)
{
operations++;
ops.Add(i + 1);
invert = false ;
}
}
}
Console.Write(operations + "\n" );
if (operations != 0)
{
foreach ( int x in ops)
Console.Write(x + " " );
}
}
public static void Main(String[] args)
{
String A = "001" , B = "000" ;
int N = A.Length;
findOperations(A, B, N);
}
}
|
Javascript
<script>
function findOperations(A, B, N) {
var operations = 0;
var ops = [];
var invert = false ;
for ( var i = N - 1; i >= 0; i--) {
if (A[i] !== B[i]) {
if (!invert) {
operations++;
ops.push(i + 1);
invert = true ;
}
} else {
if (invert) {
operations++;
ops.push(i + 1);
invert = false ;
}
}
}
document.write(operations + "<br>" );
if (operations !== 0) {
for (const x of ops) {
document.write(x + " " );
}
}
}
var A = "001" ,
B = "000" ;
var N = A.length;
findOperations(A, B, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...