Subsets of numbers
For each subset we can xor the elements. If there are 3 numbers in the array, there are possible subsets. So, we use the bit patterns for the numbers
to find elements of the subsets.
Time: , space:
.
class Solution:
def xor_total(self, subset, nums):
s = 0
for i in range(32):
if subset & (1 << i):
s ^= nums[i]
return s
def subsetXORSum(self, nums: List[int]) -> int:
xor_sum = 0
subset_count = 1 << len(nums)
for subset in range(subset_count):
xor_sum += self.xor_total(subset, nums)
return xor_sum
Subsets of bit positions
Say we have two -bit numbers:
and
.
Now, XOR(,
) =
.
Say, for the numbers,
subset-xor’s have the
-th bit set. So, in the final xor-sum the
-th bit contributes
. So, the sum we are looking for is
.
Say, -th bit is set in just one of the
numbers. There are
subsets which include that particular number and there are equal number of subsets that exclude that particular number. So, in the final xor-sum, the
-th bit contributes:
.
Now, if -th bit is set in two numbers, the xor will be unset if both of them are included. So, it seems the number of subsets that have xor-sum with
-th bit set is less. But, the second number also adds to the count of subset where the first number is not included. These two, reduce and increase, nullify each other and we end up having
subsets with
-th bit set in their xor-sums.
In other words, whenever, -th bit is set in any of the
numbers, it contributes
to the final xor-sum.
Time: , space:
.
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
xor_ones = 0
for x in nums:
xor_ones |= x
return xor_ones << (len(nums)-1)
Leave a comment