Skip to content

Commit f75078c

Browse files
committed
Runtime: 603 ms (Top 88.8%) | Memory: 180.29 MB (Top 72.2%)
1 parent 762880c commit f75078c

File tree

1 file changed

+63
-13
lines changed

1 file changed

+63
-13
lines changed

scripts/algorithms/M/Maximum XOR of Two Numbers in an Array/Maximum XOR of Two Numbers in an Array.cpp

+63-13
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,70 @@
1+
// Runtime: 603 ms (Top 88.8%) | Memory: 180.29 MB (Top 72.2%)
2+
13
class Solution {
24
public:
3-
int findMaximumXOR(vector<int>& nums) {
4-
int ans=0,mask=0;
5-
unordered_set<int>st;
6-
for(int i=31;i>=0;i--){
7-
mask|=(1<<i);
8-
int temp=ans|(1<<i);
9-
for (int j = 0; j < nums.size(); j++) {
10-
int num = nums[j] & mask;
11-
if (st.find(temp ^ num)!=st.end()) {
12-
ans = temp;
13-
break;
5+
struct TrieNode {
6+
//trie with max 2 child, not taking any bool or 26 size value because no need
7+
TrieNode* one;
8+
TrieNode* zero;
9+
};
10+
void insert(TrieNode* root, int n) {
11+
TrieNode* curr = root;
12+
for (int i = 31; i >= 0; i--) {
13+
int bit = (n >> i) & 1; //it will find 31st bit and check it is 1 or 0
14+
if (bit == 0) {
15+
if (curr->zero == nullptr) { //if 0 then we will continue filling on zero side
16+
TrieNode* newNode = new TrieNode();
17+
curr->zero = newNode;
18+
}
19+
curr = curr->zero; //increase cur to next zero position
20+
}
21+
else {
22+
//similarly if we get 1
23+
if (curr->one == nullptr) {
24+
TrieNode* newNode = new TrieNode();
25+
curr->one = newNode;
26+
}
27+
curr = curr->one;
28+
}
29+
}
30+
}
31+
int findmax(TrieNode* root, int n) {
32+
TrieNode* curr = root;
33+
int ans = 0;
34+
for (int i = 31; i >= 0; i--) {
35+
int bit = (n >> i) & 1;
36+
if (bit == 1) {
37+
if (curr->zero != nullptr) { //finding complement , if find 1 then we will check on zero side
38+
ans += (1 << i); //push values in ans
39+
curr = curr->zero;
40+
}
41+
else {
42+
curr = curr->one; //if we don't get then go to one's side
1443
}
15-
st.insert(num);
1644
}
17-
st.clear();
45+
else {
46+
//similarly on zero side if we get 0 then we will check on 1 s side
47+
if (curr->one != nullptr) {
48+
ans += (1 << i);
49+
curr = curr->one;
50+
}
51+
else {
52+
curr = curr->zero;
53+
}
54+
}
55+
}
56+
return ans;
57+
}
58+
59+
int findMaximumXOR(vector<int>& nums) {
60+
int n = nums.size();
61+
TrieNode* root = new TrieNode();
62+
int ans = 0;
63+
for (int i = 0; i < n; i++) {
64+
insert(root, nums[i]); //it will make trie by inserting values
65+
}
66+
for (int i = 1; i < n; i++) {
67+
ans = max(ans, findmax(root, nums[i])); //find the necessary complementory values and maximum store
1868
}
1969
return ans;
2070
}

0 commit comments

Comments
 (0)