Leetcode 2932. Maximum Strong Pair XOR I
Given an array of integers nums
, find two integers a
and b
from the array such that the bitwise XOR of a
and b
is maximized. Return the maximum XOR value.
-2^31
to 2^31-1
unless stated otherwise.n
) can be reasonably large, up to 10^5
.Here is the implementation using the Trie optimization:
#include <vector>
#include <iostream>
#include <algorithm>
#include <climits>
class TrieNode {
public:
TrieNode* children[2];
TrieNode() {
children[0] = children[1] = nullptr;
}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(int num) {
TrieNode* node = root;
// Insert each bit to the Trie
for (int i = 31; i >= 0; --i) {
int bit = (num >> i) & 1;
if (!node->children[bit]) {
node->children[bit] = new TrieNode();
}
node = node->children[bit];
}
}
int getMaxXOR(int num) {
TrieNode* node = root;
int max_xor = 0;
for (int i = 31; i >= 0; --i) {
int bit = (num >> i) & 1;
if (node->children[1 - bit]) {
max_xor |= (1 << i);
node = node->children[1 - bit];
} else {
node = node->children[bit];
}
}
return max_xor;
}
};
int findMaximumXOR(std::vector<int>& nums) {
Trie trie;
int max_xor = 0;
for (int num : nums) {
trie.insert(num);
max_xor = std::max(max_xor, trie.getMaxXOR(num));
}
return max_xor;
}
int main() {
std::vector<int> nums = {3, 10, 5, 25, 2, 8};
std::cout << "Maximum XOR: " << findMaximumXOR(nums) << std::endl;
return 0;
}
Each number is inserted into the Trie and checked for maximum XOR, resulting in a relatively optimal and feasible solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?