# Minimum flips in two binary arrays so that their XOR is equal to another array in C++.

C++Server Side ProgrammingProgramming

## Problem statement

Given three arrays with 0’s and 1’s of size n, the task is to find minimum flip of bits in the first and second array such that the XOR of i’th index bit of first and second array is equal to i’th index bit of the third array.

Please note that we can only flip at most p bits of array 1 and at most q bits of array 2. Also rearranging array elements is not allowed.

Let us suppose p = 2 and q = 5

arr1[] = {1, 0, 1, 1, 0, 1, 0}
arr2[] = {0, 1, 0, 1, 0, 0, 1}
arr3[] = {0, 1, 1, 0, 0, 0, 0}
• (arr1 ^ arr2) i.e (1 ^ 0) = 1 which is not equal to arr3. Hence flip is required.
• (arr1 ^ arr2) i.e (0 ^ 1) = 1 which is equal to arr3. Hence flip is not required.

• (arr1 ^ arr2) i.e (1 ^ 0) = 1 which is equal to arr3. Hence flip is not required.

• (arr1 ^ arr2) i.e (1 ^ 1) = 0 which is equal to arr3. Hence flip is not required.

• (arr1 ^ arr2) i.e (0 ^ 0) = 0 which is equal to arr3. Hence flip is not required.

• (arr1 ^ arr2) i.e (1 ^ 0) = 1 which is not equal to arr3. Hence flip is required.

• (arr1 ^ arr2) i.e (0 ^ 1) = 1 which is not equal to arr3. Hence flip is required.

## Algorithm

1. If (arr1[i] ^ arr2[i]) == arr3[i] then continue as flip is not required.
2. If (arr1[i] ^ arr2[i]) != arr3[i] then flip is required.
a. If arr3[i] == 0 then one of the following condition is
true:
i. (arr1[i] == 0) and (arr2[i] == 0) OR
ii. (arr1[i] == 1) and (arr2[i] == 1)
b. If arr3[i] == 1 then one of the following condition is
true:
i. (arr1[i] == 0) and (arr2 == 1) OR
ii. (arr1[i] == 1) and (arr2[i] == 0)
3. If flip is required then we can either flip arr1[i] or arr2[i]. Hence we can conclude that number of flips required to make XOR of arr1 and arr2 equal to arr3 should be less than or equal to p + q.

## Example

#include <iostream>
#define SIZE(arr) (sizeof(arr) / sizeof(arr))
using namespace std;
int getRequiredFlips(int *arr1, int *arr2, int *arr3, int n, int p, int q){
int flips = 0;
for (int i = 0; i < n; ++i) {
if ((arr1[i] ^ arr2[i]) != arr3[i]) {
++flips;
}
}
return flips <= (p + q) ? flips : -1;
}
int main(){
int arr1[] = {1, 0, 1, 1, 0, 1, 0};
int arr2[] = {0, 1, 0, 1, 0, 0, 1};
int arr3[] = {0, 1, 1, 0, 0, 0, 0};
int size = SIZE(arr1);
cout << "Flips required: " << getRequiredFlips(arr1, arr2, arr3, size, 2, 5) << "\n";
return 0;
}

## Output

When you compile and execute the above program. It generates the following output −

Flips required: 3