Given two binary arrays arr1[] and arr2[] of the same size, the task is to make both the arrays equal by swapping pairs of arr1[ ] only if arr1[i] = 0 and arr1[j] = 1 (0 ? i < j < N)). If it is possible to make both the arrays equal, print “Yes”. Otherwise, print “No”.
Examples:
Input: arr1[] = {0, 0, 1, 1}, arr2[] = {1, 1, 0, 0}
Output: Yes
Explanation:
Swap arr1[1] and arr1[3], it becomes arr1[] = {0, 1, 1, 0}.
Swap arr1[0] and arr1[2], it becomes arr1[] = {1, 1, 0, 0}.Input: arr1[] = {1, 0, 1, 0, 1}, arr2[] = {0, 1, 0, 0, 1}
Output: No
Approach: Follow the steps below to solve the problem:
- Initialize two variable, say count and flag (= true).
- Traverse the array and for every array element, perform the following operations:
- If arr1[i] != arr2[i]:
- If arr1[i] == 0, increment count by 1.
- Otherwise, decrement count by 1 and if count < 0, update flag = false.
 
 
- If arr1[i] != arr2[i]:
- If flag is equal to true, print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
C++
| // C++ program for above approach#include <bits/stdc++.h>usingnamespacestd;// Function to check if two arrays// can be made equal or not by swapping// pairs of only one of the arraysvoidcheckArrays(intarr1[], intarr2[], intN){    // Stores elements required    // to be replaced    intcount = 0;    // To check if the arrays    // can be made equal or not    boolflag = true;    // Traverse the array    for(inti = 0; i < N; i++) {        // If array elements are not equal        if(arr1[i] != arr2[i]) {            if(arr1[i] == 0)                // Increment count by 1                count++;            else{                // Decrement count by 1                count--;                if(count < 0) {                    flag = 0;                    break;                }            }        }    }    // If flag is true and count is 0,    // print "Yes". Otherwise "No"    if(flag && count == 0)        cout << "Yes"<< endl;    else        cout << "No"<< endl;}// Driver Codeintmain(){    // Given arrays    intarr1[] = { 0, 0, 1, 1 };    intarr2[] = { 1, 1, 0, 0 };    // Size of the array    intN = sizeof(arr1) / sizeof(arr1[0]);    checkArrays(arr1, arr2, N);    return0;} | 
Java
| // Java program for above approachpublicclassGFG {  // Function to check if two arrays  // can be made equal or not by swapping  // pairs of only one of the arrays  staticvoidcheckArrays(intarr1[], intarr2[], intN)  {    // Stores elements required    // to be replaced    intcount = 0;    // To check if the arrays    // can be made equal or not    booleanflag = true;    // Traverse the array    for(inti = 0; i < N; i++) {      // If array elements are not equal      if(arr1[i] != arr2[i])      {        if(arr1[i] == 0)          // Increment count by 1          count++;        else        {          // Decrement count by 1          count--;          if(count < 0)          {            flag = false;            break;          }        }      }    }    // If flag is true and count is 0,    // print "Yes". Otherwise "No"    if((flag && (count == 0)) == true)      System.out.println("Yes");    else      System.out.println("No");  }  // Driver Code  publicstaticvoidmain (String[] args)  {    // Given arrays    intarr1[] = { 0, 0, 1, 1};    intarr2[] = { 1, 1, 0, 0};    // Size of the array    intN = arr1.length;       checkArrays(arr1, arr2, N);  }}// This code is contributed by AnkThon | 
Python3
| # Python3 program for above approach# Function to check if two arrays# can be made equal or not by swapping# pairs of only one of the arraysdefcheckArrays(arr1, arr2, N):      # Stores elements required    # to be replaced    count =0    # To check if the arrays    # can be made equal or not    flag =True    # Traverse the array    fori inrange(N):        # If array elements are not equal        if(arr1[i] !=arr2[i]):            if(arr1[i] ==0):                # Increment count by 1                count +=1            else:                # Decrement count by 1                count -=1                if(count < 0):                    flag =0                    break    # If flag is true and count is 0,    # pr"Yes". Otherwise "No"    if(flag andcount ==0):        print("Yes")    else:        print("No")# Driver Codeif__name__ =='__main__':        # Given arrays    arr1 =[0, 0, 1, 1]    arr2 =[1, 1, 0, 0]    # Size of the array    N =len(arr1)    checkArrays(arr1, arr2, N)    # This code is contributed by mohit kumar 29. | 
C#
| // C# program for the above approachusingSystem;classGFG{// Function to check if two arrays  // can be made equal or not by swapping  // pairs of only one of the arrays  staticvoidcheckArrays(int[] arr1, int[] arr2, intN)  {    // Stores elements required    // to be replaced    intcount = 0;    // To check if the arrays    // can be made equal or not    boolflag = true;    // Traverse the array    for(inti = 0; i < N; i++) {      // If array elements are not equal      if(arr1[i] != arr2[i])      {        if(arr1[i] == 0)          // Increment count by 1          count++;        else        {          // Decrement count by 1          count--;          if(count < 0)          {            flag = false;            break;          }        }      }    }    // If flag is true and count is 0,    // print "Yes". Otherwise "No"    if((flag && (count == 0)) == true)      Console.WriteLine("Yes");    else      Console.WriteLine("No");  }// Driver CodestaticpublicvoidMain(){    // Given arrays    int[] arr1 = { 0, 0, 1, 1 };    int[] arr2 = { 1, 1, 0, 0 };    // Size of the array    intN = arr1.Length;       checkArrays(arr1, arr2, N);}}// This code is contributed by susmitakundugoaldanga. | 
Javascript
| <script>// Java script program for above approach// Function to check if two arrays// can be made equal or not by swapping// pairs of only one of the arraysfunctioncheckArrays(arr1,arr2,N){    // Stores elements required    // to be replaced    let count = 0;    // To check if the arrays    // can be made equal or not    let flag = true;    // Traverse the array    for(let i = 0; i < N; i++) {    // If array elements are not equal    if(arr1[i] != arr2[i])    {        if(arr1[i] == 0)        // Increment count by 1        count++;        else        {        // Decrement count by 1        count--;        if(count < 0)        {            flag = false;            break;        }        }    }    }    // If flag is true and count is 0,    // print "Yes". Otherwise "No"    if((flag && (count == 0)) == true)    document.write("Yes");    else    document.write("No");}// Driver Code    // Given arrays    let arr1 = [ 0, 0, 1, 1 ];    let arr2 = [ 1, 1, 0, 0 ];    // Size of the array    let N = arr1.length;    checkArrays(arr1, arr2, N);// This code is contributed by Gottumukkala Sravan Kumar (171fa07058)</script> | 
Yes
Time Complexity: O(N)
Auxiliary Space: O(1) 
Another Approach:
- Define two binary arrays arr1[] and arr2[] of the same size.
- Calculate the size of the arrays using the sizeof() operator and store it in the variable n.
- Initialize three integer variables zero_count, one_count, and mismatch_count to zero.
- Use a for loop to iterate through the arrays from 0 to n-1.
- Inside the for loop, check if the current element of arr1 is zero. If yes, increment the zero_count variable. Otherwise, increment the one_count variable.
- Also inside the for loop, check if the current element of arr1 is not equal to the current element of arr2. If yes, increment the mismatch_count variable.
- After the for loop, check if the zero_count and one_count variables are equal and the mismatch_count variable is even. If yes, print “Yes”. Otherwise, print “No”.
- End the program.
Below is the implementation of the above approach:
C++
| #include <iostream>usingnamespacestd;intmain() {    intarr1[] = {0, 0, 1, 1};    intarr2[] = {1, 1, 0, 0};    intn = sizeof(arr1) / sizeof(arr1[0]); // calculate size of arrays    intzero_count = 0, one_count = 0, mismatch_count = 0;    for(inti = 0; i < n; i++) {        if(arr1[i] == 0) {            zero_count++; // count the number of zeros in arr1        } else{            one_count++; // count the number of ones in arr1        }        if(arr1[i] != arr2[i]) {            mismatch_count++; // count the number of mismatches between arr1 and arr2        }    }    if(zero_count == one_count && mismatch_count % 2 == 0) {        cout << "Yes"; // if the number of zeros and ones in arr1 are equal and the number of mismatches is even, we can make both arrays equal by swapping pairs of arr1    } else{        cout << "No"; // otherwise, we cannot make both arrays equal by swapping pairs of arr1    }    return0;}// This code is contributed by rudra1807raj | 
Java
| publicclassMain {    publicstaticvoidmain(String[] args) {        int[] arr1 = {0, 0, 1, 1};        int[] arr2 = {1, 1, 0, 0};        intn = arr1.length; // Calculate the size of arrays        intzeroCount = 0, oneCount = 0, mismatchCount = 0;        for(inti = 0; i < n; i++) {            if(arr1[i] == 0) {                zeroCount++; // Count the number of zeros in arr1            } else{                oneCount++; // Count the number of ones in arr1            }            if(arr1[i] != arr2[i]) {                mismatchCount++; // Count the number of mismatches between arr1 and arr2            }        }        if(zeroCount == oneCount && mismatchCount % 2== 0) {            System.out.println("Yes"); // If the number of zeros and ones in arr1 are equal and the number of mismatches is even, we can make both arrays equal by swapping pairs of arr1        } else{            System.out.println("No"); // Otherwise, we cannot make both arrays equal by swapping pairs of arr1        }    }}//This code is Contributed by chinmaya121221 | 
Python3
| # Given arraysarr1 =[0, 0, 1, 1]arr2 =[1, 1, 0, 0]n =len(arr1)  # calculate size of arrayszero_count =0one_count =0mismatch_count =0# Loop through each element of the arraysfori inrange(n):    # Count the number of zeros in arr1    ifarr1[i] ==0:        zero_count +=1    else:        one_count +=1# Count the number of ones in arr1    # Count the number of mismatches between arr1 and arr2    ifarr1[i] !=arr2[i]:        mismatch_count +=1# Check the conditions to determine if it's possible to make both arrays equalifzero_count ==one_count andmismatch_count %2==0:    print("Yes")  # If conditions are met, we can make both arrays equal by swapping pairs of arr1else:    print("No")  # Otherwise, we cannot make both arrays equal by swapping pairs of arr1 | 
C#
| usingSystem;classProgram{    staticvoidMain()    {        int[] arr1 = { 0, 0, 1, 1 };        int[] arr2 = { 1, 1, 0, 0 };        intn = arr1.Length; // Calculate the size of arrays        intzeroCount = 0, oneCount = 0, mismatchCount = 0;        for(inti = 0; i < n; i++)        {            if(arr1[i] == 0)            {                zeroCount++; // Count the number of zeros in arr1            }            else            {                oneCount++; // Count the number of ones in arr1            }            if(arr1[i] != arr2[i])            {                mismatchCount++; // Count the number of mismatches between arr1 and arr2            }        }        if(zeroCount == oneCount && mismatchCount % 2 == 0)        {            Console.WriteLine("Yes"); // If the number of zeros and ones                                       // in arr1 are equal and the number of mismatches is                                      // even, we can make both arrays equal by swapping                                      // pairs of arr1        }        else        {            Console.WriteLine("No"); // Otherwise, we cannot make both arrays                                      // equal by swapping pairs of arr1        }    }} | 
Output:
Yes
Time Complexity: The time complexity of the given code is O(n), where n is the size of the arrays. This is because the code uses a single loop to iterate through both arrays, and each operation inside the loop takes constant time.
Auxiliary Space: The space complexity of the code is O(1), as it uses only a few variables to store the counts and does not allocate any additional memory based on the input size.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







