Minimum operations to make XOR of array zero - GeeksforGeeks

28 Apr, 2021
We are given an array of n elements. The task is to make XOR of whole array 0. We can do the following to achieve this.  
We can select any one of the elements.After selecting an element, we can either increment or decrement it by 1.
We can select any one of the elements.
After selecting an element, we can either increment or decrement it by 1.
We need to find the minimum number of increment/decrement operations required for the selected element to make the XOR sum of the 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 the 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 between the selected element and obtained XOR. This process of finding cost will be done for each element and thus resulting in Time Complexity of (n^2).Efficient Approach: Find the XOR of the 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 the minimum of these absolute values for each element will be our minimum required operation also the element corresponding to the minimum required operation will be our selected element.  
C++
Java
Python3
C#
PHP
Javascript
// CPP to find min cost to make// XOR of whole array zero#include <bits/stdc++.h>using namespace std; // function to find min costvoid 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 programint main(){    int arr[] = { 2, 8, 4, 16 };    int n = sizeof(arr) / sizeof(arr[0]);    minCost(arr, n);    return 0;}
// JAVA program to find min cost to make// XOR of whole array zeroimport java.lang.*; class GFG{    // function to find min cost    static void minCost(int[] arr, int n)    {        int cost = Integer.MAX_VALUE;        int element=0;         // 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 > Math.abs((XOR ^ arr[i])                                - arr[i])) {                cost = Math.abs((XOR ^ arr[i]) -                                       arr[i]);                element = arr[i];            }        }     System.out.println("Element = " + element);    System.out.println("Operation required = "+                             Math.abs(cost));    }     // driver program    public static void main (String[] args)    {        int[] arr = { 2, 8, 4, 16 };        int n = arr.length;        minCost(arr, n);    }}/* This code is contributed by Kriti Shukla */
# python to find min cost to make# XOR of whole array zero # function to find min costdef minCost(arr,n):         cost = 999999;         # calculate XOR sum of array    XOR = 0;    for i in range(0, n):        XOR ^= arr[i];     # find the min cost and element    # corresponding    for i in range(0,n):        if (cost > abs((XOR ^ arr[i]) - arr[i])):            cost = abs((XOR ^ arr[i]) - arr[i])            element = arr[i]     print("Element = ", element)    print("Operation required = ", abs(cost))  # driver programarr = [ 2, 8, 4, 16 ]n = len(arr)minCost(arr, n) # This code is contributed by Sam007
// C# program to find min cost to// make XOR of whole array zerousing System; class GFG{    // function to find min cost    static void minCost(int []arr, int n)    {        int cost = int.MaxValue;        int element=0;         // 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 > Math.Abs((XOR ^ arr[i]) - arr[i]))            {                cost = Math.Abs((XOR ^ arr[i]) - arr[i]);                element = arr[i];            }        }     Console.WriteLine("Element = " + element);    Console.Write("Operation required = "+                          Math.Abs(cost));    }     // Driver program    public static void Main ()    {        int []arr = {2, 8, 4, 16};        int n = arr.Length;        minCost(arr, n);    }} // This code is contributed by nitin mittal.
<?php// PHP to find min cost to make// XOR of whole array zero // function to find min costfunction minCost($arr, $n){    $cost = PHP_INT_MAX;    $element;     // calculate XOR sum of array    $XOR = 0;    for ($i = 0; $i < $n; $i++)        $XOR ^= $arr[$i];     // find the min cost and    // element corresponding    for ($i = 0; $i < $n; $i++)    {        if ($cost > abs(($XOR ^ $arr[$i]) -                                 $arr[$i]))        {            $cost = abs(($XOR ^ $arr[$i]) -                                 $arr[$i]);            $element = $arr[$i];        }    }     echo "Element = " , $element ,"\n";    echo "Operation required = " , abs($cost);} // Driver Code$arr = array(2, 8, 4, 16) ;$n = count($arr);minCost($arr, $n); // This code is contributed by vt_m.?>
<script> // javascript to find min cost to make// XOR of whole array zero // function to find min costfunction minCost(arr, n){    var cost = 1000000000;    var element;     // calculate XOR sum of array    var XOR = 0;    for (var i = 0; i < n; i++)        XOR ^= arr[i];     // find the min cost and element corresponding    for (var i = 0; i < n; i++) {        var x= Math.abs((XOR ^ arr[i]) - arr[i])        if (cost > x) {            cost = x;            element = arr[i];        }    }     document.write( "Element = " + element + "<br>");    document.write( "Operation required = " + Math.abs(cost));} // driver programvar arr = [ 2, 8, 4, 16 ];var n = arr.length;minCost(arr, n); </script>
Output: 
Element = 16
Operation required = 2
Time Complexity : O(n)This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
vt_m
Sam007
itsok
Bitwise-XOR
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array