Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 5, 2025 22:51
Show Gist options
  • Save Ifihan/f66c76bc701b7d79909751bcaeaaceea to your computer and use it in GitHub Desktop.
Save Ifihan/f66c76bc701b7d79909751bcaeaaceea to your computer and use it in GitHub Desktop.
Sum of All Subset XOR Totals

Question

Approach

I used a recursive DFS to explore all possible subsets of the array. At each index, I either included the element in the XOR or skipped it. Once I reached the end of the array, I returned the XOR total of that subset. Summing all these gave me the final result.

Implementation

class Solution:
    def subsetXORSum(self, nums: List[int]) -> int:
        def dfs(i, curr_xor):
            if i == len(nums):
                return curr_xor
            # Include nums[i] in subset XOR or skip it
            return dfs(i + 1, curr_xor ^ nums[i]) + dfs(i + 1, curr_xor)

        return dfs(0, 0)

Complexities

  • Time: O(2^n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment