Maximum XOR of Subsequences Problem
Description
LeetCode Problem 3681.
You are given an integer array nums of length n where each element is a non-negative integer.
Select two subsequences of nums (they may be empty and are allowed to overlap), each preserving the original order of elements, and let:
Xbe the bitwise XOR of all elements in the first subsequence.Ybe the bitwise XOR of all elements in the second subsequence.
Return the maximum possible value of X XOR Y.
Note: The XOR of an empty subsequence is 0.
Example 1:
Input: nums = [1,2,3]
Output: 3
Explanation:
Choose subsequences:
- First subsequence [2], whose XOR is 2.
- Second subsequence [2,3], whose XOR is 1.
Then, XOR of both subsequences = 2 XOR 1 = 3.
This is the maximum XOR value achievable from any two subsequences.
Example 2:
Input: nums = [5,2]
Output: 7
Explanation:
Choose subsequences:
- First subsequence [5], whose XOR is 5.
- Second subsequence [2], whose XOR is 2.
Then, XOR of both subsequences = 5 XOR 2 = 7.
This is the maximum XOR value achievable from any two subsequences.
Constraints:
2 <= nums.length <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Linear Basis
An element that is in both subsequences cancels out in X XOR Y, and an element in exactly one of them is counted once. So X XOR Y can be the XOR of any subset of nums (put the chosen subset in the first subsequence and leave the second one empty), and nothing else. The task is to find the maximum XOR of a subset.
Build a linear basis over the bits 29 down to 0: for each number, go from the highest set bit down. If the basis has no vector with this leading bit, store the number there; otherwise XOR the number with that vector and continue. Finally, start with ans = 0 and go from the high bit to the low bit, replacing ans with ans XOR basis[b] whenever that makes it larger.
Complexity: O(n log M) time and O(log M) extra space, where M is the maximum value (log M = 30).
class Solution:
def maxXorSubsequences(self, nums: List[int]) -> int:
# X xor Y is the xor of any subset of nums, so we want the maximum subset xor (linear basis)
basis = [0] * 30
for x in nums:
for b in range(29, -1, -1):
if not (x >> b) & 1:
continue
if basis[b] == 0:
basis[b] = x
break
x ^= basis[b]
ans = 0
for b in range(29, -1, -1):
ans = max(ans, ans ^ basis[b])
return ans