-
Notifications
You must be signed in to change notification settings - Fork 154
/
maximum-xor-of-two-numbers-in-an-array.js
93 lines (77 loc) · 1.62 KB
/
maximum-xor-of-two-numbers-in-an-array.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Maximum XOR of Two Numbers in an Array
*
* Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
*
* Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
*
* Could you do this in O(n) runtime?
*
* Example:
*
* Input: [3, 10, 5, 25, 2, 8]
*
* Output: 28
*
* Explanation: The maximum result is 5 ^ 25 = 28.
*/
const INT_SIZE = 32;
class TrieNode {
constructor() {
this.children = {};
this.num = null;
}
}
class Trie {
/**
* @param {number[]} nums
*/
constructor() {
this.root = new TrieNode();
}
/**
* @param {number} num
*/
insert(num) {
let current = this.root;
for (let i = INT_SIZE - 1; i >= 0; i--) {
const bit = (num & ((1 << i) >>> 0)) > 0 ? 1 : 0;
if (!current.children[bit]) {
current.children[bit] = new TrieNode();
}
current = current.children[bit];
}
current.num = num;
}
/**
* @param {number} num
*/
search(num) {
let current = this.root;
for (let i = INT_SIZE - 1; i >= 0; i--) {
const bit = (num & ((1 << i) >>> 0)) > 0 ? 1 : 0;
if (current.children[1 - bit]) {
current = current.children[1 - bit];
} else {
current = current.children[bit];
}
}
return current.num;
}
}
/**
* @param {number[]} nums
* @return {number}
*/
const findMaximumXOR = nums => {
let max = 0;
const trie = new Trie();
trie.insert(nums[0]);
for (let i = 1; i < nums.length; i++) {
const num = trie.search(nums[i]);
max = Math.max(max, num ^ nums[i]);
trie.insert(nums[i]);
}
return max;
};
export default findMaximumXOR;