The problem, in one line. For a short list of numbers, XOR together the members of every possible subset, then add up all those results. LeetCode 1863.
The tell. “Every subset” with a list of at most 12 numbers. A small size cap is the statement saying that doing the work for every subset is expected, so the question is only how to visit them without building them.
The wrong first idea
Build every subset as a list, then fold XOR over each list and add the results.
total = 0
for mask in range(1 << len(nums)):
x = 0
for i in range(len(nums)):
if mask >> i & 1:
x ^= nums[i]
total += x
return total
This is correct and it passes. It re-walks all n positions for each of the 2 to the n subsets, so 12 numbers means 4,096 subsets and about 49,000 steps. The recursion below does the same visiting but carries the XOR down as it goes, so each subset costs one step instead of n.
The invariant
Go through the list one number at a time. For each number there are two branches: take it or leave it. The running XOR travels down with you, and when you run out of numbers the running value is one subset’s total.
flowchart TB R["start, xor 0"] -->|"take 1"| A["xor 1"] R -->|"leave 1"| B["xor 0"] A -->|"take 3"| C["leaf, xor 2"] A -->|"leave 3"| D["leaf, xor 1"] B -->|"take 3"| E["leaf, xor 3"] B -->|"leave 3"| F["leaf, xor 0"]
The sentence that stays true every step: the running XOR is the XOR of exactly the numbers I took so far. The four leaves give 2, 1, 3 and 0, which add to 6.
The solution
def subset_xor_sum(nums):
def go(i, xor):
if i == len(nums):
return xor
return go(i + 1, xor ^ nums[i]) + go(i + 1, xor) # take it, or leave it
return go(0, 0)
print(subset_xor_sum([1, 3]))
print(subset_xor_sum([5, 1, 6]))
print(subset_xor_sum([3, 4, 5, 6, 7, 8]))
6
28
480
func subsetXORSum(nums []int) int {
var rec func(i, x int) int
rec = func(i, x int) int {
if i == len(nums) {
return x
}
return rec(i+1, x^nums[i]) + rec(i+1, x) // take it, or leave it
}
return rec(0, 0)
}
Same three calls print 6, 28, 480.
Complexity
- Time O(2^n): two branches per number, so 2 to the n leaves, each reached in constant work per level shared with its siblings.
- Space O(n): only the recursion stack, no subset is ever stored.
Traps
- Combining with
+instead of^. On[1, 3]the full subset becomes 4 instead of 2 and the answer is 8 instead of 6. - Treating equal values as one.
[5, 5]has four subsets by position and the answer is 10, but deduplicating the values gives 5. - Returning the XOR of the whole list. That is only the single largest subset, so
[1, 3]gives 2 instead of 6.
Next in the ladder
subsets asks for the subsets themselves instead of a number, so the running value becomes a list you must copy at every node.