[LeetCode] Maximum XOR With an Element From Array

1707. Maximum XOR With an Element From Array

You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].

The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.

Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.

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
struct Trie{
Trie* next[2];
Trie() {memset(next, 0, sizeof next);}
void insert(int n, int p = 30) {
if(p == -1) return ;
bool bi = n & (1<<p);
if(!next[bi]) next[bi] = new Trie();
next[bi]->insert(n, p - 1);
}
int query(int x, int n, int p = 30, bool exceed = false) {
if(p == -1) return exceed ? 0 : -1;
if(exceed) {
bool nbi = n & (1<<p);

if(next[!nbi])
return (1<<p) ^ next[!nbi]->query(x,n,p-1,true);

return next[nbi]->query(x,n,p-1,true);
} else {
bool xbi = x & (1<<p);
if(xbi) {
int res = -1;
if(next[1]) {
int ans = next[1]->query(x,n,p-1,false);
if(ans != -1) {
bool nbi = n & (1<<p);
res = max(res, ans ^ (nbi ? 0 : (1<<p)) );
}
}
if(next[0]) {
res = max(res, (n & (1<<p)) ^ next[0]->query(x,n,p-1,true));
}
return res;
} else {
if(!next[0]) return -1;
int ans = next[0]->query(x,n,p-1,false);
if(ans != -1) {
ans ^= n & (1<<p);
}
return ans;
}
}
}
};
class Solution {
public:
vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) {
int mi = INT_MAX;
unordered_set<int> A;
vector<int> res;
Trie* t = new Trie();
for(auto& n : nums) {
mi = min(mi,n);
t->insert(n);
A.insert(n);
}
for(auto& q : queries) {
int x = q[0], m = q[1];
if(m < mi) res.push_back(-1);
else {
int ans = t->query(m,x);
if(A.count(m)) ans = max(ans, m ^ x);
res.push_back(ans);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/02/PS/LeetCode/maximum-xor-with-an-element-from-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.