Maximum XOR of Two Numbers in an Array LeetCode solution in JavaScript
1var findMaximumXOR = function (nums) {2const trie = {};3const add = (num) => {4let p = trie;5for (let i = 31; i >= 0; i--) {6const isSet = (num >> i) & 1;7if (!p[isSet]) p[isSet] = {};8p = p[isSet];9}10};11const xor = (num) => {12let p = trie;13let ans = 0;14for (let i = 31; i >= 0; i--) {15const isSet = (num >> i) & 1;16const opp = 1 - isSet;17const hasOpp = p[opp];18if (hasOpp) {19ans = ans | (1 << i);20p = p[opp];21} else {22p = p[isSet];23}24}25return ans;26};2728for (let num of nums) {29add(num);30}31let max = 0;32for (let num of nums) {33max = Math.max(max, xor(num));34}35return max;36};