Skip to content

1863. Sum of All Subset XOR Totals 👍

Approach 1: DFS

  • Time: $O(2^n)$
  • Space: $O(2^n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int subsetXORSum(vector<int>& nums) {
    return dfs(nums, 0, 0);
  }

 private:
  int dfs(const vector<int>& nums, int i, int xors) {
    if (i == nums.size())
      return xors;

    const int x = dfs(nums, i + 1, xors);
    const int y = dfs(nums, i + 1, nums[i] ^ xors);
    return x + y;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int subsetXORSum(int[] nums) {
    return dfs(nums, 0, 0);
  }

  private int dfs(int[] nums, int i, int xors) {
    if (i == nums.length)
      return xors;

    final int x = dfs(nums, i + 1, xors);
    final int y = dfs(nums, i + 1, nums[i] ^ xors);
    return x + y;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def subsetXORSum(self, nums: list[int]) -> int:
    def dfs(i: int, xors: int) -> int:
      if i == len(nums):
        return xors

      x = dfs(i + 1, xors)
      y = dfs(i + 1, nums[i] ^ xors)
      return x + y

    return dfs(0, 0)

Approach 2: Math

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
class Solution {
 public:
  int subsetXORSum(vector<int>& nums) {
    return accumulate(nums.begin(), nums.end(), 0, bit_or<>())
           << nums.size() - 1;
  }
};
1
2
3
4
5
class Solution {
  public int subsetXORSum(int[] nums) {
    return Arrays.stream(nums).reduce((a, b) -> a | b).getAsInt() << nums.length - 1;
  }
}
1
2
3
class Solution:
  def subsetXORSum(self, nums: list[int]) -> int:
    return functools.reduce(operator.or_, nums) << len(nums) - 1