Problem Statement
You are given an array arr[]. You can choose any subset of the array (including a subset containing one element or all elements). Your task is to find the maximum possible XOR of the chosen subset.
Example 1
Input
arr = [2, 4, 5]
Possible XORs
{} = 0
{2} = 2
{4} = 4
{5} = 5
{2,4} = 6
{2,5} = 7 <- Maximum
{4,5} = 1
{2,4,5} = 3
Output
7
Example 2
Input
arr = [9, 8, 5]
Output
13
Explanation
8 XOR 5 = 13
Naive Approach
Generate every possible subset and calculate its XOR.
Number of subsets = 2ⁿ
Time Complexity = O(2ⁿ × n)
This works only for very small arrays.
Since n can be 100000, we need a much faster solution.
Efficient Approach (XOR Basis / Gaussian Elimination)
The idea is very similar to Gaussian Elimination used in mathematics.
Instead of eliminating numbers using addition and subtraction, we eliminate bits using the XOR operation.
The goal is to build a set of independent numbers called the XOR Basis.
Key Observation
Suppose we have
2 = 010
4 = 100
5 = 101
Notice:
5 XOR 4 = 001
Now our basis becomes
100
010
001
Using these three numbers, we can generate every XOR combination.
The maximum possible XOR is
100
010
001
-------
111 = 7
Algorithm
Starting from the most significant bit (31st bit) to the least significant bit:
Step 1
Find a number whose current bit is set.
Example
Bit = 4
16 = 10000
20 = 10100
9 = 01001
Choose one number having bit 4 set.
Step 2
Move that number to the current position.
This becomes our pivot.
Step 3
Remove that bit from every other number.
If another number also has that bit,
number ^= pivot
This clears the highest set bit.
Repeat for every bit.
Eventually every basis element has a unique highest set bit.
Dry Run
Input
arr = [2,4,5]
Binary
2 = 010
4 = 100
5 = 101
Processing Bit 2 (Value = 4)
Pivot
100
Eliminate from others
101 XOR 100 = 001
Now
100
010
001
Processing Bit 1 (Value = 2)
Pivot
010
No elimination needed.
Processing Bit 0 (Value = 1)
Pivot
001
Finished.
Final basis
100
010
001
Maximum XOR
100
010
001
-------
111 = 7
Answer = 7
Code
class Solution {
public int maxSubsetXOR(int[] arr) {
int n = arr.length;
// Position where next basis element will be placed
int index = 0;
// Traverse every bit from MSB to LSB
for (int bit = 31; bit >= 0; bit--) {
int maxIndex = -1;
// Find an element with current bit set
for (int i = index; i < n; i++) {
if (((arr[i] >> bit) & 1) == 1) {
maxIndex = i;
break;
}
}
// No element has this bit
if (maxIndex == -1)
continue;
// Bring pivot to current position
int temp = arr[index];
arr[index] = arr[maxIndex];
arr[maxIndex] = temp;
// Remove current bit from every other element
for (int i = 0; i < n; i++) {
if (i != index &&
((arr[i] >> bit) & 1) == 1) {
arr[i] ^= arr[index];
}
}
index++;
}
// XOR of basis gives maximum subset XOR
int result = 0;
for (int num : arr)
result ^= num;
return result;
}
}

Join the conversation! Your thoughts help the community grow.