Minimum operations to make XOR of array zero
Last Updated :
28 Oct, 2023
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 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.
Implementation:
C++
// 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;
}
Java
// JAVA program to find min cost to make
// XOR of whole array zero
import 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 */
Python3
# python to find min cost to make
# XOR of whole array zero
# function to find min cost
def 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 program
arr = [ 2, 8, 4, 16 ]
n = len(arr)
minCost(arr, n)
# This code is contributed by Sam007
C#
// C# program to find min cost to
// make XOR of whole array zero
using 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.
JavaScript
<script>
// javascript to find min cost to make
// XOR of whole array zero
// function to find min cost
function 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 program
var arr = [ 2, 8, 4, 16 ];
var n = arr.length;
minCost(arr, n);
</script>
PHP
<?php
// PHP to find min cost to make
// XOR of whole array zero
// function to find min cost
function 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.
?>
OutputElement = 16
Operation required = 2
Time Complexity : O(n)
Auxiliary space: O(1) it is using constant space
New Approach:
C++
// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum cost
void minCost(int arr[], int n)
{
unordered_map<int, int> freq;
for (int i = 0; i < n; i++) {
freq[arr[i]]++;
}
int max_freq = INT_MIN;
int max_elem = -1;
for (auto it : freq) {
if (it.second > max_freq) {
max_freq = it.second;
max_elem = it.first;
}
}
int XOR = 0;
for (int i = 0; i < n; i++) {
XOR ^= arr[i];
}
int cost = abs((XOR ^ max_elem) - max_elem);
cout << "Element = " << max_elem << endl;
cout << "Operation required = " << abs(cost) << endl;
}
// Driver code
int main()
{
int arr[] = { 2, 8, 4, 16 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
minCost(arr, n);
return 0;
}
Java
import java.util.*;
public class MinCost {
public static void minCost(int[] arr, int n) { //function to find minimum cost
HashMap<Integer, Integer> freq = new HashMap<>();
for (int i = 0; i < n; i++) { //iterate the array from left to right and compute frequency of each element
freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);
}
int maxFreq = Integer.MIN_VALUE;
int maxElem = -1;
for (Integer elem : freq.keySet()) {
if (freq.get(elem) > maxFreq) {
maxFreq = freq.get(elem);
maxElem = elem;
}
}
//Find xor of every element of the array
int xor = 0;
for (int i = 0; i < n; i++) {
xor ^= arr[i];
}
int cost = Math.abs((xor ^ maxElem) - maxElem);
System.out.println("Element = " + maxElem);
System.out.println("Operation required = " + Math.abs(cost));
}
public static void main(String[] args) {
int[] arr = {2, 8, 4, 16};
int n = arr.length;
minCost(arr, n);
}
}
Python3
from collections import Counter
# Function to find minimum cost
def min_cost(arr):
freq = Counter(arr)
max_freq = float('-inf')
max_elem = -1
for element, frequency in freq.items():
if frequency > max_freq:
max_freq = frequency
max_elem = element
XOR = 0
for element in arr:
XOR ^= element
cost = abs((XOR ^ max_elem) - max_elem)
print("Element =", max_elem)
print("Operation required =", abs(cost))
# Driver code
if __name__ == "__main__":
arr = [2, 8, 4, 16]
# Function call
min_cost(arr)
C#
using System;
using System.Collections.Generic;
public class Program
{
// Function to find the minimum cost
public static void MinCost(int[] arr)
{
Dictionary<int, int> freq = new Dictionary<int, int>();
// Count the frequency of each element in the array
for (int i = 0; i < arr.Length; i++)
{
if (freq.ContainsKey(arr[i]))
freq[arr[i]]++;
else
freq[arr[i]] = 1;
}
int max_freq = int.MinValue;
int max_elem = -1;
// Find the element with the maximum frequency
foreach (var kvp in freq)
{
if (kvp.Value > max_freq)
{
max_freq = kvp.Value;
max_elem = kvp.Key;
}
}
int XOR = 0;
// Perform XOR operation on all elements of the array
for (int i = 0; i < arr.Length; i++)
{
XOR ^= arr[i];
}
// Calculate the cost by performing XOR operations
int cost = Math.Abs((XOR ^ max_elem) - max_elem);
// Print the maximum frequency element and the required operation count
Console.WriteLine("Element = " + max_elem);
Console.WriteLine("Operation required = " + Math.Abs(cost));
}
// Driver code
public static void Main()
{
int[] arr = { 2, 8, 4, 16 };
// Function call
MinCost(arr);
}
}
JavaScript
// Javascript Implementation
const freq = new Map();
// Function to find minimum cost
function minCost(arr) {
for (let i = 0; i < arr.length; i++) {
if (freq.has(arr[i])) {
freq.set(arr[i], freq.get(arr[i]) + 1);
} else {
freq.set(arr[i], 1);
}
}
let max_freq = -Infinity;
let max_elem = -1;
for (let [key, value] of freq) {
if (value >= max_freq) {
max_freq = value;
max_elem = key;
}
}
let XOR = 0;
for (let i = 0; i < arr.length; i++) {
XOR ^= arr[i];
}
let cost = Math.abs((XOR ^ max_elem) - max_elem);
console.log("Element = " + max_elem);
console.log("Operation required = " + Math.abs(cost));
}
// Driver code
const arr = [2, 8, 4, 16];
// Function call
minCost(arr);
OutputElement = 16
Operation required = 2
Time Complexity: O(n), where n is the size of the input array.
Auxiliary Space: O(n)
Similar Reads
Minimum no. of operations required to make all Array Elements Zero Given an array of N elements and each element is either 1 or 0. You need to make all the elements of the array equal to 0 by performing the below operations: If an element is 1, You can change it's value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.
12 min read
Minimum Operations to Reduce X to Zero Given an integer array of nums[] and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations, the task is to return the minimum number of operations to reduc
9 min read
Minimizing Bitwise-OR with XOR Operation on an Array Given an array arr[] of non-negative integers where arr[i] >= 0, the task is to select a non-negative integer 'k' and perform the bitwise-XOR operation on every element of the array with 'k' (i.e., XOR0 = arr[0] ^ k, XOR1 = arr[1] ^ k, and so on). The objective is to minimize the bitwise-OR of th
9 min read
Minimum Bitwise XOR operations to make any two array elements equal Given an array arr[] of integers of size N and an integer K. One can perform the Bitwise XOR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make a
9 min read
Minimum XOR of OR and AND of any pair in the Array Given an array arr[] of N positive integers the task is to find the minimum value of Bitwise XOR of Bitwise OR and AND of any pair in the given array. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 Explanation: For element 2 & 3: The value of the expression (2&3) xor (2|3) is 1, which is
5 min read
Minimum operations to make all Array elements 0 by MEX replacement Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
5 min read