Minimum operations to make XOR of array zero - cook the code

Monday 18 September 2017

Minimum operations to make XOR of array zero

Minimum operations to make XOR of array zero

We are given an array of n elements. The task is to make XOR of whole array 0. We can do following to achieve this.
  1. We can select any one of the element.
  2. After selecting element, we can either increment or decrement it by 1.
We need to find the minimum number of increment/decrement operation required for the selected element to make the XOR sum of whole array zero.
Examples:
Input : arr[] = {2, 4, 8}
Output : Element = 8, 
         Operation required = 2
Explanation : Select 8 as element and perform 2 
              time decrement on it. So that it
              became 6, Now our array is {2, 4, 6} 
              whose XOR sum is 0.

Input : arr[] = {1, 1, 1, 1}
Output : Element = 1, 
         Operation required = 0
Explanation : Select any of 1 and you have already
              your XOR sum = 0. So, no operation 
              required.
Naive Approach : Select an element and then find the XOR of rest of the array. If that element became equals to XOR obtained then our XOR of the whole array should become zero. Now, our cost for that will be the absolute difference of selected element and obtained XOR. This process of finding cost will be done for each element and thus resulting into Time Complexity of (n^2).
Efficient Approach : Find the XOR of whole array. Now, suppose we have selected element arr[i], so cost required for that element will be absolute(arr[i]-(XORsum^arr[i])). Calculating minimum of these absolute values for each of element will be our minimum required operation also the element corresponding to minimum required operation will be our selected element.
// CPP to find min cost to make
// XOR of whole array zero
#include <bits/stdc++.h>
using namespace std;
 
// function to find min cost
void minCost(int arr[], int n)
{
    int cost = INT_MAX;
    int element;
 
    // calculate XOR sum of array
    int XOR = 0;
    for (int i = 0; i < n; i++)
        XOR ^= arr[i];
 
    // find the min cost and element corresponding
    for (int i = 0; i < n; i++) {
        if (cost > abs((XOR ^ arr[i]) - arr[i])) {
            cost = abs((XOR ^ arr[i]) - arr[i]);
            element = arr[i];
        }
    }
 
    cout << "Element = " << element << endl;
    cout << "Operation required = " << abs(cost);
}
 
// driver program
int main()
{
    int arr[] = { 2, 8, 4, 16 };
    int n = sizeof(arr) / sizeof(arr[0]);
    minCost(arr, n);
    return 0;
}
Output:
Element = 16
Operation required = 2
Time Complexity : O(n)

No comments:

Post a Comment