LeetCode Problem Number: 1863

Sum of All Subset XOR Totals

Solve on LeetCode

Problem Description

The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.

For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.

Given an array nums, return the sum of all XOR totals for every subset of nums.

Note: Subsets with the same elements should be counted multiple times.


Example 1:

Input: nums = [1,3]
Output: 6
Explanation: The 4 subsets of [1,3] are:
- The empty subset has an XOR total of 0.
- [1] has an XOR total of 1.
- [3] has an XOR total of 3.
- [1,3] has an XOR total of 1 XOR 3 = 2.
0 + 1 + 3 + 2 = 6

Example 2:

Input: nums = [5,1,6]
Output: 28
Explanation: The 8 subsets of [5,1,6] are:
- The empty subset has an XOR total of 0.
- [5] has an XOR total of 5.
- [1] has an XOR total of 1.
- [6] has an XOR total of 6.
- [5,1] has an XOR total of 5 XOR 1 = 4.
- [5,6] has an XOR total of 5 XOR 6 = 3.
- [1,6] has an XOR total of 1 XOR 6 = 7.
- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.
0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28

Example 3:

Input: nums = [3,4,5,6,7,8]
Output: 480
Explanation: The sum of all XOR totals for every subset is 480.

Solution Code


class Solution {
public:
    int subsetXORSum(vector& a) {
        int n = a.size();
        int bitSize = 1 << n;
        int res = 0;
        for (int i = 0; i < bitSize; i++) {
            int xorSum = 0;
            for (int j = 0; j < n; j++) {
                if (i & (1 << j)) {
                    xorSum ^= a[j];
                }
            }
            res += xorSum;
        }
        return res;
    }
};
                    

Solution Explanation

The problem involves calculating the sum of XOR totals for every subset of a given array. The solution follows these steps:

  • Generate Subsets: For an array of size n, there are 2^n subsets. We use a bitmask approach to generate all possible subsets. Each bit in the bitmask represents whether a corresponding element in the array is included in the subset or not.
  • Calculate XOR Total: For each subset represented by a bitmask, calculate the XOR total by iterating through the elements and applying XOR operation based on the bitmask.
  • Sum XOR Totals: Accumulate the XOR totals of all subsets to get the final result.