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
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Minimum substring flips required to convert given binary string to another
Next article icon

Minimum substring flips required to convert a Binary String to another

Last Updated : 01 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = "110111"
Output: 2
Explanation:
Initially string S1 = "100001".
Reversal 1: Reverse the substring S1[1, 1], then the string S1 becomes "110001".
Reversal 2: Reverse the substring S1[3, 4], then the string S1 becomes "110111".
After the above reversals, the string S1 and S2 are equal.
Therefore, the count of reversals is 2.

Input: S1 = 101, S2 = 10
Output: -1

Approach: Follow the below steps to solve this problem:

  • Initialize a variable, say answer, to store the resultant count of reversal required.
  • If the length of the given strings S1 and S2 are not the same, then print "-1".
  • Iterate over the range [0, N - 1] and perform the following steps:
    • If S1[i] and S2[i] are not the same, then iterate till S1[i] and S2[i] are the same. Increment the answer by 1 as the current substring needs to be flipped.
    • Otherwise, continue to the next iteration.
  • After completing the above steps, print the value of the answer as the resultant flipping of substrings required.

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 the minimum number // of reversals required to make the // given binary strings s1 and s2 same int canMakeSame(string s1, string s2) {     // Stores the minimum count of     // reversal of substrings required     int ans = 0;      // If the length of the strings     // are not the same then return -1     if (s1.size() != s2.size()) {         return -1;     }      int N = s1.length();      // Iterate over each character     for (int i = 0; i < N; i++) {          // If s1[i] is not         // equal to s2[i]         if (s1[i] != s2[i]) {              // Iterate until s1[i] != s2[i]             while (i < s1.length()                    && s1[i] != s2[i]) {                 i++;             }              // Increment answer by 1             ans++;         }     }      // Return the resultant count of     // reversal of substring required     return ans; }  // Driver Code int main() {     string S1 = "100001";     string S2 = "110111";      // Function Call     cout << canMakeSame(S1, S2);      return 0; } 
Java
// Java program for the above approach import java.io.*; class GFG  {    // Function to count the minimum number   // of reversals required to make the   // given binary strings s1 and s2 same   static int canMakeSame(String s1, String s2)   {      // Stores the minimum count of     // reversal of substrings required     int ans = 0;      // If the length of the strings     // are not the same then return -1     if (s1.length() != s2.length()) {       return -1;     }      int N = s1.length();      // Iterate over each character     for (int i = 0; i < N; i++)     {        // If s1[i] is not       // equal to s2[i]       if (s1.charAt(i) != s2.charAt(i))        {          // Iterate until s1[i] != s2[i]         while (i < s1.length()                && s1.charAt(i) != s2.charAt(i))          {           i++;         }          // Increment answer by 1         ans++;       }     }      // Return the resultant count of     // reversal of substring required     return ans;   }    // Driver Code   public static void main(String[] args)   {     String S1 = "100001";     String S2 = "110111";      // Function Call     System.out.println(canMakeSame(S1, S2));   } }  // This code is contributed by Dharanendra L V 
Python3
# Python3 program for the above approach  # Function to count the minimum number # of reversals required to make the # given binary strings s1 and s2 same def canMakeSame(s1, s2) :          # Stores the minimum count of     # reversal of substrings required     ans = -1      # If the length of the strings     # are not the same then return -1     if (len(s1) != len(s2)) :         return -1     N = len(s1)      # Iterate over each character     for i in range(0, N):          # If s1[i] is not         # equal to s2[i]         if (s1[i] != s2[i]) :              # Iterate until s1[i] != s2[i]             while (i < len(s1)                 and s1[i] != s2[i]) :                 i += 1                          # Increment answer by 1             ans += 1          # Return the resultant count of     # reversal of subrequired     return ans  # Driver Code  S1 = "100001" S2 = "110111"  # Function Call print(canMakeSame(S1, S2))  # This code is contributed by code_hunt. 
C#
// C# program for the above approach using System;  class GFG{    // Function to count the minimum number   // of reversals required to make the   // given binary strings s1 and s2 same   static int canMakeSame(string s1, string s2)   {      // Stores the minimum count of     // reversal of substrings required     int ans = 0;      // If the length of the strings     // are not the same then return -1     if (s1.Length != s2.Length) {       return -1;     }      int N = s1.Length;      // Iterate over each character     for (int i = 0; i < N; i++)     {        // If s1[i] is not       // equal to s2[i]       if (s1[i] != s2[i])        {          // Iterate until s1[i] != s2[i]         while (i < s1.Length                && s1[i] != s2[i])          {           i++;         }          // Increment answer by 1         ans++;       }     }      // Return the resultant count of     // reversal of substring required     return ans;   }  // Driver Code public static void Main(string[] args) {     string S1 = "100001";     string S2 = "110111";      // Function Call     Console.Write(canMakeSame(S1, S2)); } }  // This code is contributed by susmitakundugoaldanga. 
JavaScript
<script>  // JavaScript program for the above approach  // Function to count the minimum number // of reversals required to make the // given binary strings s1 and s2 same function canMakeSame(s1, s2) {     // Stores the minimum count of     // reversal of substrings required     var ans = 0;      // If the length of the strings     // are not the same then return -1     if (s1.length != s2.length) {         return -1;     }      var N = s1.length;      // Iterate over each character     for (var i = 0; i < N; i++) {          // If s1[i] is not         // equal to s2[i]         if (s1[i] != s2[i]) {              // Iterate until s1[i] != s2[i]             while (i < s1.length                    && s1[i] != s2[i]) {                 i++;             }              // Increment answer by 1             ans++;         }     }      // Return the resultant count of     // reversal of substring required     return ans; }  // Driver Code var S1 = "100001"; var S2 = "110111";  // Function Call document.write( canMakeSame(S1, S2));  </script>   

Output: 
2

 

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


Next Article
Minimum substring flips required to convert given binary string to another
author
sagnikmukherjee2
Improve
Article Tags :
  • Misc
  • Strings
  • Mathematical
  • DSA
  • binary-string
  • substring
Practice Tags :
  • Mathematical
  • Misc
  • Strings

Similar Reads

  • 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 prefixes required to be flipped to convert a Binary String to another
    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 prefi
    9 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 flips required in a binary string such that all K-size substring contains 1
    Given a binary string str of size N and a positive integer K, the task is to find the minimum number of flips required to make all substring of size K contain at least one '1'.Examples: Input: str = "0001", K = 2 Output: 1 Explanation: Flipping the bit at index 1 modifies str to "0101". All substrin
    11 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 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
  • Minimum substring reversals required to make given Binary String alternating
    Given a binary string S of length N, the task is to count the minimum number substrings of S that is required to be reversed to make the string S alternating. If it is not possible to make string alternating, then print "-1". Examples: Input: S = "10001110"Output: 2Explanation:In the first operation
    7 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 flips or swapping of adjacent characters required to make a string equal to another
    Given two binary strings A and B of length N, the task is to convert the string A to B by either flipping any character of A or swapping adjacent characters of A minimum number of times. If it is not possible to make both the strings equal, print -1. Examples: Input: A = "10010010", B = "00001000" O
    6 min read
  • Minimum swaps required to make a binary string alternating
    You are given a binary string of even length (2N) and an equal number of 0's (N) and 1's (N). What is the minimum number of swaps to make the string alternating? A binary string is alternating if no two consecutive elements are equal. Examples: Input : 000111Output : 1Explanation : Swap index 2 and
    11 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