Sum of All Subset XOR Totals - Problem
Sum of All Subset XOR Totals

Imagine you have an array of numbers and need to find every possible subset (including the empty set), calculate the XOR of all elements in each subset, and then sum all these XOR results together.

The XOR total of an array is the bitwise XOR of all its elements. For an empty array, the XOR total is 0.

Example: For array [2, 5, 6], the XOR total is 2 โŠ• 5 โŠ• 6 = 1

Your task is to:
1. Generate all possible subsets of the given array
2. Calculate the XOR total for each subset
3. Return the sum of all these XOR totals

Note: A subset can be obtained by deleting some (possibly zero) elements from the original array.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 3]
โ€บ Output: 6
๐Ÿ’ก Note: Subsets: {} (XOR=0), {1} (XOR=1), {3} (XOR=3), {1,3} (XOR=1โŠ•3=2). Sum: 0+1+3+2=6
example_2.py โ€” Single Element
$ Input: [5]
โ€บ Output: 5
๐Ÿ’ก Note: Subsets: {} (XOR=0), {5} (XOR=5). Sum: 0+5=5
example_3.py โ€” Three Elements
$ Input: [5, 1, 6]
โ€บ Output: 28
๐Ÿ’ก Note: 8 subsets total: {}, {5}, {1}, {6}, {5,1}, {5,6}, {1,6}, {5,1,6} with XOR totals 0,5,1,6,4,3,7,2. Sum: 0+5+1+6+4+3+7+2=28

Visualization

Tap to expand
๐Ÿ”ฎ The Magic of Subset XOR TotalsMagical Stones13โ†’All Combinations{}XOR = 0{1}XOR = 1{3}XOR = 3{1,3}XOR = 2Sum = 0+1+3+2 = 6โ†’โšก Optimal FormulaOR(1,3) = 1|3 = 33 ร— 2^(2-1) = 3 ร— 2= 6 โœจ๐Ÿ”‘ Key InsightEach magical stone appears in exactly half of all combinations!โ€ข Stone 1 appears in: {1}, {1,3} โ†’ 2 out of 4 combinationsโ€ข Stone 3 appears in: {3}, {1,3} โ†’ 2 out of 4 combinationsโ€ข For n stones: each appears in 2^(n-1) combinationsโ€ข So: OR ร— 2^(n-1) gives us the total magical power!
Understanding the Visualization
1
List all combinations
For stones [1,3]: {}, {1}, {3}, {1,3}
2
Calculate each XOR
XOR totals: 0, 1, 3, 2
3
Sum all totals
Total magical power: 0+1+3+2 = 6
4
Discover the pattern
OR(1,3) ร— 2^(2-1) = 3 ร— 2 = 6 โœจ
Key Takeaway
๐ŸŽฏ Key Insight: Instead of generating all 2^n subsets, we use the mathematical property that each element contributes to exactly 2^(n-1) subsets. The OR of all elements combined with left-shift gives us the answer in O(n) time!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

We iterate through the array once to calculate OR, then do constant time operations

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few integer variables for calculations

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 12
  • 1 โ‰ค nums[i] โ‰ค 20
  • The array can have at most 212 = 4096 subsets
Asked in
Amazon 35 Microsoft 28 Google 22 Meta 18
48.2K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen