1863. Sum of All Subset XOR Totals
Problem
The XOR total of a subset is the XOR of all its elements (0 for the empty set). Return the sum of the XOR totals of every subset of nums; equal values at different positions count as different subsets.
Example: [1,3] → 6 (0 + 1 + 3 + 2)
Constraints: n ≤ 12.
Backtracking over all 2ⁿ subsets works (n ≤ 12). The elegant O(n) answer: a bit that is set in any element is set in exactly half of all subset XORs, so the sum is (OR of all nums) · 2^(n−1).
Complexity: O(n).
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
return functools.reduce(lambda x, y: x | y, nums) << (len(nums) - 1)
assert Solution().subsetXORSum([1, 3]) == 6
assert Solution().subsetXORSum([5, 1, 6]) == 28
assert Solution().subsetXORSum([3, 4, 5, 6, 7, 8]) == 480
nums = [9, 2, 7, 12, 1]
brute = sum(functools.reduce(lambda x, y: x ^ y, c, 0) for r in range(len(nums) + 1) for c in itertools.combinations(nums, r))
assert Solution().subsetXORSum(nums) == brute
class Solution {
public int subsetXORSum(int[] nums) {
int or = 0;
for (int x : nums) or |= x;
return or << (nums.length - 1);
}
}
func subsetXORSum(nums []int) int {
or := 0
for _, x := range nums {
or |= x
}
// each bit set in some number is set in exactly half of the 2^n subset XORs
return or << (len(nums) - 1)
}