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:
Below is the implementation of the above approach:
// C++ program for above approach #include <bits/stdc++.h> using namespace std; // Function to check if two arrays // can be made equal or not by swapping // pairs of only one of the arrays void checkArrays(int arr1[], int arr2[], int N) { // Stores elements required // to be replaced int count = 0; // To check if the arrays // can be made equal or not bool flag = true; // Traverse the array for (int 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 = 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 Code int main() { // Given arrays int arr1[] = { 0, 0, 1, 1 }; int arr2[] = { 1, 1, 0, 0 }; // Size of the array int N = sizeof(arr1) / sizeof(arr1[0]); checkArrays(arr1, arr2, N); return 0; }
Output:
Yes
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.