Open In App

Check if two binary strings can be made equal by swapping pairs of unequal characters

Improve
Improve
Like Article
Like
Save
Share
Report

Given two binary strings S1 and S2 of length N (1 ? N ? 105), the task is to check if it is possible to convert the string S1 to 
S2 by performing the following operations any number of times:

  1. Select any two indices i and j (1 ? i < j ? N) such that S1[i] is ‘0’ and S1[j] is ‘1’.
  2. Swap S1[i] with S1[j].

Examples:

Input: S1 =”100111″, S2 = “111010” 
Output: YES 
Explanation:Swap S[2] and S[3] with S[4] and S[6] respectively.

Input: S1 = “110100”, S2 = “010101” 
Output: NO

Approach: Follow the steps below to solve the problem:

  1. Check if the number of occurrences of character ‘0’ and ‘1’ in both the strings are equal. If not found to be true, then it is impossible to transform string S1 into S2.
  2. If the number of characters are equal, then we move to the next step. By the given condition it is possible to move the ‘0’ only in forward direction by swapping with letter ‘1’ in string S1.
  3. Hence, iterate characters of both the strings and count the number of occurrences of ‘0’ in both strings. If at any point the count of characters of ‘0’ in string S2 becomes strictly greater than count of occurrences in string S1, terminate the loop and print “NO”.
  4. If both the strings iterated successfully, print “YES”.

Below is the implementation of above approach:

C++




// C++ Program to implement
// of above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a string
// s1 can be converted into s2
void check(string s1, string s2)
{
    // Count of '0' in strings in s1 and s2
    int s1_0 = 0, s2_0 = 0;
 
    // Iterate both the strings and
    // count the number of occurrences of
    for (int i = 0; i < s1.size(); i++) {
 
        if (s1[i] == '0') {
            s1_0++;
        }
 
        if (s2[i] == '0') {
            s2_0++;
        }
    }
 
    // Count is not equal
    if (s1_0 != s2_0) {
        cout << "NO" << endl;
        return;
    }
 
    else {
 
        int Count1 = 0, Count2 = 0;
 
        // Iterating over both the
        // arrays and count the
        // number of occurrences of '0'
        for (int i = 0; i < s1.size(); i++) {
 
            if (s1[i] == '0') {
                Count1++;
            }
 
            if (s2[i] == '0') {
                Count2++;
            }
 
            // If the count of occurrences
            // of '0' in S2 exceeds that in S1
            if (Count1 < Count2) {
                cout << "NO" << endl;
                return;
            }
        }
 
        cout << "YES" << endl;
    }
}
 
// Driver program
int main()
{
 
    string s1 = "100111";
    string s2 = "111010";
    check(s1, s2);
 
    s1 = "110100";
    s2 = "010101";
    check(s1, s2);
 
    return 0;
}


Java




// Java program to implement
// the above approach
import java.util.*;
class GFG
{
  
// Function to check if a string
// s1 can be converted into s2
static void check(String s1, String s2)
{
     
    // Count of '0' in strings in s1 and s2
    int s1_0 = 0, s2_0 = 0;
     
    // Iterate both the strings and
    // count the number of occurrences of
    for(int i = 0; i < s1.length(); i++)
    {
        if (s1.charAt(i) == '0')
        {
            s1_0++;
        }
   
        if (s2.charAt(i) == '0')
        {
            s2_0++;
        }
    }
   
    // Count is not equal
    if (s1_0 != s2_0)
    {
        System.out.println("NO");
        return;
    }
   
    else
    {
        int Count1 = 0, Count2 = 0;
         
        // Iterating over both the
        // arrays and count the
        // number of occurrences of '0'
        for(int i = 0; i < s1.length(); i++)
        {
            if (s1.charAt(i) == '0')
            {
                Count1++;
            }
   
            if (s2.charAt(i) == '0')
            {
                Count2++;
            }
   
            // If the count of occurrences
            // of '0' in S2 exceeds that in S1
            if (Count1 < Count2)
            {
                System.out.println("NO");
                return;
            }
        }
        System.out.println("YES");
    }
}
  
// Driver Code
public static void main(String[] args)
{
    String s1 = "100111";
    String s2 = "111010";    
    check(s1, s2);
    s1 = "110100";
    s2 = "010101";
    check(s1, s2);
}
}
 
// This code is contributed by code_hunt.


Python3




# Python3 program to implement
# of above approach
 
# Function to check if a string
# s1 can be converted into s2
def check(s1, s2):
 
    # Count of '0' in strings in s1 and s2
    s1_0 = 0
    s2_0 = 0
 
    # Iterate both the strings and
    # count the number of occurrences of
    for i in range(len(s1)):
        if (s1[i] == '0'):
            s1_0 += 1
             
        if (s2[i] == '0'):
            s2_0 += 1
 
    # Count is not equal
    if (s1_0 != s2_0):
        print("NO")
        return
 
    else:
        Count1 = 0
        Count2 = 0;
 
        # Iterating over both the
        # arrays and count the
        # number of occurrences of '0'
        for i in range(len(s1)):
            if (s1[i] == '0'):
                Count1 += 1
 
            if (s2[i] == '0'):
                Count2 += 1
 
            # If the count of occurrences
            # of '0' in S2 exceeds that in S1
            if (Count1 < Count2):
                print("NO")
                return
            
        print("YES")
 
# Driver code
if __name__ == "__main__":
 
    s1 = "100111"
    s2 = "111010"
    check(s1, s2)
 
    s1 = "110100"
    s2 = "010101"
    check(s1, s2)
 
# This code is contributed by chitranayal


C#




// C# program to implement
// of above approach
using System;
 
class GFG{
     
// Function to check if a string
// s1 can be converted into s2
static void check(string s1, string s2)
{
     
    // Count of '0' in strings in s1 and s2
    int s1_0 = 0, s2_0 = 0;
     
    // Iterate both the strings and
    // count the number of occurrences of
    for(int i = 0; i < s1.Length; i++)
    {
        if (s1[i] == '0')
        {
            s1_0++;
        }
   
        if (s2[i] == '0')
        {
            s2_0++;
        }
    }
   
    // Count is not equal
    if (s1_0 != s2_0)
    {
        Console.WriteLine("NO");
        return;
    }
   
    else
    {
        int Count1 = 0, Count2 = 0;
         
        // Iterating over both the
        // arrays and count the
        // number of occurrences of '0'
        for(int i = 0; i < s1.Length; i++)
        {
            if (s1[i] == '0')
            {
                Count1++;
            }
   
            if (s2[i] == '0')
            {
                Count2++;
            }
   
            // If the count of occurrences
            // of '0' in S2 exceeds that in S1
            if (Count1 < Count2)
            {
                Console.WriteLine("NO");
                return;
            }
        }
        Console.WriteLine("YES");
    }
}
 
// Driver code
static void Main()
{
    string s1 = "100111";
    string s2 = "111010";
     
    check(s1, s2);
     
    s1 = "110100";
    s2 = "010101";
     
    check(s1, s2);
}
}
 
// This code is contributed by divyesh072019


Javascript




<script>
    // Javascript program to implement of above approach
     
    // Function to check if a string
    // s1 can be converted into s2
    function check(s1, s2)
    {
 
        // Count of '0' in strings in s1 and s2
        let s1_0 = 0, s2_0 = 0;
 
        // Iterate both the strings and
        // count the number of occurrences of
        for(let i = 0; i < s1.length; i++)
        {
            if (s1[i] == '0')
            {
                s1_0++;
            }
 
            if (s2[i] == '0')
            {
                s2_0++;
            }
        }
 
        // Count is not equal
        if (s1_0 != s2_0)
        {
            document.write("NO");
            return;
        }
 
        else
        {
            let Count1 = 0, Count2 = 0;
 
            // Iterating over both the
            // arrays and count the
            // number of occurrences of '0'
            for(let i = 0; i < s1.length; i++)
            {
                if (s1[i] == '0')
                {
                    Count1++;
                }
 
                if (s2[i] == '0')
                {
                    Count2++;
                }
 
                // If the count of occurrences
                // of '0' in S2 exceeds that in S1
                if (Count1 < Count2)
                {
                    document.write("NO" + "</br>");
                    return;
                }
            }
            document.write("YES" + "</br>");
        }
    }
     
    let s1 = "100111";
    let s2 = "111010";
      
    check(s1, s2);
      
    s1 = "110100";
    s2 = "010101";
      
    check(s1, s2);
   
  // This code is contributed by decode 2207.
</script>


Output

YES
NO




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

Approach 2: Dynamic Programming:
Here’s a dynamic programming approach to solve the problem:

  • Create a 2D dynamic programming array dp[n+1][2], where dp[i][0] represents the minimum number of flips required to make the i-th character of string 1 same as the i-th character of string 2, such that both characters are 0, and dp[i][1] represents the minimum number of flips required to make the i-th character of string 1 same as the i-th character of string 2, such that one character is 0 and the other is 1.
  • Initialize dp[0][0] = dp[0][1] = 0.
  • Traverse through the strings s1 and s2 and fill the dp array as follows:
  • If s1[i] and s2[i] are both 0, then dp[i+1][0] = dp[i][0] and dp[i+1][1] = dp[i][1] + 1.
  • If s1[i] and s2[i] are both 1, then dp[i+1][0] = dp[i][0] + 1 and dp[i+1][1] = dp[i][1].
  • If s1[i] is 0 and s2[i] is 1, then dp[i+1][0] = dp[i][1] and dp[i+1][1] = dp[i][0] + 1.
  • If s1[i] is 1 and s2[i] is 0, then dp[i+1][0] = dp[i][0] + 1 and dp[i+1][1] = dp[i][1].
  • Return “YES” if dp[n][0] >= dp[n][1], else return “NO”.

Here’s the C++ code for the same:

C++




#include <bits/stdc++.h>
using namespace std;
 
void check(string s1, string s2)
{
    int n = s1.size();
    int dp[n+1][2];
    memset(dp, 0, sizeof(dp));
 
    for (int i = 0; i < n; i++) {
        if (s1[i] == '0' && s2[i] == '0') {
            dp[i+1][0] = dp[i][0];
            dp[i+1][1] = dp[i][1] + 1;
        } else if (s1[i] == '1' && s2[i] == '1') {
            dp[i+1][0] = dp[i][0] + 1;
            dp[i+1][1] = dp[i][1];
        } else if (s1[i] == '0' && s2[i] == '1') {
            dp[i+1][0] = dp[i][1];
            dp[i+1][1] = dp[i][0] + 1;
        } else {
            dp[i+1][0] = dp[i][0] + 1;
            dp[i+1][1] = dp[i][1];
        }
    }
 
    if (dp[n][0] >= dp[n][1]) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
    }
}
 
int main()
{
    string s1 = "100111";
    string s2 = "111010";
    check(s1, s2);
 
    s1 = "110100";
    s2 = "010101";
    check(s1, s2);
 
    return 0;
}


Java




import java.util.Arrays;
 
// Added by ~Nikunj Sonigara
 
public class Main {
    public static void check(String s1, String s2) {
        int n = s1.length();
        int[][] dp = new int[n + 1][2];
        for (int i = 0; i <= n; i++) {
            Arrays.fill(dp[i], 0);
        }
 
        for (int i = 0; i < n; i++) {
            if (s1.charAt(i) == '0' && s2.charAt(i) == '0') {
                dp[i + 1][0] = dp[i][0];
                dp[i + 1][1] = dp[i][1] + 1;
            } else if (s1.charAt(i) == '1' && s2.charAt(i) == '1') {
                dp[i + 1][0] = dp[i][0] + 1;
                dp[i + 1][1] = dp[i][1];
            } else if (s1.charAt(i) == '0' && s2.charAt(i) == '1') {
                dp[i + 1][0] = dp[i][1];
                dp[i + 1][1] = dp[i][0] + 1;
            } else {
                dp[i + 1][0] = dp[i][0] + 1;
                dp[i + 1][1] = dp[i][1];
            }
        }
 
        if (dp[n][0] >= dp[n][1]) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
    }
 
    public static void main(String[] args) {
        String s1 = "100111";
        String s2 = "111010";
        check(s1, s2);
 
        s1 = "110100";
        s2 = "010101";
        check(s1, s2);
    }
}


Python




# Added by ~Nikunj Sonigara
 
def check(s1, s2):
    n = len(s1)
    dp = [[0, 0] for _ in range(n + 1)]
 
    for i in range(n):
        if s1[i] == '0' and s2[i] == '0':
            dp[i + 1][0] = dp[i][0]
            dp[i + 1][1] = dp[i][1] + 1
        elif s1[i] == '1' and s2[i] == '1':
            dp[i + 1][0] = dp[i][0] + 1
            dp[i + 1][1] = dp[i][1]
        elif s1[i] == '0' and s2[i] == '1':
            dp[i + 1][0] = dp[i][1]
            dp[i + 1][1] = dp[i][0] + 1
        else:
            dp[i + 1][0] = dp[i][0] + 1
            dp[i + 1][1] = dp[i][1]
 
    if dp[n][0] >= dp[n][1]:
        print("YES")
    else:
        print("NO")
 
s1 = "100111"
s2 = "111010"
check(s1, s2)
 
s1 = "110100"
s2 = "010101"
check(s1, s2)


C#




using System;
 
class Program
{
    // Function to compare two strings, s1 and s2
    static void Check(string s1, string s2)
    {
        int n = s1.Length;
        int[,] dp = new int[n + 1, 2]; // Create a 2D array to store dynamic programming values
 
        for (int i = 0; i < n; i++)
        {
            // Check each character of the strings and update the dp array based on the character comparison
            if (s1[i] == '0' && s2[i] == '0')
            {
                dp[i + 1, 0] = dp[i, 0];         // If both characters are '0', update dp values accordingly
                dp[i + 1, 1] = dp[i, 1] + 1;
            }
            else if (s1[i] == '1' && s2[i] == '1')
            {
                dp[i + 1, 0] = dp[i, 0] + 1;     // If both characters are '1', update dp values accordingly
                dp[i + 1, 1] = dp[i, 1];
            }
            else if (s1[i] == '0' && s2[i] == '1')
            {
                dp[i + 1, 0] = dp[i, 1];         // If s1 is '0' and s2 is '1', update dp values accordingly
                dp[i + 1, 1] = dp[i, 0] + 1;
            }
            else
            {
                dp[i + 1, 0] = dp[i, 0] + 1;     // If s1 is '1' and s2 is '0', update dp values accordingly
                dp[i + 1, 1] = dp[i, 1];
            }
        }
 
        // Compare the final values in dp array to determine the result
        if (dp[n, 0] >= dp[n, 1])
        {
            Console.WriteLine("YES"); // If the first category has equal or more '1's, print "YES"
        }
        else
        {
            Console.WriteLine("NO");  // If the second category has more '1's, print "NO"
        }
    }
 
    static void Main()
    {
        string s1 = "100111";
        string s2 = "111010";
        Check(s1, s2);
 
        s1 = "110100";
        s2 = "010101";
        Check(s1, s2);
    }
}


Javascript




function check(s1, s2) {
    let n = s1.length;
    let dp = new Array(n + 1).fill(0).map(() => new Array(2).fill(0));
 
    for (let i = 0; i < n; i++) {
        if (s1[i] == '0' && s2[i] == '0') {
            dp[i + 1][0] = dp[i][0];
            dp[i + 1][1] = dp[i][1] + 1;
        } else if (s1[i] == '1' && s2[i] == '1') {
            dp[i + 1][0] = dp[i][0] + 1;
            dp[i + 1][1] = dp[i][1];
        } else if (s1[i] == '0' && s2[i] == '1') {
            dp[i + 1][0] = dp[i][1];
            dp[i + 1][1] = dp[i][0] + 1;
        } else {
            dp[i + 1][0] = dp[i][0] + 1;
            dp[i + 1][1] = dp[i][1];
        }
    }
 
    if (dp[n][0] >= dp[n][1]) {
        console.log("YES");
    } else {
        console.log("NO");
    }
}
 
let s1 = "100111";
let s2 = "111010";
check(s1, s2);
 
s1 = "110100";
s2 = "010101";
check(s1, s2);


Output

YES
NO




Time Complexity: O(n log n), where n is the length of the input string
Auxiliary Space: O(n), where n is the length of the input string



Last Updated : 17 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads