1559. Subset XOR Peak

Hard7.5 points estimatedBit ManipulationMathsGreedy

A treasure vault holds n enchanted keys, where key i has power nums[i]. You may pick any subset of the keys, including none at all. When keys are combined their powers merge by bitwise XOR, so the charge of a subset is the XOR of the powers of the chosen keys; the empty subset has charge 0.

Return the largest charge that any subset can produce. Keys with equal power are separate keys, but picking both just cancels them out. The number of subsets is astronomically large, so enumeration will not work; the intended solution uses O(n log M) time and O(log M) extra space, where M = 2^30.

Example 1

Input:
nums = [8,1,2]
Output:
11
Explanation:

Choosing all three keys gives 8 ^ 1 ^ 2 = 11, which no other subset beats.

Example 2

Input:
nums = [6,6,6]
Output:
6
Explanation:

Every subset XOR is 0 or 6, so the best is 6.

Constraints

1 ≤ nums.length ≤ 105

0 ≤ nums[i] ≤ 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 3,200 msC++ 800 msJava 1,600 msJavaScript 1,600 msTypeScript 1,600 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…