Leetcode 421. Maximum XOR of Two Numbers in an Array
Given an integer array nums
, return the maximum result of nums[i] XOR nums[j]
, where 0 <= i <= j < n
.
nums
?
One efficient approach to solve this problem involves using a Trie (Prefix Tree) to store binary representations of the numbers. The high-level steps are:
1
, we prefer to go to 0
and vice versa) to maximize the XOR value.Here’s the Java code implementing the detailed strategy:
import java.util.*;
public class Solution {
class TrieNode {
TrieNode[] children = new TrieNode[2]; // For binary 0 and 1
}
public int findMaximumXOR(int[] nums) {
TrieNode root = new TrieNode();
// Insert each number into the Trie
for (int num : nums) {
TrieNode node = root;
for (int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
if (node.children[bit] == null) {
node.children[bit] = new TrieNode();
}
node = node.children[bit];
}
}
int max_xor = 0;
// Find the maximum XOR for each number
for (int num : nums) {
TrieNode node = root;
int current_xor = 0;
for (int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
if (node.children[bit ^ 1] != null) { // Prefer opposite bit
current_xor = (current_xor << 1) | 1;
node = node.children[bit ^ 1];
} else {
current_xor = (current_xor << 1);
node = node.children[bit];
}
}
max_xor = Math.max(max_xor, current_xor);
}
return max_xor;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {3, 10, 5, 25, 2, 8};
System.out.println(sol.findMaximumXOR(nums)); // Output: 28
}
}
This approach ensures that we can efficiently find the maximum XOR pair in an optimal time.
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?