- Related Questions & Answers
- Sum of the products of all possible Subsets in C++
- Sum of XOR of all subarrays in C++
- XOR of Sum of every possible pair of an array in C++
- Sum of XOR of all pairs in an array in C++
- Count number of subsets having a particular XOR value in C++
- Maximum possible difference of two subsets of an array in C++
- XOR of all subarray XORs in C++
- Sum of all subsets of a set formed by first n natural numbers
- Print all subsets of given size of a set in C++
- Print all possible sums of consecutive numbers with sum N in C++
- Find all distinct subsets of a given set in C++
- Minimizing array sum by applying XOR operation on all elements of the array in C++
- Find sum of sum of all sub-sequences in C++
- XOR of all Prime numbers in an Array in C++
- Maximum value of XOR among all triplets of an array in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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)).

Program to illustrate the working of our solution,

#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); }

Sum of XOR of all possible subsets is 20

Advertisements