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++ // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to count flips required // to make strings A and B equal void findOperations(string A, string B, int N) { // Stores the count of the // number of operations int operations = 0; // Stores the length of // the chosen prefixes vector<int> ops; // Stores if operations are // performed even or odd times bool invert = false; // Traverse the given string for (int i = N - 1; i >= 0; i--) { // If current characters in // the two strings are unequal if (A[i] != B[i]) { // If A[i] is not flipped if (!invert) { // Increment count // of operations operations++; // Insert the length of // the chosen prefix ops.push_back(i + 1); // Update invert to true invert = true; } } else { // If A[i] is flipped if (invert) { // Increment count // of operations operations++; // Insert length of // the chosen prefix ops.push_back(i + 1); // Update invert to false invert = false; } } } // Print the number of // operations required cout << operations << endl; // Print the chosen prefix // length in each operation if (operations != 0) { for (auto x : ops) cout << x << " "; } } // Driver Code int main() { // Given binary strings string A = "001", B = "000"; int N = A.size(); findOperations(A, B, N); return 0; }
Java // Java program for the above approach import java.util.*; class GFG{ // Function to count flips required // to make Strings A and B equal static void findOperations(String A, String B, int N) { // Stores the count of the // number of operations int operations = 0; // Stores the length of // the chosen prefixes Vector<Integer> ops = new Vector<>(); // Stores if operations are // performed even or odd times boolean invert = false; // Traverse the given String for (int i = N - 1; i >= 0; i--) { // If current characters in // the two Strings are unequal if (A.charAt(i) != B.charAt(i)) { // If A[i] is not flipped if (!invert) { // Increment count // of operations operations++; // Insert the length of // the chosen prefix ops.add(i + 1); // Update invert to true invert = true; } } else { // If A[i] is flipped if (invert) { // Increment count // of operations operations++; // Insert length of // the chosen prefix ops.add(i + 1); // Update invert to false invert = false; } } } // Print the number of // operations required System.out.print(operations +"\n"); // Print the chosen prefix // length in each operation if (operations != 0) { for (int x : ops) System.out.print(x+ " "); } } // Driver Code public static void main(String[] args) { // Given binary Strings String A = "001", B = "000"; int N = A.length(); findOperations(A, B, N); } } // This code is contributed by Amit Katiyar
Python3 # Python program for the above approach # Function to count flips required # to make strings A and B equal def findOperations(A, B, N): # Stores the count of the # number of operations operations = 0 # Stores the length of # the chosen prefixes ops = [] # Stores if operations are # performed even or odd times invert = False # Traverse the given string for i in range(N - 1, -1, -1): # If current characters in # the two strings are unequal if (A[i] != B[i]): # If A[i] is not flipped if (not invert): # Increment count # of operations operations += 1 # Insert the length of # the chosen prefix ops.append(i + 1) # Update invert to true invert = True else: # If A[i] is flipped if (invert): # Increment count # of operations operations += 1 # Insert length of # the chosen prefix ops.append(i + 1) # Update invert to false invert = False # Print the number of # operations required print (operations) # Print the chosen prefix # length in each operation if (operations != 0): for x in ops: print(x, end = " ") # Driver Code if __name__ == '__main__': # Given binary strings A, B = "001", "000" N = len(A) findOperations(A, B, N) # This code is contributed by mohit kumar 29.
C# // C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function to count flips required // to make Strings A and B equal static void findOperations(String A, String B, int N) { // Stores the count of the // number of operations int operations = 0; // Stores the length of // the chosen prefixes List<int> ops = new List<int>(); // Stores if operations are // performed even or odd times bool invert = false; // Traverse the given String for(int i = N - 1; i >= 0; i--) { // If current characters in // the two Strings are unequal if (A[i] != B[i]) { // If A[i] is not flipped if (!invert) { // Increment count // of operations operations++; // Insert the length of // the chosen prefix ops.Add(i + 1); // Update invert to true invert = true; } } else { // If A[i] is flipped if (invert) { // Increment count // of operations operations++; // Insert length of // the chosen prefix ops.Add(i + 1); // Update invert to false invert = false; } } } // Print the number of // operations required Console.Write(operations + "\n"); // Print the chosen prefix // length in each operation if (operations != 0) { foreach(int x in ops) Console.Write(x + " "); } } // Driver Code public static void Main(String[] args) { // Given binary Strings String A = "001", B = "000"; int N = A.Length; findOperations(A, B, N); } } // This code is contributed by 29AjayKumar
JavaScript <script> // JavaScript program for the above approach // Function to count flips required // to make Strings A and B equal function findOperations(A, B, N) { // Stores the count of the // number of operations var operations = 0; // Stores the length of // the chosen prefixes var ops = []; // Stores if operations are // performed even or odd times var invert = false; // Traverse the given String for (var i = N - 1; i >= 0; i--) { // If current characters in // the two Strings are unequal if (A[i] !== B[i]) { // If A[i] is not flipped if (!invert) { // Increment count // of operations operations++; // Insert the length of // the chosen prefix ops.push(i + 1); // Update invert to true invert = true; } } else { // If A[i] is flipped if (invert) { // Increment count // of operations operations++; // Insert length of // the chosen prefix ops.push(i + 1); // Update invert to false invert = false; } } } // Print the number of // operations required document.write(operations + "<br>"); // Print the chosen prefix // length in each operation if (operations !== 0) { for (const x of ops) { document.write(x + " "); } } } // Driver Code // Given binary Strings var A = "001", B = "000"; var N = A.length; findOperations(A, B, N); </script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Minimum substring flips required to convert a Binary String to another
Given two binary strings S1 and S2 of size N and M respectively, the task is to find the minimum number of reversal of substrings of equal characters required to convert the string S1 to S2. If it is not possible to convert the string S1 to S2, then print "-1". Examples: Input: S1 = "100001", S2 = "
6 min read
Minimum substring flips required to convert given binary string to another
Given two binary strings A and B, the task is to find the minimum number of times a substring starting from the first character of A needs to be flipped, i.e. convert 1s to 0s and 0s to 1s, to convert A to B. Examples: Input: A = â0010â, B = â1011âOutput; 3Explanation:Step 1: Flip the entire string
7 min read
Minimum swaps required to convert one binary string to another
Given two binary string M and N of equal length, the task is to find a minimum number of operations (swaps) required to convert string N to M. Examples: Input: str1 = "1101", str2 = "1110" Output: 1 Swap last and second last element in the binary string, so that it become 1101 Input: str1 = "1110000
5 min read
Minimum given operations required to convert a given binary string to all 1's
Given a binary number as a string str of length L. The task is to find the minimum number of operations needed so that the number becomes 2L-1, that is a string consisting of only 1's of the length L. In each operation, the number N can be replaced by N xor (N + 1). Examples: Input: str = "10010111"
7 min read
Minimum operations required to convert a binary string to all 0s or all 1s
Given a binary string str, the task is to find the minimum number of operations required to make all the characters of the string same i.e. either the resultant string contains all 0s or all 1s. In a single operation, any block of consecutive 0s can be converted to a block of consecutive 1s of the s
4 min read
Minimum number of given operations required to convert a string to another string
Given two strings S and T of equal length. Both strings contain only the characters '0' and '1'. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S: Swap any two characters of the string.Replace a '0' with a '1' or vice
15 min read
Minimum cost of flipping characters required to convert Binary String to 0s only
Given binary string str, and integers A, which denotes the cost of converting consecutive 1s to 0s, and B, which denotes the cost of converting 0s to 1s. The task is to find the minimum cost to reduce the string str to 0s only. Examples: Input: str = â01101110â, A = 5, B = 1Output: 6Explanation:Conv
8 min read
Minimum Count of Bit flips required to make a Binary String Palindromic
Given an integer N, the task is to find the minimum number of bits required to be flipped to convert the binary representation of N into a palindrome. Examples: Input: N = 12 Output: 2 Explanation: Binary String representing 12 = "1100". To make "1100" a palindrome, convert the string to "0110". The
7 min read
Minimum number of characters to be removed to make a binary string alternate
Given a binary string, the task is to find minimum number of characters to be removed from it so that it becomes alternate. A binary string is alternate if there are no two consecutive 0s or 1s.Examples : Input : s = "000111" Output : 4 We need to delete two 0s and two 1s to make string alternate. I
4 min read
Minimum Subarray flips required to convert all elements of a Binary Array to K
The problem statement is asking for the minimum number of operations required to convert all the elements of a given binary array arr[] to a specified value K, where K can be either 0 or 1. The operations can be performed on any index X of the array, and the operation is to flip all the elements of
8 min read