Problem Statement
Given an array of integers, find the maximum XOR value of any two elements in the array.
The condition |x - y| <= min(x, y)
means that for a pair of integers (x, y
) to be considered a "strong pair
", the absolute difference between x
and y
(|x - y|
) must be less than or equal to the minimum of x
and y
(min(x, y)
).
In simpler terms, it means that the absolute difference between x and y should not exceed the smaller of the two numbers.
For example:
- For the pair (3, 5), the absolute difference is |3 - 5| = 2, and the minimum of 3 and 5 is 3. Since 2 is less than or equal to 3, the pair (3, 5) is a strong pair.
- For the pair (8, 2), the absolute difference is |8 - 2| = 6, and the minimum of 8 and 2 is 2. Since 6 is greater than 2, the pair (8, 2) is not a strong pair.
Examples
Example 1:
Input: arr = [3, 10, 5, 25, 2, 8]
Output: Maximum XOR value: 28
Explanation: In the given array, the maximum XOR value of any two elements is achieved when 5 and 25 are selected.
5^25 = 28
Hence, the maximum XOR value is 28.
Example 2:
Input: arr[] = {0, 2, 5, 7}
Output: 7
Explanation: The maximum XOR value is achieved by 0 XOR 7 = 7
Theory
XOR, also known as exclusive OR, is a bitwise operation that outputs true only when the input differs (one is true, other is false) (both are different). The XOR operation is denote dby the symbol ^
. For example:
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
Different Approaches
1 Brute Force Approach
Algorithm:
- Initialize a variable maxXOR to store the maximum XOR value.
- Iterate through all pairs of elements in the array.
- For each pair of elements (
arr[i]
,arr[j]
), calculate theirXOR
value and update maxXOR if the XOR value is greater than the current maxXOR. - Return
maxXOR
.
Code Implementation:
#include <iostream>
#include <vector>
using namespace std;
int findMaximumXORPair(vector<int>& arr) {
int n = arr.size();
int maxXOR = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
maxXOR = max(maxXOR, arr[i] ^ arr[j]);
}
}
return maxXOR;
}
int main() {
vector<int> arr = {3, 10, 5, 25, 2, 8};
cout << "Maximum XOR Pair: " << findMaximumXORPair(arr) << endl;
return 0;
}
Complexity Analysis:
Time Complexity:
- The brute force approach involves checking all possible pairs of elements in the array, resulting in a time complexity of O(N^2), where N is the size of the array.
Space Complexity:
- The space complexity is O(1) as we are not using any extra space apart from the input array.