Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Backtracking

Sum of every subset’s XOR

Easy · Target 12 minutes · Backtracking · Type asked atAmazonBloomberg

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.

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.