Approach
Sorting and greedy selection
For Maximum XOR With an Element From Array, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 69 lines of Python from the credited upstream file 1707.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from dataclasses import dataclass2 3 4class TrieNode:5 def __init__(self):6 self.children: list[TrieNode | None] = [None] * 27 8 9class BitTrie:10 def __init__(self, maxBit: int):11 self.maxBit = maxBit12 self.root = TrieNode()13 14 def insert(self, num: int) -> None:15 node = self.root16 for i in range(self.maxBit, -1, -1):17 bit = num >> i & 118 if not node.children[bit]:19 node.children[bit] = TrieNode()20 node = node.children[bit]21 22 def getMaxXor(self, num: int) -> int:23 maxXor = 024 node = self.root25 for i in range(self.maxBit, -1, -1):26 bit = num >> i & 127 toggleBit = bit ^ 128 if node.children[toggleBit]:29 maxXor = maxXor | 1 << i30 node = node.children[toggleBit]31 elif node.children[bit]:32 node = node.children[bit]33 else: 34 return 035 return maxXor36 37 38@dataclass(frozen=True)39class IndexedQuery:40 queryIndex: int41 x: int42 m: int43 44 def __iter__(self):45 yield self.queryIndex46 yield self.x47 yield self.m48 49 50class Solution:51 def maximizeXor(self, nums: list[int], queries: list[list[int]]) -> list[int]:52 ans = [-1] * len(queries)53 maxBit = int(math.log2(max(max(nums), max(x for x, _ in queries))))54 bitTrie = BitTrie(maxBit)55 56 nums.sort()57 58 i = 0 59 for queryIndex, x, m in sorted([IndexedQuery(i, x, m)60 for i, (x, m) in enumerate(queries)],61 key=lambda x: x.m):62 while i < len(nums) and nums[i] <= m:63 bitTrie.insert(nums[i])64 i += 165 if i > 0 and nums[i - 1] <= m:66 ans[queryIndex] = bitTrie.getMaxXor(x)67 68 return ans69