SDE & MLE Prep

1863. Sum of All Subset XOR Totals

Problem

The XOR total of a subset is the XOR of all its elements (0 for the empty set). Return the sum of the XOR totals of every subset of nums; equal values at different positions count as different subsets.

Example: [1,3] → 6 (0 + 1 + 3 + 2)

Constraints: n ≤ 12.

Backtracking over all 2ⁿ subsets works (n ≤ 12). The elegant O(n) answer: a bit that is set in any element is set in exactly half of all subset XORs, so the sum is (OR of all nums) · 2^(n−1).

Complexity: O(n).

class Solution:
    def subsetXORSum(self, nums: List[int]) -> int:
        return functools.reduce(lambda x, y: x | y, nums) << (len(nums) - 1)