VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-maximum-subset-xor-given-set/

⇱ Maximum XOR Subset - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum XOR Subset

Last Updated : 12 Jun, 2026

Given an array arr[] of positive integers, find the maximum XOR value obtainable by taking the XOR of any subset of its elements.

Examples:

Input: arr[] = [2, 4, 5]
Output: 7
Explanation: The subset {2, 5} has the maximum XOR value.

Input: arr[] = [9, 8, 5]
Output: 13
Explanation: The subset {8, 5} has the maximum XOR value.

[Naive Approach] By generating all possible subsets - O(2^n × n) Time and O(1) Space

Generate all subsets, compute the XOR of elements in each subset, and keep track of the maximum XOR value obtained.

Since a subset can either include or exclude each element, there are 2n possible subsets of an array of size n.


Output
7

[Expected Approach] By applying Gaussian Elimination on Bits

 The idea is based on below facts:

  1. Number of bits to represent all elements is fixed which is 32 bits for integer in most of the cases.
  2. If an element has Most Significant Bit MSB at position i, then result is at least 2i

Steps

  • Process bits from the most significant bit to the least significant bit.
  • For each bit, select an element having that bit set and make it the pivot.
  • Place the pivot at the current basis position so that it is not considered again. Note that we modify the same array to have the XOR subset elements.
  • Eliminate the current bit from all other elements using XOR so that when we finally do XOR of the array, these elements are not considered.
  • Return XOR of the modified array.

Output
7

Time Complexity: O(n × log(max(arr))) - For each bit position, all n elements may be processed once.
Auxiliary Space: O(1)

Comment
Article Tags: