Maximum XOR With an Element From Array
Each query (x, m) asks: max x XOR a over array elements a ≤ m (or −1 if none). Answer all queries fast.
Intuition
This is problem 421 with a ceiling. Handle it offline: sort the array, and sort queries by their limit m. Sweep queries in increasing m, inserting array elements into the bit-trie only while they are ≤ m. Each query then greedily walks a trie that contains exactly its allowed elements — the constraint dissolves into insertion order.
Approach
Constraint blocks direct reuse
The 421 trie answers 'max XOR with anything'. The a ≤ m filter differs per query, so a static trie over-answers. Rebuilding per query is O(n) each — too slow.
Offline sweep
Sort nums ascending; sort queries by m (remembering original indices). A pointer inserts nums[ptr] while nums[ptr] ≤ m. Trie contents = exactly the eligible elements — no removal ever needed.
Greedy query as before
Walk 30 bits top-down preferring the opposite bit. Empty trie (m below the minimum element) → −1.
Solution & live demo
Edge cases
Nothing inserted yet — answer −1.
Insert both; identical paths are harmless.
Carry each query's original index through the sort.