Problem solution · Java

Maximum XOR With an Element From Array

Maximum XOR With an Element From Array: a Java solution using sorting and greedy selection. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sorting and greedy selection
Source
walkccc LeetCode Solutions
Length
77 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Choose the key that reveals the greedy or grouping structure.
  2. Sort the relevant records by that key.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum XOR With an Element From Array · JavaJava
Use this to learn the idea, then write your own version.
class TrieNode {  public TrieNode[] children = new TrieNode[2];} class BitTrie {  public BitTrie(int maxBit) {    this.maxBit = maxBit;  }   public void insert(int num) {    TrieNode node = root;    for (int i = maxBit; i >= 0; --i) {      final int bit = (int) (num >> i & 1);      if (node.children[bit] == null)        node.children[bit] = new TrieNode();      node = node.children[bit];    }  }   public int getMaxXor(int num) {    int maxXor = 0;    TrieNode node = root;    for (int i = maxBit; i >= 0; --i) {      final int bit = (int) (num >> i & 1);      final int toggleBit = bit ^ 1;      if (node.children[toggleBit] != null) {        maxXor = maxXor | 1 << i;        node = node.children[toggleBit];      } else if (node.children[bit] != null) {        node = node.children[bit];      } else { // There's nothing in the Bit Trie.        return 0;      }    }    return maxXor;  }   private int maxBit;  private TrieNode root = new TrieNode();} class Solution {  public int[] maximizeXor(int[] nums, int[][] queries) {    int[] ans = new int[queries.length];    Arrays.fill(ans, -1);    final int maxNumInNums = Arrays.stream(nums).max().getAsInt();    final int maxNumInQuery = Arrays.stream(queries).mapToInt(query -> query[0]).max().getAsInt();    final int maxBit = (int) (Math.log(Math.max(maxNumInNums, maxNumInQuery)) / Math.log(2));    BitTrie bitTrie = new BitTrie(maxBit);     Arrays.sort(nums);     int i = 0; // nums' index    for (IndexedQuery indexedQuery : getIndexedQueries(queries)) {      final int queryIndex = indexedQuery.queryIndex;      final int x = indexedQuery.x;      final int m = indexedQuery.m;      while (i < nums.length && nums[i] <= m)        bitTrie.insert(nums[i++]);      if (i > 0 && nums[i - 1] <= m)        ans[queryIndex] = bitTrie.getMaxXor(x);    }     return ans;  }   private record IndexedQuery(int queryIndex, int x, int m){};   private IndexedQuery[] getIndexedQueries(int[][] queries) {    IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];    for (int i = 0; i < queries.length; ++i)      indexedQueries[i] = new IndexedQuery(i, queries[i][0], queries[i][1]);    Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::m));    return indexedQueries;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗