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 Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Minimum swaps required to make a binary string alternating
Next article icon

Minimum swaps required to convert one binary string to another

Last Updated : 28 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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", str2 = "0001101" Output: 3

Approach:

Initialize the counter and Iterate over the M such that if any non-equal elements found in both binary strings, increment the counter. In the end, if the counter is even then print the result/2 because for one swap two elements are non-identical. 

Suppose S1 = “10” and S2 = “01”, so two pairs are non-identical, the count = 2 and as the count is even, so number of swaps are count/2, i.e. 1. Even count determines that there are chances to swap the elements.

Below is the implementation of the above approach: 

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Method to count swaps
void minSwaps(string str1, string str2)
{
    // Initialize the count
    int count = 0;
 
    // Iterate the loop with str1 length
    for (int i = 0; i < str1.length(); i++) {
 
        // If any non-equal elements are found
        // increment the counter
        if (str1[i] != str2[i])
            count++;
    }
 
    // If counter is even print the swap
    if (count % 2 == 0)
        cout << count / 2;
    else
        cout << "Not Possible";
}
 
// Driver code
int main()
{
    // Take two input
    string binaryString1 = "1110000";
    string binaryString2 = "0001101";
 
    // Call the method
    minSwaps(binaryString1, binaryString2);
 
    return 0;
}
 
 

Java




// Java Program to count minimum number of swap
// required to make string N to M
public class GFG {
 
    // Method to count swaps
    static void minSwaps(String str1, String str2)
    {
        // Initialize the count
        int count = 0;
 
        // Iterate the loop with str1 length
        for (int i = 0; i < str1.length(); i++) {
 
            // If any non-equal elements are found
            // increment the counter
            if (str1.charAt(i) != str2.charAt(i))
                count++;
        }
 
        // If counter is even print the swap
        if (count % 2 == 0)
            System.out.println(count / 2);
        else
            System.out.println("Not Possible");
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Take two input
        String binaryString1 = "1110000";
        String binaryString2 = "0001101";
 
        // Call the method
        minSwaps(binaryString1, binaryString2);
    }
}
 
 

Python 3




# Python3 implementation of
# the above approach
 
# function to count swaps
def minSwaps(str1, str2) :
 
    # Initialize the count
    count = 0
 
    # Iterate the loop with
    # length of str1
    for i in range(len(str1)) :
 
        # If any non-equal elements are
        # found increment the counter
        if str1[i] != str2[i] :
            count += 1
 
    # If counter is even print
    # the swap
    if count % 2 == 0 :
        print(count // 2)
    else :
        print("Not Possible")
 
 
# Driver code
if __name__ == "__main__" :
 
    # Take two input
    binaryString1 = "1110000"
    binaryString2 = "0001101"
 
    # Call the function
    minSwaps( binaryString1, binaryString2)
 
# This code is contributed by ANKITRAI1
 
 

C#




// C# Program to count minimum number of swap
// required to make string N to M
using System;
class GFG
{
 
// Method to count swaps
static void minSwaps(string str1, string str2)
{
    // Initialize the count
    int count = 0;
 
    // Iterate the loop with str1 length
    for (int i = 0; i < str1.Length; i++) {
 
        // If any non-equal elements are found
        // increment the counter
        if (str1[i] != str2[i])
            count++;
    }
 
    // If counter is even print the swap
    if (count % 2 == 0)
        Console.WriteLine(count / 2);
    else
        Console.WriteLine("Not Possible");
}
 
// Driver Code
public static void Main()
{
    // Take two input
    string binaryString1 = "1110000";
    string binaryString2 = "0001101";
 
    // Call the method
    minSwaps(binaryString1, binaryString2);
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)
 
 

PHP




<?php
// PHP implementation of the above
// approach
 
// Method to count swaps
function minSwaps($str1, $str2)
{
    // Initialize the count
    $count = 0;
     
    // Iterate the loop with str1 length
    for ($i = 0; $i < strlen($str1); $i++)
    {
 
        // If any non-equal elements are
        // found increment the counter
        if ($str1[$i] != $str2[$i])
            $count++;
    }
 
    // If counter is even print the swap
    if ($count % 2 == 0)
        echo ($count / 2);
    else
        echo "Not Possible";
}
 
// Driver code
 
// Take two input
$binaryString1 = "1110000";
$binaryString2 = "0001101";
 
// Call the method
minSwaps($binaryString1, $binaryString2);
 
// This code is contributed
// by Sach_Code
?>
 
 

Javascript




<script>
      // JavaScript Program to count minimum number of swap
      // required to make string N to M
      // Method to count swaps
      function minSwaps(str1, str2) {
        // Initialize the count
        var count = 0;
 
        // Iterate the loop with str1 length
        for (var i = 0; i < str1.length; i++) {
          // If any non-equal elements are found
          // increment the counter
          if (str1[i] !== str2[i]) count++;
        }
 
        // If counter is even print the swap
        if (count % 2 === 0) document.write(count / 2);
        else document.write("Not Possible");
      }
 
      // Driver Code
      // Take two input
      var binaryString1 = "1110000";
      var binaryString2 = "0001101";
 
      // Call the method
      minSwaps(binaryString1, binaryString2);
    </script>
 
 
Output
3

Time Complexity: O(n)

Auxiliary Space: O(1) it is using constant space for variables



Next Article
Minimum swaps required to make a binary string alternating
author
bilal-hungund
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Strings
  • Technical Scripter
  • binary-string
Practice Tags :
  • Bit Magic
  • 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 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 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
  • Minimum adjacent swaps required to make a binary string alternating
    Given a binary string S of size N, the task is to find the number of minimum adjacent swaps required to make the string alternate. If it is not possible to do so, then print -1. Examples: Input: S = "10011"Output: 1Explanation:Swap index 2 and index 3 and the string becomes 10101 . Input: S = "11010
    11 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 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 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 operations to convert String A to String B
    Given two strings consisting of lowercase alphabets A and B, both of the same length. Each character of both the strings is either a lowercase letter or a question mark '?'. The task is to find the minimum number of operations required to convert A to B, in one operation you can choose an index i, i
    12 min read
  • Minimum operations require to balance Binary String
    Given a binary string S of length N, the task is to find the minimum number of operations required to balance (equal number of '0' and '1') the given binary string, you can perform two types of operations one at a time, which is given below. Remove a character from the front of the given string.Remo
    7 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