Suppose we have a list of numbers nums and a list of queries where each query contains [x, limit]. We have to find a list such that for each query [x, limit], we find an element e in nums such that e ≤ limit and e XOR x is maximized. If there is no such element, return -1.
So, if the input is like nums = [3, 5, 9] queries = [[4, 6],[2, 0]], then the output will be [3, -1], as for the first query, we can use 2 or 4 in nums. 3 ^ 4 = 7 while 5 ^ 4 = 3 so we select 3 which yields the bigger XOR. In the second query, there is no such number that's less than or equal to 0, so we set it to -1.
To solve this, we will follow these steps −
trie := a new map
Define a function bits() . This will take i
return 32 bit binary representation of i
Define a function insert. This will take i
node := trie
for each c in bits(i), do
node := if c is not in node, insert an empty map inside it
node[2] := i
Define a function query() . This will take i
node := trie
for each c in bits(i), do
rc := c XOR 1
node := node[rc] if exists otherwise node[c]
return node[2]
From the main method do the following −
sort the list A
B := a list of elements in the form (i, x, limit) for each query index i and query values x and limit. Then sort it based on limit
(j, n, ans) := (0, size of A , a list of size same as queries, fill with -1)
for each index i and value x and limit in B, do
while j < n and A[j] <= limit, do
insert(A[j])
j := j + 1
if j is non-zero, then
ans[i] := query(x)
return ans
Example (Python)
Let us see the following implementation to get a better understanding −
class Solution: def solve(self, A, queries): trie = {} def bits(i): return map(int, bin(i)[2:].zfill(32)) def insert(i): node = trie for c in bits(i): node = node.setdefault(c, {}) node[2] = i def query(i): node = trie for c in bits(i): rc = c ^ 1 node = node.get(rc, node.get(c)) return node[2] A.sort() B = sorted([(i, x, limit) for i, (x, limit) in enumerate(queries)], key=lambda x: x[2]) j, n, ans = 0, len(A), [-1] * len(queries) for i, x, limit in B: while j < n and A[j] <= limit: insert(A[j]) j += 1 if j: ans[i] = query(x) return ans ob = Solution() nums = [3, 5, 9] queries = [ [4, 6], [2, 0] ] print(ob.solve(nums, queries))
Input
[3, 5, 9], [[4, 6],[2, 0]]
Output
[3, -1]