Problem 401006 · hard · Level 04 Non-Linear Data Structures

Tuning Crystals Under a Power Cap

binary trie · bit manipulation · greedy · offline queries · sorting

A radio lab keeps quartz crystals, each labelled with a non-negative integer code in crystals. A tuning request is a pair [signal, cap]. The request may only use a crystal whose code is at most cap, and its quality is signal XOR code (signal ^ code in Python). For every request return the largest quality it can reach, or -1 if no crystal has a code <= cap.

Return the answers as a list in the order the requests were given.

Examples

Input:  crystals = [2, 7, 4, 9], requests = [[5, 4], [5, 9], [0, 1]]
Output: [7, 12, -1]
Explanation: request [5, 4] may use codes 2 and 4: 5 ^ 2 = 7 beats 5 ^ 4 = 1.
[5, 9] may use all four: 5 ^ 9 = 12 is best. [0, 1] has no crystal with code <= 1.

Input:  crystals = [8, 3, 3, 10], requests = [[1, 3], [6, 8], [6, 7]]
Output: [2, 14, 5]
Explanation: the cap is inclusive, so [6, 8] may use code 8: 6 ^ 8 = 14. With cap 7 only code 3 is left: 6 ^ 3 = 5.

Constraints

  • 0 <= len(crystals), len(requests) <= 2 * 10**4
  • 0 <= crystals[i], signal, cap < 2**30
  • Target: about O((n + q) * 30) after sorting; testing every crystal for every request is too slow

Goals

  • Answer maximum-XOR queries greedily with a binary trie
  • Handle an upper bound on the partner by sorting queries and inserting values lazily
  • Detect queries that have no valid partner at all
Starting Python…