Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Minimum operations required to convert a binary string to all 0s or all 1s
Next article icon

Minimum prefixes required to be flipped to convert a Binary String to another

Last Updated : 28 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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> 

Output: 
2 3 2

 

Time Complexity: O(N)
Auxiliary Space: O(N)  


 


Next Article
Minimum operations required to convert a binary string to all 0s or all 1s

P

pawanharwani11
Improve
Article Tags :
  • Strings
  • DSA
  • binary-string
  • prefix
Practice Tags :
  • Strings

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences