VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-maximum-subarray-xor-in-a-given-array/

⇱ Maximum Subarray XOR - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Subarray XOR

Last Updated : 3 May, 2026

Given an array arr[] of size, N. Find the subarray with maximum XOR. A subarray is a contiguous part of the array.

Examples: 

Input: arr[] = [1, 2, 3, 4]
Output: 7
Explanation: The subarray [3, 4] has maximum XOR value

Input: arr[] = [8, 1, 2, 12, 7, 6]
Output: 15
Explanation: The subarray [1, 2, 12] has maximum XOR value

Input: arr[] = [4, 6]
Output: 6
Explanation: The subarray [6] has maximum XOR value

[Naive Approach] Consider all Subarrays - O(n²) Time and O(1) Space

Consider all possible subarrays and calculate their XORs. The maximum among them will be the required answer.


Output
15

[Optimal Approach] Using Trie and Prefix XOR - O(n * 32) Time and O(n * 32) Space

Any subarray XOR can be written as XOR of two prefix XORs. So instead of checking all subarrays, we store prefix XORs and try to find another prefix that gives maximum XOR with the current one. A Trie helps us maximize XOR greedily by choosing opposite bits on a path from Trie root.

  • Use property: XOR(i, j) = prefix[j] ^ prefix[i-1]
  • Create a Trie to store prefix XOR values
  • Insert 0 initially to handle subarrays starting from index 0
  • Maintain prefix XOR and update it while traversing the array
  • Insert each updated prefix XOR into the Trie
  • Query the Trie for maximum XOR by traversing opposite bits

Illustration:

It can be observed from the above algorithm that we build a Trie that contains XOR of all prefixes of given array. To find the maximum XOR subarray ending with arr[i], there may be two cases. 

  • The prefix itself has the maximum XOR value ending with arr[i]. For example if i=2 in [8, 2, 1, 12], then the maximum subarray xor ending with arr[2] is the whole prefix. 
  • Remove some prefix (ending at index from 0 to i-1). For example if i=3 in [8, 2, 1, 12], then the maximum subarray xor ending with arr[3] starts with arr[1] and we need to remove arr[0].
  • To find the prefix to be removed, find the entry in Trie that has maximum XOR value with current prefix. If we do XOR of such previous prefix with current prefix, get the maximum XOR value ending with arr[i]. 
  • If there is no prefix to be removed (case i), then we return 0 (that's why we inserted 0 in Trie). 

Below is the implementation of the above idea :


Output
15

Exercise: Extend the above solution so that it also prints starting and ending indexes of subarray with maximum value (Hint: we can add one more field to Trie node to achieve this 

Comment