![]() |
VOOZH | about |
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 valueInput: arr[] = [8, 1, 2, 12, 7, 6]
Output: 15
Explanation: The subarray [1, 2, 12] has maximum XOR valueInput: arr[] = [4, 6]
Output: 6
Explanation: The subarray [6] has maximum XOR value
Table of Content
Consider all possible subarrays and calculate their XORs. The maximum among them will be the required answer.
15
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.
prefix[j] ^ prefix[i-1]0 initially to handle subarrays starting from index 0 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 :
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