Skip to content
Problem 1863 · LeetCode 1863(opens in a new tab)

Sum of All Subset XOR Totals

EasyBit manipulation

The XOR total of a list is what you get by XOR-ing all of its values together. An empty list has XOR total 0, and [6, 3] has XOR total 6 XOR 3 = 5.

Given nums, look at every subset you can form by keeping some of its positions and dropping the rest (keeping none and keeping all both count). Add up the XOR totals of all these subsets and return the sum. Subsets that hold the same values but use different positions are counted separately.

Example 1

Input:  nums = [2, 5]
Output: 14
Why:    subsets give 0, 2, 5 and 2 XOR 5 = 7; 0 + 2 + 5 + 7 = 14
2 more examples and the constraints

Example 2

Input:  nums = [2, 4, 4]
Output: 24
Why:    the 8 subsets give 0, 2, 4, 4, 6, 6, 0, 2

Example 3

Input:  nums = [9]
Output: 9
Why:    the empty subset gives 0 and [9] gives 9

Constraints

  • 1 ≤ length of nums ≤ 12
  • 1 ≤ each value ≤ 20

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every subsetO(n·2ⁿ)
  2. OR of all, shiftedO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 12 numbersVerdict
Try every subsetO(n·2ⁿ)
Passes at n ≤ 12
OR of all, shiftedO(n)
Best; one pass

n = length of nums.

Edge cases to test

  • One number. [9] gives 0 + 9 = 9, and 9 << 0 is 9.
  • Repeated values. [2, 4, 4] has 8 subsets because each position counts, so the answer is 24, not the 12 of [2, 4].
  • All bits overlap. [7, 7] has OR 7, so the sum is 7 × 2 = 14: subsets give 0, 7, 7, 0.
  • Largest input. 12 numbers with OR 31 give 31 × 2¹¹ = 63,488, which fits in an int.

Common mistakes

  • Skipping the empty subset and miscounting the subsets as 2ⁿ − 1 when deriving the shift.
  • Removing duplicate values first; repeated positions are separate subsets.
  • Shifting by n instead of n − 1: each bit is on in half the subsets, not all of them.

How to talk through it

  1. 1Clarify. Does the empty subset count? Are equal values at different positions separate subsets?
  2. 2Give the enumeration. n ≤ 12, so 4,096 bitmasks are cheap. Say it is O(n·2ⁿ).
  3. 3Think per bit. XOR works bit by bit, so ask: in how many subsets is bit b on?
  4. 4Prove the half. Toggling one number that has bit b pairs every subset with one of the opposite parity, so half have it.
  5. 5Test out loud. Check [2, 5] = 14 both ways, then a single number and a repeated value.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?