![]() |
VOOZH | about |
We are given an array arr[], find the sum of XOR values of all possible subsets of the array.
Note: Every subset formed using different index selections must be considered separately, even if two subsets contain the same elements.
Examples:
Input: arr[] = [1, 2, 3]
Output: 12
Explanation: All possible subsets are: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Bitwise-XOR of these subsets will be: 0, 1, 2, 3, 3, 2, 1, 0, 12 respectively.
Sum of all these XOR values will be 12(0 + 1 + 2 + 3 + 3 + 2 + 1 + 0).Input: arr[] = [7, 2]
Output: 14
Explanation: All possible subsets are: [[], [7], [2], [7, 2]]
There Bitwise-XOR will be: 0, 7, 2 and 5 respectively.
Sum of all these XOR values will be 14(0 + 7 + 2 + 5).
Table of Content
We can use recursion to explore all possible subsets. At each step, we will decide whether to include or exclude the current element, and we update the running XOR value based on that choice. This allows us to compute the XOR contribution of every subset. By returning the sum of the results from both choices i.e. one including the element and one excluding it - we accumulate the total XOR sum of all subsets.
12
The idea is to determine how many subsets will have a particular bit set in their XOR value. A bit contributes to the XOR only when it appears an odd number of times in a subset. So, if a bit appears k times in the array, it can contribute when it is chosen 1, 3, 5, ... times in the subset—up to at most k times. By counting how many subsets produce an odd occurrence for each bit, and repeating this process for every bit position, we can compute the total contribution of each bit and sum these contributions to get the final XOR sum of all subsets.
Therefore, we first take the bitwise OR of all numbers to gather every bit that appears anywhere, and then multiply it by 2(n-1) to get the final sum.
Examples:
12