Skip to main content

Maximum XOR With an Element From Array

Problem

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.

Solution Approach

Expected Time complexity: O(nlogn)O(nlogn)

Click - to see solution code
struct Node {
vector<Node*> v;
int val;
Node(int _val) {
v = {NULL, NULL};
val = _val;
}
};

class Solution {
public:
Node* root;

void insert(int n) {
Node* temp = root;
int i = 0;
for (int i = 30; i >= 0; i--) {
int bit = (n & (1 << i));
if (temp->v[bit > 0] == NULL) {
Node* newNode = new Node(bit > 0);
temp->v[bit > 0] = newNode;
}
temp = temp->v[bit ? 1 : 0];
}
}

int query(int n) {
Node* temp = root;
int ans = 0;
for (int i = 30; i >= 0; i--) {
int bit = n & (1ll << i);
if (temp->v[bit == 0] != NULL) {
ans += (1ll << i);
temp = temp->v[bit == 0];
} else
temp = temp->v[bit != 0];
}
return ans;
}

vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) {
for (int i = 0; i < queries.size(); i++) {
queries[i].push_back(i);
swap(queries[i][0], queries[i][1]);
}
sort(queries.begin(), queries.end());
sort(nums.begin(), nums.end());
root = new Node(0);
int i = 0, j = 0;
vector<int> ans(queries.size());
while (j < queries.size()) {
while (i < nums.size() && nums[i] <= queries[j][0]) {
insert(nums[i]);
i++;
}

if (i == 0) {
ans[queries[j][2]] = -1;
} else {
ans[queries[j][2]] = query(queries[j][1]);
}
j++;
}
return ans;
}
};