You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].
The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.
Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.
Example 1:
Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
Output: [3,3,7]
Explanation:
1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
2) 1 XOR 2 = 3.
3) 5 XOR 2 = 7.
Each query asks for the maximum \(x_i\oplus nums[j]\) among values \(\le m_i\). Scanning the array per query is \(O(nq)\) and fails for \(n,q\le 10^5\).
Queries are independent of one another and of the order of \(nums\). Sorting by \(m_i\) lets us insert eligible numbers monotonically into one structure.
Sort \(nums\) and insert values \(\le m_i\) into a binary trie with a moving pointer. Walking opposite bits on the trie yields the maximum XOR; an empty trie answers \(-1\).
From the problem description, we know that each query is independent and the result of the query is irrelevant to the order of elements in \(nums\). Therefore, we consider sorting all queries in ascending order of \(m_i\), and also sorting \(nums\) in ascending order.
Next, we use a binary trie to maintain the elements in \(nums\). We use a pointer \(j\) to record the current elements in the trie, initially \(j=0\). For each query \([x_i, m_i]\), we continuously insert elements from \(nums\) into the trie until \(nums[j] > m_i\). At this point, we can query all elements not exceeding \(m_i\) in the trie, and we take the XOR value of the element with the maximum XOR value with \(x_i\) as the answer.
The time complexity is \(O(m \times \log m + n \times (\log n + \log M))\), and the space complexity is \(O(n \times \log M)\). Where \(m\) and \(n\) are the lengths of the arrays \(nums\) and \(queries\) respectively, and \(M\) is the maximum value in the array \(nums\). In this problem, \(M \le 10^9\).