Maximum Strong Pair XOR II - Bitwise Trie [JS]

Description 

Solution: Bitwise Trie & Two Pointers

Sort nums in asc order.
For each nums[i], move up index j while nums[j] - nums[i] <= nums[i].
Use a bitwise trie to find the maximum bitwise XOR, which is a greedy strategy of taking the opposite bit whenever possible.

n = length of numsm = max(nums[i])
Time Complexity: O(n log(m))
Space Complexity: O(m)

var maximumStrongPairXor = function(nums) {
  nums.sort((a, b) => a - b);
  let n = nums.length, trie = new BitwiseTrie(), maxXor = 0;
  for (let i = 0, j = 0; i < n; i++) {
    if (i > 0) trie.removeNum(nums[i - 1]);
    while (j < n && nums[j] - nums[i] <= nums[i]) {
      trie.addNum(nums[j]);
      j++;
    }
    maxXor = Math.max(maxXor, trie.maxXor(nums[i]));
  } 
  return maxXor;
};

class TrieNode {
  constructor() {
    this.children = Array(2);
    this.num = null;
    this.count = 0;
  }
}

class BitwiseTrie {
  constructor() {
    this.root = new TrieNode();
  }
  addNum(num) {
    let node = this.root;
    for (let i = 20; i >= 0; i--) {
      let bit = (num >> i) & 1; 
      node = node.children;
      if (!node[bit]) node[bit] = new TrieNode();
      node = node[bit];
      node.count++;
    }
    node.num = num;
  }
  removeNum(num) {
    let node = this.root;
    for (let i = 20; i >= 0; i--) {
      let bit = (num >> i) & 1;
      node = node.children;
      node[bit].count--;
      if (node[bit].count <= 0) {
        node[bit] = null;
        break;
      }
      else node = node[bit];
    }
  }
  maxXor(num) {
    let node = this.root;
    for (let i = 20; i >= 0; i--) {
      let bit = (num >> i) & 1, opposite = bit ^ 1;
      node = node.children;
      if (node[opposite]) node = node[opposite];
      else node = node[bit];
    }
    return num ^ node.num;
  }
}

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]