#3681
Maximum XOR of Subsequences
HardArrayMathGreedyBit ManipulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log(max)) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log(max))Space O(n)
Use a linear basis to represent the numbers in terms of their binary representation, allowing efficient calculation of maximum XOR.
⚙️
Algorithm
3 steps- 1Step 1: Build a basis for the binary representation of the numbers.
- 2Step 2: Use the basis to compute the maximum XOR possible.
- 3Step 3: Return the maximum XOR value derived from the basis.
solution.py11 lines
1def maxXOR(nums):
2 basis = []
3 for num in nums:
4 for b in basis:
5 num = min(num, num ^ b)
6 if num > 0:
7 basis.append(num)
8 max_xor = 0
9 for b in basis:
10 max_xor = max(max_xor, max_xor ^ b)
11 return max_xorℹ
Complexity note: Building the basis takes O(n log(max)), where max is the largest number in nums. Space is used to store the basis.
- 1XOR is maximized when bits differ.
- 2Building a basis helps efficiently compute maximum XOR.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.