1560. Subset XOR Ways

Hard7.5 points estimatedBit ManipulationMathsCombinatorics

A music app lets a listener build a "mix" from n tracks, where track i has a style code nums[i]. A mix is any subset of tracks chosen by position (so two tracks with the same code at different positions are different choices), and the empty mix is allowed. The style of a mix is the bitwise XOR of the codes of its tracks, and the empty mix has style 0.

Count the mixes whose style equals exactly target, and return that count modulo 1000000007. The count can be astronomically large before the modulus. Dynamic programming over all reachable styles is too slow; the intended solution runs in O(n log M) time with O(log M) extra space, where M = 2^30.

Example 1

Input:
nums = [1,2,3], target = 3
Output:
2
Explanation:

The subsets {3} and {1, 2} both XOR to 3, and nothing else does, so there are 2 ways.

Example 2

Input:
nums = [4,4], target = 0
Output:
2
Explanation:

The empty subset and the subset of both tracks give style 0, so there are 2 ways.

Constraints

1 ≤ nums.length ≤ 105

0 ≤ nums[i], target ≤ 230 - 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n log M)
Space
O(log M)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…