1863. Sum of All Subset XOR Totals #1521
-
Topics: The XOR total of an array is defined as the bitwise
Given an array Note: Subsets with the same elements should be counted multiple times. An array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to calculate the sum of all XOR totals for every subset of a given array. The key insight here is to leverage bit manipulation and mathematical properties to avoid generating all subsets explicitly, which would be computationally expensive. ApproachThe XOR total of a subset is determined by the bitwise XOR of all its elements. For each bit position, the XOR result will have that bit set if an odd number of elements in the subset have that bit set.
Let's implement this solution in PHP: 1863. Sum of All Subset XOR Totals <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function subsetXORSum($nums) {
return array_reduce($nums, function($carry, $item) {
return $carry | $item;
}) << (count($nums) - 1);
}
subsetXORSum([1,3]); // Output: 6
subsetXORSum([5,1,6]); // Output: 28
subsetXORSum([3,4,5,6,7,8]); // Output: 480
?> Explanation:
This approach efficiently computes the required sum in O(n) time complexity, where n is the number of elements in the array, making it highly efficient even for the upper constraint of n = 12. |
Beta Was this translation helpful? Give feedback.
We need to calculate the sum of all XOR totals for every subset of a given array. The key insight here is to leverage bit manipulation and mathematical properties to avoid generating all subsets explicitly, which would be computationally expensive.
Approach
The XOR total of a subset is determined by the bitwise XOR of all its elements. For each bit position, the XOR result will have that bit set if an odd number of elements in the subset have that bit set.