Sum of All Subset XOR Totals
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
Sum of All Subset XOR Totals
Return the sum of all XOR totals for every subset of
nums.Examples
Input: nums = [1,3]
Output: 6
Input: nums = [5,1,6]
Output: 28
Approach 1
Level I: Brute Force (Backtracking)
Intuition
Generate all possible subsets, calculate the XOR of each, and sum them up.
Thought Process
- Use recursion to explore including or excluding each element.
- Maintain a
currentXorvalue through the recursion tree. - Base case: If reached end of array, return
currentXor.
Pattern: Subset Generation
⏱ O(2^N) - We visit every subset.💾 O(N) - Recursion depth.
Approach 2
Level II: Iterative Subset Generation
Intuition
Use a bitmask from 0 to to represent every possible subset of
nums. For each mask, calculate the XOR total and add it to the sum.⏱ $O(N \cdot 2^N)$💾 $O(1)$
Approach 3
Level III: Optimal (Contribution of Each Bit)
Intuition
For a bit position , if at least one number in
nums has the -th bit set, then in exactly half of the subsets (i.e., ), the XOR total will have the -th bit set. This is because adding a number with the -th bit set flips the -th bit of the XOR sum.Thought Process
- Find the bitwise OR of all numbers in the array. This identifies all bit positions that are set in at least one number.
- If the -th bit is set in the OR result, it contributes to the total sum.
- Result =
(OR of all nums) * 2^(n-1).
Pattern: Combinatorial Bit Counting
⏱ O(N) - Single pass to find the bitwise OR.💾 O(1) - Constant space.
Detailed Dry Run
nums = [1, 3], n = 2
OR = 1 | 3 = 3 (binary 11)
Sum = 3 * 2^(2-1) = 3 * 2 = 6.
Result matches brute force!
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.