
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Flips in Two Binary Arrays for Equal XOR
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[0] ^ arr2[0]) i.e (1 ^ 0) = 1 which is not equal to arr3[0]. Hence flip is required.
(arr1[1] ^ arr2[1]) i.e (0 ^ 1) = 1 which is equal to arr3[1]. Hence flip is not required.
(arr1[2] ^ arr2[2]) i.e (1 ^ 0) = 1 which is equal to arr3[2]. Hence flip is not required.
(arr1[3] ^ arr2[3]) i.e (1 ^ 1) = 0 which is equal to arr3[3]. Hence flip is not required.
(arr1[4] ^ arr2[4]) i.e (0 ^ 0) = 0 which is equal to arr3[4]. Hence flip is not required.
(arr1[5] ^ arr2[5]) i.e (1 ^ 0) = 1 which is not equal to arr3[5]. Hence flip is required.
(arr1[6] ^ arr2[6]) i.e (0 ^ 1) = 1 which is not equal to arr3[6]. 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[0] == 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[0])) 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