Sum of All Subset XOR Totals

The XOR total of an array is the bitwise XOR of all its elements, or 0 if the array is empty. Given an array nums, return the sum of the XOR totals of every subset of nums. Subsets with the same elements taken from different positions are counted separately.

30:00

Sum of All Subset XOR Totals
easy
Free written solution
Topics
Companies

The XOR total of an array is the bitwise XOR of all its elements, or 0 if the array is empty. Given an array nums, return the sum of the XOR totals of every subset of nums. Subsets with the same elements taken from different positions are counted separately.

Example 1:
Input: {"nums":[1,3]}
Output: 6
Constraints:
  • 1≤nums.length≤121 \leq nums.length \leq 12

  • 1≤nums[i]≤201 \leq nums[i] \leq 20

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,3]}

There are 2^2 = 4 subsets. Instead of XOR-ing each one, look at every bit column on its own. Start with bits = 0.

OR every number into one mask

n = 2, subsets = 4

4
2
1
1
0
0
1
3
0
1
1
bits=0
0
0
0

each live bit is on in half the subsets

sum = 0

after the OR, each 1 in bits adds its value x 2^(n-1)

check: every subset and its XOR

[] = 0
[1] = 1
[3] = 3
[1,3] = 2
Variables
VariableValue
bits0
n2
DepthFunction Call
Stack empty
0/8