Approach
Sorting and greedy selection
For Maximum XOR With an Element From Array, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 77 lines of Java from the credited upstream file 1707.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TrieNode {2 public TrieNode[] children = new TrieNode[2];3}4 5class BitTrie {6 public BitTrie(int maxBit) {7 this.maxBit = maxBit;8 }9 10 public void insert(int num) {11 TrieNode node = root;12 for (int i = maxBit; i >= 0; --i) {13 final int bit = (int) (num >> i & 1);14 if (node.children[bit] == null)15 node.children[bit] = new TrieNode();16 node = node.children[bit];17 }18 }19 20 public int getMaxXor(int num) {21 int maxXor = 0;22 TrieNode node = root;23 for (int i = maxBit; i >= 0; --i) {24 final int bit = (int) (num >> i & 1);25 final int toggleBit = bit ^ 1;26 if (node.children[toggleBit] != null) {27 maxXor = maxXor | 1 << i;28 node = node.children[toggleBit];29 } else if (node.children[bit] != null) {30 node = node.children[bit];31 } else { 32 return 0;33 }34 }35 return maxXor;36 }37 38 private int maxBit;39 private TrieNode root = new TrieNode();40}41 42class Solution {43 public int[] maximizeXor(int[] nums, int[][] queries) {44 int[] ans = new int[queries.length];45 Arrays.fill(ans, -1);46 final int maxNumInNums = Arrays.stream(nums).max().getAsInt();47 final int maxNumInQuery = Arrays.stream(queries).mapToInt(query -> query[0]).max().getAsInt();48 final int maxBit = (int) (Math.log(Math.max(maxNumInNums, maxNumInQuery)) / Math.log(2));49 BitTrie bitTrie = new BitTrie(maxBit);50 51 Arrays.sort(nums);52 53 int i = 0; 54 for (IndexedQuery indexedQuery : getIndexedQueries(queries)) {55 final int queryIndex = indexedQuery.queryIndex;56 final int x = indexedQuery.x;57 final int m = indexedQuery.m;58 while (i < nums.length && nums[i] <= m)59 bitTrie.insert(nums[i++]);60 if (i > 0 && nums[i - 1] <= m)61 ans[queryIndex] = bitTrie.getMaxXor(x);62 }63 64 return ans;65 }66 67 private record IndexedQuery(int queryIndex, int x, int m){};68 69 private IndexedQuery[] getIndexedQueries(int[][] queries) {70 IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];71 for (int i = 0; i < queries.length; ++i)72 indexedQueries[i] = new IndexedQuery(i, queries[i][0], queries[i][1]);73 Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::m));74 return indexedQueries;75 }76}77