Leetcode 1863. Sum of All Subset XOR Totals
Given an integer array nums
, find the sum of all XOR totals for every subset of nums
. The XOR total of a subset is defined as the bitwise XOR of all its elements if the subset is not empty.
nums
array?
nums
are non-negative integers and the length of nums
is between 1 and 12.nums
.n
, we can simplify the computation.import java.util.ArrayList;
import java.util.List;
public class Solution {
public int subsetXORSum(int[] nums) {
List<Integer> currentSubset = new ArrayList<>();
return backtrack(nums, currentSubset, 0);
}
private int backtrack(int[] nums, List<Integer> currentSubset, int index) {
if (index == nums.length) {
// Calculate the XOR total for the current subset (excluding empty subset)
if (currentSubset.isEmpty()) return 0;
int xorTotal = 0;
for (int num : currentSubset) {
xorTotal ^= num;
}
return xorTotal;
}
// Include the current element
currentSubset.add(nums[index]);
int include = backtrack(nums, currentSubset, index + 1);
currentSubset.remove(currentSubset.size() - 1);
// Exclude the current element
int exclude = backtrack(nums, currentSubset, index + 1);
return include + exclude;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {1, 3};
System.out.println(sol.subsetXORSum(nums)); // Output: 6
}
}
The time complexity for this backtracking solution is exponential, O(2^n), where n
is the number of elements in the nums
array. This is because we generate all possible subsets (which is 2^n
subsets). In practice, given nums
array length constraints (1 ≤ n ≤ 12), this exponential time complexity is manageable.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?