File: sum-of-all-subset-xor-totals/solution.py

Date: 2026-06-06

Time: 19:21

sum-of-all-subset-xor-totals/solution.py

Purpose

Solves LeetCode 1863 — Sum of All Subset XOR Totals. Given an array of positive integers, compute the XOR of every possible subset, then return the sum of all those XOR values.

Key Components

subsetXORSum(nums: List[int]) -> int — The single public function. Takes a list of positive integers, returns the aggregate XOR-sum across all 2^n subsets (including the empty subset, which contributes 0).

Patterns

The solution uses a closed-form bit-contribution formula instead of the naive O(n * 2^n) enumeration of all subsets.

The mathematical insight: for any bit position b, if *at least one* element in nums has bit b set, then exactly half of all 2^n subsets will have an odd number of elements with that bit set — and those are precisely the subsets where bit b survives the XOR. So bit b contributes 2^b * 2^(n-1) to the total sum.

Summing over all bit positions where at least one element has the bit set gives:


(OR of all elements) * 2^(n-1)

That's what reduce(or, nums) * (1 << (len(nums) - 1)) computes. The reduce(or, nums) bitwise-ORs every element together to find which bit positions are "active" anywhere in the array, then multiplies by 2^(n-1).

This reduces the problem from exponential enumeration to O(n) time and O(1) space.

Dependencies

Imports:

Imported by: sum-of-all-subset-xor-totals/test_solution.py (and appears in the shared test import list across the repo, likely through a common test harness pattern).

Flow

1. Guard: if nums is empty, return 0 immediately (avoids reduce on an empty sequence).

2. reduce(or_, nums) — fold bitwise OR across all elements, producing a single integer whose set bits are the union of all set bits in nums.

3. Multiply by 1 << (len(nums) - 1) — i.e., 2^(n-1), the number of subsets in which any given active bit contributes.

4. Return the product.

Invariants

Error Handling

Minimal — the only guard is the empty-list check. reduce(or_, []) would raise TypeError without an initial value; the early return prevents that. No other validation is performed; the function trusts that inputs conform to the LeetCode contract.

Topics to Explore

Beliefs