
Sponsored
Sponsored
This approach uses recursion to generate all possible subsets of the array and calculates their XOR sum. The function will explore each element, either including or excluding it in the subset. This will give us the XOR sum for each subset, and we can accumulate the total from there.
Time Complexity: O(2n), where n is the length of nums.
Space Complexity: O(n) because of the recursion stack.
1function subsetXORSum(nums) {
2 function xorSubsetSum(index, currentXor) {
3 if (index === nums.length) {
4 return currentXor;
5 }
6 const include = xorSubsetSum(index + 1, currentXor ^ nums[index]);
7 const exclude = xorSubsetSum(index + 1, currentXor);
8 return include + exclude;
9 }
10 return xorSubsetSum(0, 0);
11}
12
13console.log(subsetXORSum([1, 3])); // Output: 6This JavaScript function solves the problem using a recursive approach by deciding whether to include or exclude each element, hence calculating the XOR sum for each subset.
The alternative approach involves using bit manipulation to generate subsets efficiently. Each number's inclusion in a subset corresponds to a binary decision, allowing us to loop from 0 to (2n - 1) integers, using each binary representation as a decision for a subset.
Time Complexity: O(n * 2n), where n is the length of nums due to the bitwise operations.
Space Complexity: O(1) as no additional space is used apart from counters.
This Java method uses a bitmask loop to process every possible subset. Each number is conditionally XORed into a total based on the binary representation of the mask.