Program to find list of elements which are less than limit and XOR is maximum in Python

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.

Problem Understanding

For example, if nums = [3, 5, 9] and queries = [[4, 6], [2, 0]], then the output will be [3, -1]. For the first query, we can use 3 or 5 from nums (both ? 6). 3 ^ 4 = 7 while 5 ^ 4 = 1, so we select 3 which yields the bigger XOR. In the second query, there is no number ? 0, so we return -1.

Algorithm Approach

We use a Trie data structure to efficiently find the maximum XOR. The key steps are ?

  • Build a trie to store binary representations of numbers

  • For each query, insert valid numbers (? limit) into the trie

  • Find the element that gives maximum XOR with the query value

  • Process queries in order of increasing limit for efficiency

Implementation

class Solution:
    def solve(self, nums, queries):
        trie = {}
        
        def bits(i):
            # Convert number to 32-bit binary representation
            return map(int, bin(i)[2:].zfill(32))
        
        def insert(i):
            # Insert number into trie
            node = trie
            for c in bits(i):
                node = node.setdefault(c, {})
            node[2] = i  # Store the actual number
        
        def query(i):
            # Find number that gives maximum XOR with i
            node = trie
            for c in bits(i):
                rc = c ^ 1  # Opposite bit for maximum XOR
                node = node.get(rc, node.get(c))
            return node[2]
        
        # Sort numbers and queries by limit
        nums.sort()
        indexed_queries = sorted([(i, x, limit) for i, (x, limit) in enumerate(queries)], 
                               key=lambda x: x[2])
        
        j, n, ans = 0, len(nums), [-1] * len(queries)
        
        for i, x, limit in indexed_queries:
            # Insert all valid numbers (? limit) into trie
            while j < n and nums[j] <= limit:
                insert(nums[j])
                j += 1
            
            # If any numbers inserted, find maximum XOR
            if j:
                ans[i] = query(x)
        
        return ans

# Example usage
ob = Solution()
nums = [3, 5, 9]
queries = [[4, 6], [2, 0]]
print(ob.solve(nums, queries))

Output

[3, -1]

How It Works

The algorithm uses a binary trie to store numbers in their 32-bit binary form. For each query, it tries to find the opposite bit at each position to maximize XOR. The key optimization is processing queries in order of increasing limits, allowing us to incrementally build the trie.

XOR Maximization with Trie Query: x=4, limit=6 Valid numbers: [3, 5] x = 4: 100 num = 3: 011 ? XOR = 111 (7) num = 5: 101 ? XOR = 001 (1) Trie Structure: root 0 1 Maximum XOR: 3 ^ 4 = 7 Answer: 3

Time Complexity

The time complexity is O(32 × (n + m)) where n is the length of nums and m is the number of queries. The space complexity is O(32 × n) for the trie structure.

Conclusion

This solution efficiently finds maximum XOR values using a binary trie data structure. By processing queries in sorted order of limits, we avoid rebuilding the trie for each query, making the algorithm optimal for multiple queries.

Updated on: 2026-03-25T13:43:31+05:30

253 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements