Leetcode 1863. Sum of All Subset XOR Totals
You are given an integer array nums
. The XOR total of an array is defined as the bitwise XOR of all its elements, or 0
if the array is empty.
[2,5,6]
is 2 XOR 5 XOR 6 = 1
.Return the sum of all XOR totals for every subset of nums
.
A subset of an array is a selection of elements (possibly empty) of the array.
nums
contain?
1 <= nums.length <= 12
).nums
?
0 <= nums[i] <= 1000
).We need to compute the sum of XOR totals for all possible subsets. Given that the array size is relatively small (max 12), an exhaustive approach is feasible. Each subset can be generated and evaluated using bitwise XOR.
Let’s translate the strategy into C++ code.
#include <vector>
#include <cmath>
class Solution {
public:
int subsetXORSum(std::vector<int>& nums) {
int n = nums.size();
int totalSubsets = 1 << n; // 2^n subsets
int sumOfXORs = 0;
// Generate each subset
for (int subsetMask = 0; subsetMask < totalSubsets; ++subsetMask) {
int currentXOR = 0;
// Calculate XOR for the current subset
for (int i = 0; i < n; ++i) {
if (subsetMask & (1 << i)) {
currentXOR ^= nums[i];
}
}
sumOfXORs += currentXOR;
}
return sumOfXORs;
}
};
Hence, the time complexity is: [ O(n \cdot 2^n) ]
This is manageable given the constraints ((n \leq 12)).
This approach efficiently addresses the problem within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?