Editor

Total of Every Subset's XOR

#333 · Bit manipulation · Intermediate · 80 XP · about 15 min

The XOR of a group of numbers is what you get by combining them all with ^; the XOR of the empty group is 0. Write xor_total(nums) that returns the sum of the XORs of all the subsets of nums, the empty subset included.

Subsets are chosen by position, so a list of n numbers always has 2^n subsets, and when a value appears twice, subsets that use one copy or the other are counted separately.

Examples

xor_total([1, 3])     # returns 6
xor_total([5, 1, 6])  # returns 28
xor_total([2, 2])     # returns 4
xor_total([])         # returns 0

The subsets of [1, 3] are the empty one (XOR 0), [1] (1), [3] (3) and [1, 3] (1 ^ 3 = 2), and 0 + 1 + 3 + 2 = 6.

Constraints

  • 0 <= len(nums) <= 60
  • 0 <= nums[i] <= 10**9
  • With 60 numbers there are more than 10^18 subsets, far too many to visit one by one.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.