Sum of XOR of all possible subsets in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array aar[] of n numbers. Our task is to create a program to find the Sum of XOR of all possible subsets.

Here, we will find all subsets of the array. Then for each subset, we will find the XOR of elements of the subset and add them to the sum variable.

Let’s take an example to understand the problem,

Input: arr[] = {5, 1, 4}
Output: 20
Explanation: XOR of all subsets:
{5} = 5
{1} = 1
{4} = 4
{5, 1} = 4
{5, 4} = 1
{1, 4} = 5
{5, 1, 4} = 0
Sum of XOR = 5 + 1 + 4 + 4 + 1 + 5 = 20

A simple solution to the problem, is using loop and find all possible subsets of the array and then for each subset find XOR of all the elements and update the sum. Return sum at the end.

This is not an effective approach, for the large value, the time complexity will grow exponentially.

An efficient approach is using the properties of XOR. Here, we will find the OR of all elements of the array and check the bits. If the ith is set, then update sum with (2^(n-1+i)).

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
int subSetXORSum(int arr[], int n) {
   int bitOR = 0;
   for (int i=0; i < n; ++i)
   bitOR |= arr[i];
   return (bitOR * pow(2, n-1));
}
int main() {
   int arr[] = {1, 5, 4};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Sum of XOR of all possible subsets is "<<subSetXORSum(arr, size);
}

Output

Sum of XOR of all possible subsets is 20
raja
Published on 17-Aug-2020 13:30:52
Advertisements