Maximum XOR of Two Numbers in an Array LeetCode solution in JavaScript

1
var findMaximumXOR = function (nums) {
2
const trie = {};
3
const add = (num) => {
4
let p = trie;
5
for (let i = 31; i >= 0; i--) {
6
const isSet = (num >> i) & 1;
7
if (!p[isSet]) p[isSet] = {};
8
p = p[isSet];
9
}
10
};
11
const xor = (num) => {
12
let p = trie;
13
let ans = 0;
14
for (let i = 31; i >= 0; i--) {
15
const isSet = (num >> i) & 1;
16
const opp = 1 - isSet;
17
const hasOpp = p[opp];
18
if (hasOpp) {
19
ans = ans | (1 << i);
20
p = p[opp];
21
} else {
22
p = p[isSet];
23
}
24
}
25
return ans;
26
};
27

28
for (let num of nums) {
29
add(num);
30
}
31
let max = 0;
32
for (let num of nums) {
33
max = Math.max(max, xor(num));
34
}
35
return max;
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0