![]() |
VOOZH | about |
Given an array arr[] of non-negative integers. The task is to find the maximum possible XOR of any two elements of the array.
Example:
Input: arr[] = [26, 100, 25, 13, 4, 14]
Output: 126
Explanation: XOR of 26 ^ 100 = 126, which is the maximum possible XOR.Input: arr[] = [1, 2, 3, 4, 5, 6, 7]
Output: 7
Explanation: XOR of 1 ^ 6 = 7, which is the maximum possible XOR.
Table of Content
The idea is to generate all possible pairs of elements of the array arr[] and find the maximum among them. To do so, use two nested loops to generate all the pairs and compute XOR of them. The maximum of all the pairs is the result.
126
The idea is to find two numbers in an array arr[] such that their XOR equals a number X, where X is the maximum value we want to achieve at the current bit position (i-th bit). To achieve the largest XOR value, we aim to maximize the number of 1s in the XOR result, starting from the most significant bit (leftmost bit) to the least significant bit (rightmost bit).
To evaluate each bit position, we use a mask. A mask helps us focus on specific bits of the numbers in the array by keeping only the relevant bits up to the current position and ignoring the rest. Using the mask, we extract prefixes for all numbers in the array (i.e., the portions of the numbers defined by the mask). These prefixes help us determine if a pair of numbers exists in the array whose XOR can yield a maximum value at the current bit.
For each bit position:
- Apply the mask to extract prefixes from the numbers.
- Try to update the maximum XOR value by assuming the i-th bit of the result is 1.
- Using the set of prefixes, we check if any two prefixes can produce the desired XOR value (with the i-th bit set).
This process is repeated for all 32 bits, starting from the leftmost bit, to compute the largest possible XOR value step by step.
126
Time Complexity: O(n * log m), where n is the size of array and m is the maximum element.
Auxiliary Space: O(n * log m)
The idea is to use Trie data structure to effectively store and search bits of each element of array arr[]. For each element arr[i], check if an element with opposite bits is present in the Trie or not i.e. if current bit of arr[i] is set (1), then check if unset bit (0) at current index is present in Trie.
Note: Please refer to Trie article to know more about insert and search operation.
126