Minimum XOR operations to make all array elements zero

Updated

You are given an integer X and an array consisting of containing N integers and you need to convert those integers to 0 but you can only perform the following operation :

  • Choose an integer i and select at most X integers from the given array and replace those elements as let the element is E so replace E with E^(1<<i) where ^ denote the bitwise XOR operator and << denotes the bitwise left shift operator

So you need to print the minimum number of moves in which you can make all the array elements to 0.

Examples :

Input : N = 4 , X = 3
       Arr[] = {1,2,3,4}
Output : Minimum number of operations to be performed: 3
Explanation :
We will first select 1 and 3 and take i = 0 then performing the
operation the array becomes {0,2,2,4}
Then we will select 2 and 2 and take i = 1 then performing the
operation the array becomes {0,0,0,4}
In the last operation we select 4 and i = 2 then the array will become
{0,0,0,0} which is required

Example 2 :
Input : N = 10 ,X = 4
	   Arr[] = {34,2,28,8,39,19,38,18,29,10}
Output : Minimum number of operations to be performed: 7

Approach :

In order to solve the problem we must know the property of XOR function i.e. 1^1 = 0 && 0^1 = 1 .So we want to make all the elements 0 therefore we need to unset all the bits of all the elements. So now we need to know which elements to choose and count the steps ,as we are working on bits so we can store the set bits of each element in an array and then the minimum operations require to unset those bits will be ceil(countOfSetBits/X) so we need to print in the output.

Code implementation of the approach :

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
    int N, X;
    N = 10, X = 4;
    int elements[]
        = { 34, 2, 28, 8, 39, 19, 38, 18, 29, 10 };
    int setBits[32];
    for (int i = 0; i < 32; i++) {
        setBits[i] = 0;
    }
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < 32; j++) {
            if (elements[i] & (1 << j)) {
                setBits[j]++;
            }
        }
    }
    int minOperations = 0;
    for (int i = 0; i < 32; i++) {
        minOperations += ceil(1.0 * setBits[i] / X);
    }
    cout << "Minimum number of operations to be performed: "
         << minOperations;
    return 0;
}
Output

Minimum number of operations to be performed: 7

Complexity analysis :

Time Complexity : O(N)

Space Complexity : O(1)

Comment
Mithlesh Upadhyay Published 21 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials