You are given an array of integers nums
. A strong pair (i, j)
is defined as follows:
0 <= i < j < nums.length
nums[i]
and nums[j]
is maximum possible.Return the maximum XOR of any strong pair.
Example:
Input: nums = [3, 10, 5, 25, 2, 8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.
1 <= nums.length <= 2 * 10^4
and 0 <= nums[i] <= 2^31 - 1
.To solve this problem, a brute force approach would involve checking all pairs (i, j)
and computing their XOR value to find the maximum. However, with an upper limit of 2*10^4
on the length of nums
, this approach would be inefficient since its time complexity would be (O(n^2)).
Instead, we can use a more efficient method leveraging bit manipulation and a trie data structure to store the binary representations of numbers. Here’s a step-by-step outline of the optimized approach:
Convert numbers to binary and insert into a trie: We’ll create a binary trie where each bit of the number represents a path in the trie.
Maximize XOR with greedy approach: For each number, we will try to find the maximum possible XOR by traversing the trie. The goal is to select paths in the trie that would maximize the bit difference at each level.
Here’s an implementation of the solution using a trie:
class TrieNode:
def __init__(self):
self.children = dict()
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, num):
node = self.root
for i in range(31, -1, -1):
bit = (num >> i) & 1
if bit not in node.children:
node.children[bit] = TrieNode()
node = node.children[bit]
def find_max_xor(self, num):
node = self.root
xor = 0
for i in range(31, -1, -1):
bit = (num >> i) & 1
toggled_bit = 1 - bit
if toggled_bit in node.children:
xor |= (1 << i)
node = node.children[toggled_bit]
else:
node = node.children.get(bit, node)
return xor
class Solution:
def findMaximumXOR(self, nums):
trie = Trie()
max_xor = 0
for num in nums:
trie.insert(num)
for num in nums:
max_xor = max(max_xor, trie.find_max_xor(num))
return max_xor
This approach ensures we handle large inputs efficiently and find the maximum XOR for any strong pair.
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?