Problem Description
Given an array of non-negative integers, nums, and a list of queries where each query is a pair [x, m], the goal is to find for each query the maximum XOR value of x with any number from nums that is less than or equal to m. If no number in nums meets the condition for a query, return -1 for that query.
Key Insights
- Sort the nums array and process queries offline based on the m value.
- Use a binary Trie (prefix tree) to efficiently compute maximum XOR for a given x.
- Iteratively add elements from nums into the Trie which are valid for each query (i.e., nums[j] <= m).
- The optimal bit-wise approach takes advantage of XOR properties by always trying to choose the opposite bit to maximize the result.
Space and Time Complexity
Time Complexity: O((n + q) * L) where L (≈32) is the number of bits, plus the sorting cost O(n log n + q log q).
Space Complexity: O(n * L) for the Trie.
Solution
We first sort the nums array. Next, we attach the original index to each query and sort the queries based on m. As we process each query in increasing order of m, we insert numbers from nums that are <= current m into our Trie. For each query, we then use the Trie to compute the maximum XOR value with x. If the Trie is empty (i.e., no valid number found), we return -1 for that query. This approach guarantees that each number is inserted only once and every query is answered in O(L) time.