#1863
Sum of All Subset XOR Totals
EasyArrayMathBacktrackingBit ManipulationCombinatoricsEnumerationBit ManipulationCombinatorics
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n * 2^n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach leverages the properties of XOR and the fact that each number contributes to multiple subsets. Specifically, each number appears in half of the subsets, allowing us to calculate the contribution of each number directly without generating all subsets.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the number of subsets that include each number, which is 2^(n-1) where n is the length of the array.
- 2Step 2: For each number in the array, compute its contribution to the total XOR sum as num * (2^(n-1)).
- 3Step 3: Sum all contributions to get the final result.
solution.py6 lines
1def subsetXORSum(nums):
2 n = len(nums)
3 total_sum = 0
4 for num in nums:
5 total_sum += num * (1 << (n - 1)) # 2^(n-1)
6 return total_sumℹ
Complexity note: The time complexity is O(n) because we iterate through the array once. The space complexity is O(1) since we use a constant amount of space.
- 1Each number contributes equally to the XOR of all subsets.
- 2The number of subsets including a number is 2^(n-1).
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.