Sum of All Subset XOR Totals
Easy · Backtracking · Explanation and code example
Bit Manipulation (Optimal)
How it works
Each bit position in any number contributes independently to the XOR totals. For any bit that is set in at least one number, exactly half of all subsets will have that bit set in their XOR result (because each element either flips the bit or not, and the combinations balance out). The OR of all numbers gives us all bits that appear in at least one element. Each such bit contributes its value multiplied by 2^(n-1) subsets.
Steps
- Compute the OR of all elements in
nums. This gives a number where eachbitis set if and only if thatbitis set in at least one element. - Left shift the
resultbyn - 1positions (multiply by2^(n-1)). - Return the
result.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)extra space.
Things to watch for
Forgetting the Empty Subset
The problem includes all subsets, including the empty subset which has an XOR value of 0. While this does not affect the sum, a common conceptual error is starting the subset generation from size 1 instead of size 0, or incorrectly counting the total number of subsets as 2^n - 1 instead of 2^n. This can lead to off-by-one issues in verification.
Misunderstanding XOR Properties
A frequent mistake is confusing XOR with addition or other operations. XOR has the property that a ^ a = 0 and a ^ 0 = a. When computing subset XOR totals, some assume that duplicate elements cancel out across all subsets, but each subset is computed independently. Also, the optimal solution relies on understanding that each bit appears in exactly half of all subsets, which requires grasping XOR's bit-level behavior.
Python code example
from typing import List
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
res = 0
for num in nums:
res |= num
return res << (len(nums) - 1)
C++ code example
class Solution {
public:
int subsetXORSum(vector<int>& nums) {
int res = 0;
for (int& num : nums) {
res |= num;
}
return res << (nums.size() - 1);
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.