Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Backtracking

Sum of every subset’s XOR

Easy · Target 12 minutes · Backtracking· Type asked at

The XOR total of a list is the bitwise XOR of all its elements (0 for the empty list). Given an array nums, return the sum of the XOR totals of all its subsets. Subsets with equal values but different positions count separately.

Examples

InputOutputWhy
nums = [1, 3]6Subsets: [] → 0, [1] → 1, [3] → 3, [1, 3] → 2. Sum 6.
nums = [5, 1, 6]28Eight subsets.
nums = [2, 2]4[] → 0, [2] → 2, [2] → 2, [2, 2] → 0.

Constraints

  • 1 ≤ n ≤ 12
  • 0 ≤ nums[i] ≤ 20

Hints

Hint 1

There are 2ⁿ subsets and n is at most 12. Can you visit each exactly once without building lists?

Hint 2

For each element there are two choices: in or out. Recurse on the index, carrying the XOR of the elements chosen so far.

Hint 3

When the index reaches n, the carried value is one subset’s XOR total: return it. The answer at each node is the sum of the answers of its two children.

Where people lose marks

  • Building every subset as a list and XOR-ing it afterwards: O(n·2ⁿ) time and a lot of allocation for no benefit.
  • Deduplicating equal values. The statement counts subsets by position, so [2, 2] has four subsets, not three.
  • Forgetting the empty subset. Its XOR total is 0, so it changes nothing here, but in counting variants it matters.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.