Sum of Subset XOR Totals
Solve this Problemnums has, counting each subset once even if two subsets happen to share the same elements or the same total, and return the overall sum.
Enumerating every subset works directly, and with at most 12 elements there are never more than 4096 of them to walk. But there's a shortcut hiding in the structure: any bit that shows up in at least one element ends up set in exactly half of all the subset totals, so its contribution to the final sum is fixed regardless of exactly which elements carry it. That collapses the whole computation to a single OR across every element, scaled by how many subsets share each bit.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ nums.length ≤ 12 - ◆
1 ≤ nums[i] ≤ 20
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Backtracking — Enumerate Every Subset
BruteBuild every subset by deciding, one element at a time, whether it's in or out — recursing on both choices. At each fully-formed subset (including the empty one, reached when every element has been decided), fold its elements together with XOR and add that to a running total. With n capped at 12, this touches at most 4096 subsets, so the exponential enumeration stays fast enough here.
O(2ⁿ × n)O(n) recursion depth1class Solution {
2 private int total = 0;
3
4 public int subsetXorSum(int[] nums) {
5 backtrack(nums, 0, 0);
6 return total;
7 }
8
9 private void backtrack(int[] nums, int index, int currentXor) {
10 if (index == nums.length) {
11 total += currentXor;
12 return;
13 }
14 backtrack(nums, index + 1, currentXor ^ nums[index]);
15 backtrack(nums, index + 1, currentXor);
16 }
17}Optimal — OR of All Elements
OptimalAny bit that's set in at least one array element ends up set in exactly half of all 2ⁿ subset totals — pairing up each subset with the one that only differs by that single element's membership flips that bit and nothing else. A bit that's set nowhere in the array can never appear in any subset total. That means the sum of every subset's XOR total equals the bitwise OR of every element, scaled by 2ⁿ⁻¹.
O(n)O(1) extra1class Solution {
2 public int subsetXorSum(int[] nums) {
3 int orAll = 0;
4 for (int num : nums) {
5 orAll |= num;
6 }
7 return orAll << (nums.length - 1);
8 }
9}