Skip to main content

Sum of All Subset XOR Totals

Easy
Data Structures and Algorithms
Editorial
Topics:
Array
Backtracking
Bit Manipulation

nums contains integers, and a subset is formed by choosing any collection of its elements, while preserving no ordering requirement. Each element may be chosen at most once, and the empty subset is allowed.

The XOR total of a subset is the bitwise XOR of all values in that subset. The XOR total of the empty subset is 0.

Implement Solution.subsetXORSum(nums) and return the sum of the XOR totals of every possible subset of nums, including the empty subset.

Example 1:

Input: nums = [1,2,4]
Output: 28
Explanation: The eight subset XOR totals sum to 28; the empty subset contributes 0.

Example 2:

Input: nums = [0,5,0]
Output: 20
Explanation: Exactly four subsets have XOR total 5, while the others have total 0, giving 4 * 5 = 20.

Example 3:

Input: nums = [6]
Output: 6
Explanation: The empty subset contributes 0 and the subset containing 6 contributes 6.

Constraints:

  • 1 <= nums.length <= 12
  • 0 <= nums[i] <= 10^4
  • nums contains only integers
  • Every position in nums represents a distinct selectable occurrence, even when values are equal

Need help or want more practice?

Practise in an interviewGet AI Coach help