Queries to calculate maximum Bitwise XOR of X with any array element not exceeding M
Last Updated :
30 Mar, 2023
Given an array arr[] consisting of N non-negative integers and a 2D array queries[][] consisting of queries of the type {X, M}, the task for each query is to find the maximum Bitwise XOR of X with any array element whose value is at most M. If it is not possible to find the Bitwise XOR, then print "-1".
Examples:
Input: arr[] = {0, 1, 2, 3, 4}, queries[][] = {{3, 1}, {1, 3}, {5, 6}}
Output: {3, 3, 7}
Explanation:
Query 1: The query is {3, 1}. Maximum Bitwise XOR = 3 ^ 0 = 3.
Query 2: The query is {1, 3}. Maximum Bitwise XOR = 1 ^ 2 = 3.
Query 3: The query is {5, 6}. Maximum Bitwise XOR = 5 ^ 2 = 7.
Input: arr[] = {5, 2, 4, 6, 6, 3}, queries[][] = {{12, 4}, {8, 1}, {6, 3}}
Output: {15, -1, 5}
Naive Approach: The simplest approach to solve the given problem is to traverse the given array for each query {X, M} and print the maximum value of Bitwise XOR of X with an array element with a value at most M. If there doesn't exist any value less than M, then print "-1" for the query.
C++
// C++ program for the above approach
#include <iostream>
#include <vector>
using namespace std;
// Function to find the maximum value of
// Bitwise XOR of X with an array element
// with a value at most M
int findMaxXOR(vector<int>& arr, int X, int M) {
int maxXOR = -1;
// Traversing through the array
for (int i = 0; i < arr.size(); i++) {
// Checking if the array element is less than or equal to M
if (arr[i] <= M) {
// Calculating the maximum XOR value
maxXOR = max(maxXOR, X ^ arr[i]);
}
}
return maxXOR;
}
// Function to solve the problem for multiple queries
void solveQueries(vector<int>& arr,vector<pair<int, int>>& queries) {
// Traversing through each query
for (int i = 0; i < queries.size(); i++) {
// Getting the values of X and M for the current query
int X = queries[i].first;
int M = queries[i].second;
int maxXOR = findMaxXOR(arr, X, M);
cout << maxXOR <<" ";
}
}
// Driver Code
int main() {
std::vector<int> nums = {0, 1, 2, 3, 4};
std::vector<std::pair<int, int>> queries = {{3, 1}, {1, 3}, {5, 6}};
solveQueries(nums, queries);
return 0;
}
// This code is contributed by Vaibhav
Java
import java.util.*;
public class Main {
// Function to find the maximum value of
// Bitwise XOR of X with an array element
// with a value at most M
public static int findMaxXOR(List<Integer> arr, int X, int M) {
int maxXOR = -1;
// Traversing through the array
for (int i = 0; i < arr.size(); i++)
{
// Checking if the array element is less than or equal to M
if (arr.get(i) <= M)
{
// Calculating the maximum XOR value
maxXOR = Math.max(maxXOR, X ^ arr.get(i));
}
}
return maxXOR;
}
// Function to solve the problem for multiple queries
public static void solveQueries(List<Integer> arr, List<Pair<Integer, Integer>> queries) {
// Traversing through each query
for (int i = 0; i < queries.size(); i++)
{
// Getting the values of X and M for the current query
int X = queries.get(i).getKey();
int M = queries.get(i).getValue();
int maxXOR = findMaxXOR(arr, X, M);
System.out.print(maxXOR + " ");
}
}
// Driver Code
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4));
List<Pair<Integer, Integer>> queries = new ArrayList<>(Arrays.asList(new Pair<>(3, 1), new Pair<>(1, 3), new Pair<>(5, 6)));
solveQueries(nums, queries);
}
}
class Pair<T, U> {
private T key;
private U value;
public Pair(T key, U value) {
this.key = key;
this.value = value;
}
public T getKey() {
return key;
}
public U getValue() {
return value;
}
}
Python3
# Python3 program for the above approach
# Function to find the maximum value of
# Bitwise XOR of X with an array element
# with a value at most M
def findMaxXOR(arr, X, M):
maxXOR = -1
# Traversing through the array
for i in range(len(arr)):
# Checking if the array element is less than or equal to M
if arr[i] <= M:
# Calculating the maximum XOR value
maxXOR = max(maxXOR, X ^ arr[i])
return maxXOR
# Function to solve the problem for multiple queries
# Traversing through each query
def solveQueries(arr, queries):
for i in range(len(queries)):
# Getting the values of X and M for the current query
X = queries[i][0]
M = queries[i][1]
maxXOR = findMaxXOR(arr, X, M)
print(maxXOR, end=" ")
print()
# Driver Code
nums = [0, 1, 2, 3, 4]
queries = [(3, 1), (1, 3), (5, 6)]
solveQueries(nums, queries)
# This code is contributed by phasing17
C#
using System;
using System.Collections.Generic;
class Program {
// Function to find the maximum value of
// Bitwise XOR of X with an array element
// with a value at most M
static int findMaxXOR(List<int> arr, int X, int M)
{
int maxXOR = -1;
// Traversing through the array
for (int i = 0; i < arr.Count; i++) {
// Checking if the array element is less than or
// equal to M
if (arr[i] <= M) {
// Calculating the maximum XOR value
maxXOR = Math.Max(maxXOR, X ^ arr[i]);
}
}
return maxXOR;
}
// Function to solve the problem for multiple queries
static void solveQueries(List<int> arr,
List<(int, int)> queries)
{
// Traversing through each query
for (int i = 0; i < queries.Count; i++) {
// Getting the values of X and M for the current
// query
int X = queries[i].Item1;
int M = queries[i].Item2;
int maxXOR = findMaxXOR(arr, X, M);
Console.Write(maxXOR + " ");
}
}
// Driver Code
static void Main()
{
List<int> nums = new List<int>{ 0, 1, 2, 3, 4 };
List<(int, int)> queries
= new List<(int, int)>{ (3, 1), (1, 3),
(5, 6) };
solveQueries(nums, queries);
}
}
// This code is contributed by Prajwal Kandekar
JavaScript
// Function to find the maximum value of
// Bitwise XOR of X with an array element
// with a value at most M
function findMaxXOR(arr, X, M) {
let maxXOR = -1;
// Traversing through the array
for (let i = 0; i < arr.length; i++) {
// Checking if the array element is less than or equal to M
if (arr[i] <= M) {
// Calculating the maximum XOR value
maxXOR = Math.max(maxXOR, X ^ arr[i]);
}
}
return maxXOR;
}
// Function to solve the problem for multiple queries
function solveQueries(arr, queries) {
let result = "";
// Traversing through each query
for (let i = 0; i < queries.length; i++) {
// Getting the values of X and M for the current query
let X = queries[i][0];
let M = queries[i][1];
let maxXOR = findMaxXOR(arr, X, M);
result += maxXOR + " ";
}
console.log(result.trim());
}
// Driver Code
let nums = [0, 1, 2, 3, 4];
let queries = [[3, 1], [1, 3], [5, 6]];
solveQueries(nums, queries);
Time Complexity: O(N*Q)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using the Trie data structure to store all the elements having values at most M. Therefore, the problem reduces to finding the maximum XOR of two elements in an array. Follow the steps below to solve the problem:
- Initialize a variable, say index, to traverse the array.
- Initialize an array, say ans[], that stores the result for each query.
- Initialize an auxiliary array, say temp[][3], and store all the queries in it with the index of each query.
- Sort the given array temp[] on the basis of the second parameter, i.e. temp[1](= M).
- Sort the given array arr[] in ascending order.
- Traverse the array temp[] and for each query {X, M, idx}, perform the following steps:
- Iterate until the value of index is less than N and arr[index] is at most M or not. If found to be true, then insert that node as the binary representation of N and increment index.
- After completing the above steps, if the value of index is non-zero, then find the node with value X in the Trie(say result) and update the maximum value for the current query as result. Otherwise, update the maximum value for the current query as "-1".
- After completing the above steps, print the array ans[] as the resultant maximum values for each query.
Below is the implementation of the above approach:
C++14
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Trie Node Class
class TrieNode {
public:
TrieNode() {
nums[0] = nums[1] = nullptr;
prefixValue = 0;
}
TrieNode *nums[2];
int prefixValue;
};
class Solution {
public:
// Function to find the maximum XOR
// of X with any array element <= M
// for each query of the type {X, M}
void maximizeXor(std::vector<int>& nums,
std::vector<std::pair<int, int>>& queries) {
int queriesLength = queries.size();
std::vector<int> ans(queriesLength);
std::vector<std::vector<int>> temp(queriesLength, std::vector<int>(3));
// Stores the queries
for (int i = 0; i < queriesLength; i++) {
temp[i][0] = queries[i].first;
temp[i][1] = queries[i].second;
temp[i][2] = i;
}
// Sort the query
std::sort(temp.begin(), temp.end(),
[](const auto& a, const auto& b) { return a[1] < b[1]; });
int index = 0;
// Sort the array
std::sort(nums.begin(), nums.end());
TrieNode *root = new TrieNode();
// Traverse the given query
for (const auto& query : temp) {
// Traverse the array nums[]
while (index < nums.size() && nums[index] <= query[1]) {
// Insert the node into the Trie
insert(root, nums[index]);
index++;
}
// Stores the resultant
// maximum value
int tempAns = -1;
// Find the maximum value
if (index != 0) {
// Search the node in the Trie
tempAns = search(root, query[0]);
}
// Update the result
// for each query
ans[query[2]] = tempAns;
}
// Print the answer
for (auto num : ans) {
cout << num << " ";
}
}
// Function to insert the
// root in the trieNode
void insert(TrieNode *root, int n) {
TrieNode *node = root;
// Iterate from 31 to 0
for (int i = 31; i >= 0; i--) {
// Find the bit at i-th position
int bit = (n >> i) & 1;
if (!node->nums[bit]) {
node->nums[bit] = new TrieNode();
}
node = node->nums[bit];
}
// Update the value
node->prefixValue = n;
}
// Function to search the root
// with the value and perform
// the Bitwise XOR with N
int search(TrieNode *root, int n) {
TrieNode *node = root;
// Iterate from 31 to 0
for (int i = 31; i >= 0; i--) {
// Find the bit at ith
// position
int bit = (n >> i) & 1;
int requiredBit = bit == 1 ? 0 : 1;
if (node->nums[requiredBit]) {
node = node->nums[requiredBit];
} else {
node = node->nums[bit];
}
}
// Return the prefixvalue XORed
// with N
return node->prefixValue ^ n;
}
};
// Driver Code
int main() {
Solution sol;
std::vector<int> nums = {0, 1, 2, 3, 4};
std::vector<std::pair<int, int>> queries = {{3, 1}, {1, 3}, {5, 6}};
sol.maximizeXor(nums, queries);
}
// This code is contributed by Aman Kumar.
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
// Trie Node Class
class TrieNode {
TrieNode nums[] = new TrieNode[2];
int prefixValue;
}
class sol {
// Function to find the maximum XOR
// of X with any array element <= M
// for each query of the type {X, M}
public void maximizeXor(
int[] nums, int[][] queries)
{
int queriesLength = queries.length;
int[] ans = new int[queriesLength];
int[][] temp = new int[queriesLength][3];
// Stores the queries
for (int i = 0; i < queriesLength; i++) {
temp[i][0] = queries[i][0];
temp[i][1] = queries[i][1];
temp[i][2] = i;
}
// Sort the query
Arrays.sort(temp,
(a, b) -> {
return a[1]
- b[1];
});
int index = 0;
// Sort the array
Arrays.sort(nums);
TrieNode root = new TrieNode();
// Traverse the given query
for (int query[] : temp) {
// Traverse the array nums[]
while (index < nums.length
&& nums[index]
<= query[1]) {
// Insert the node into the Trie
insert(root, nums[index]);
index++;
}
// Stores the resultant
// maximum value
int tempAns = -1;
// Find the maximum value
if (index != 0) {
// Search the node in the Trie
tempAns = search(root,
query[0]);
}
// Update the result
// for each query
ans[query[2]] = tempAns;
}
// Print the answer
for (int num : ans) {
System.out.print(num + " ");
}
}
// Function to insert the
// root in the trieNode
public void insert(TrieNode root,
int n)
{
TrieNode node = root;
// Iterate from 31 to 0
for (int i = 31; i >= 0; i--) {
// Find the bit at i-th position
int bit = (n >> i) & 1;
if (node.nums[bit] == null) {
node.nums[bit]
= new TrieNode();
}
node = node.nums[bit];
}
// Update the value
node.prefixValue = n;
}
// Function to search the root
// with the value and perform
// the Bitwise XOR with N
public int search(TrieNode root,
int n)
{
TrieNode node = root;
// Iterate from 31 to 0
for (int i = 31; i >= 0; i--) {
// Find the bit at ith
// position
int bit = (n >> i) & 1;
int requiredBit = bit
== 1
? 0
: 1;
if (node.nums[requiredBit]
!= null) {
node = node.nums[requiredBit];
}
else {
node = node.nums[bit];
}
}
// Return the prefixvalue XORed
// with N
return node.prefixValue ^ n;
}
}
class GFG {
// Driver Code
public static void main(String[] args)
{
sol tt = new sol();
int[] nums = { 0, 1, 2, 3, 4 };
int[][] queries = { { 3, 1 },
{ 1, 3 },
{ 5, 6 } };
tt.maximizeXor(nums, queries);
}
}
Python3
# Python3 code for the above approach
class TrieNode:
def __init__(self):
self.nums = [None, None]
self.prefixValue = 0
class Solution:
def maximizeXor(self, nums, queries):
queriesLength = len(queries)
ans = [0] * queriesLength
temp = [[0, 0, 0] for _ in range(queriesLength)]
# Stores the queries
for i in range(queriesLength):
temp[i][0] = queries[i][0]
temp[i][1] = queries[i][1]
temp[i][2] = i
# Sort the query
temp.sort(key=lambda x: x[1])
index = 0
# Sort the array
nums.sort()
root = TrieNode()
# Traverse the given query
for query in temp:
# Traverse the array nums[]
while index < len(nums) and nums[index] <= query[1]:
# Insert the node into the Trie
self.insert(root, nums[index])
index += 1
# Stores the resultant
# maximum value
tempAns = -1
# Find the maximum value
if index != 0:
# Search the node in the Trie
tempAns = self.search(root, query[0])
# Update the result
# for each query
ans[query[2]] = tempAns
# Print the answer
for num in ans:
print(num, end=' ')
print()
# Function to insert the root in the trieNode
def insert(self, root, n):
node = root
# Iterate from 31 to 0
for i in range(31, -1, -1):
# Find the bit at i-th position
bit = (n >> i) & 1
if node.nums[bit] is None:
node.nums[bit] = TrieNode()
node = node.nums[bit]
# Update the value
node.prefixValue = n
# Function to search the root
# with the value and perform
# the Bitwise XOR with N
def search(self, root, n):
node = root
# Iterate from 31 to 0
for i in range(31, -1, -1):
# Find the bit at ith position
bit = (n >> i) & 1
requiredBit = 0 if bit == 1 else 1
if node.nums[requiredBit] is not None:
node = node.nums[requiredBit]
else:
node = node.nums[bit]
# Return the prefixvalue XORed
# with N
return node.prefixValue ^ n
def main():
sol = Solution()
nums = [0, 1, 2, 3, 4]
queries = [[3, 1], [1, 3], [5, 6]]
sol.maximizeXor(nums, queries)
if __name__ == '__main__':
main()
# This code is contributed by Potta Lokesh
C#
using System;
using System.Linq;
// Trie Node Class
class TrieNode
{
public TrieNode[] nums = new TrieNode[2];
public int prefixValue;
}
class Solution
{
// Function to find the maximum XOR
// of X with any array element <= M
// for each query of the type {X, M}
public void MaximizeXor(int[] nums, int[][] queries)
{
int queriesLength = queries.Length;
int[] ans = new int[queriesLength];
int[][] temp = new int[queriesLength][];
// Stores the queries
for (int i = 0; i < queriesLength; i++)
{
temp[i] = new int[3];
temp[i][0] = queries[i][0];
temp[i][1] = queries[i][1];
temp[i][2] = i;
}
// Sort the query
Array.Sort(temp, (a, b) => a[1] - b[1]);
int index = 0;
// Sort the array
Array.Sort(nums);
TrieNode root = new TrieNode();
// Traverse the given query
foreach (var query in temp)
{
// Traverse the array nums[]
while (index < nums.Length && nums[index] <= query[1])
{
// Insert the node into the Trie
Insert(root, nums[index]);
index++;
}
// Stores the resultant
// maximum value
int tempAns = -1;
// Find the maximum value
if (index != 0)
{
// Search the node in the Trie
tempAns = Search(root, query[0]);
}
// Update the result
// for each query
ans[query[2]] = tempAns;
}
foreach (var num in ans)
{
// Print the answer
Console.Write(num + " ");
}
}
// Function to insert the
// root in the trieNode
public void Insert(TrieNode root, int n)
{
TrieNode node = root;
// Iterate from 31 to 0
for (int i = 31; i >= 0; i--)
{
// Find the bit at i-th position
int bit = (n >> i) & 1;
if (node.nums[bit] == null)
{
node.nums[bit] = new TrieNode();
}
node = node.nums[bit];
}
// Update the value
node.prefixValue = n;
}
// Function to search the root
// with the value and perform
// the Bitwise XOR with N
public int Search(TrieNode root, int n)
{
TrieNode node = root;
// Iterate from 31 to 0
for (int i = 31; i >= 0; i--)
{
// Find the bit at ith
// position
int bit = (n >> i) & 1;
int requiredBit = bit == 1 ? 0 : 1;
if (node.nums[requiredBit] != null)
{
node = node.nums[requiredBit];
}
else
{
node = node.nums[bit];
}
}
// Return the prefixvalue XORed
// with N
return node.prefixValue ^ n;
}
}
class Program
{
// Driver Code
static void Main(string[] args)
{
Solution solution = new Solution();
int[] nums = { 0, 1, 2, 3, 4 };
int[][] queries = {
new int[] { 3, 1 },
new int[] { 1, 3 },
new int[] { 5, 6 }
};
solution.MaximizeXor(nums, queries);
}
}
JavaScript
// Trie Node Class
class TrieNode {
constructor() {
this.nums = [null, null];
this.prefixValue = 0;
}
}
class Solution {
// Function to find the maximum XOR
// of X with any array element <= M
// for each query of the type {X, M}
maximizeXor(nums, queries) {
const queriesLength = queries.length;
const ans = Array(queriesLength);
const temp = Array.from({ length: queriesLength }, () => Array(3));
// Stores the queries
for (let i = 0; i < queriesLength; i++) {
temp[i][0] = queries[i][0];
temp[i][1] = queries[i][1];
temp[i][2] = i;
}
// Sort the query
temp.sort((a, b) => a[1] - b[1]);
let index = 0;
// Sort the array
nums.sort((a, b) => a - b);
const root = new TrieNode();
// Traverse the given query
for (const query of temp) {
while (index < nums.length && nums[index] <= query[1]) {
this.insert(root, nums[index]);
index++;
}
let tempAns = -1;
// Find the maximum value
if (index != 0) {
tempAns = this.search(root, query[0]);
}
// Update the result
// for each query
ans[query[2]] = tempAns;
}
// Print the answer
console.log(ans.join(" "));
}
// Function to insert the
// root in the trieNode
insert (root, n)
{
let node = root;
// Iterate from 31 to 0
for (let i = 31; i >= 0; i--)
{
// Find the bit at i-th position
const bit = (n >> i) & 1;
if (!node.nums[bit])
{
node.nums[bit] = new TrieNode ();
}
node = node.nums[bit];
}
// Update the value
node.prefixValue = n;
}
// Function to search the root
// with the value and perform
// the Bitwise XOR with N
search (root, n)
{
let node = root;
// Iterate from 31 to 0
for (let i = 31; i >= 0; i--)
{
// Find the bit at ith
// position
const bit = (n >> i) & 1;
const requiredBit = bit == 1 ? 0 : 1;
if (node.nums[requiredBit])
{
node = node.nums[requiredBit];
}
else
{
node = node.nums[bit];
}
}
// Return the prefixvalue XORed
// with N
return node.prefixValue ^ n;
}
}
const sol = new Solution();
const nums = [0, 1, 2, 3, 4];
const queries = [[3, 1], [1, 3], [5, 6]];
sol.maximizeXor(nums, queries);
Time Complexity: O(N*log N + K*log K)
Auxiliary Space: O(N)
Similar Reads
Count of N-size maximum sum Arrays with elements in range [0, 2^K â 1] and Bitwise AND equal to 0
Given two positive integers N and K, the task is to find the number of arrays of size N such that each array element lies over the range [0, 2K - 1] with the maximum sum of array element having Bitwise AND of all array elements 0. Examples: Input: N = 2 K = 2Output: 4Explanation:The possible arrays
5 min read
Maximum XOR Queries With an Element From Array
Given an array arr[] of size n containing non-negative integers and also given a list of q queries in a 2D array queries[][], where each query is of the form [xi, mi]. For each query, you need to find the maximum value of (xi XOR arr[j]) such that arr[j] is less than or equal to mi.In simple terms,
15+ min read
Sum of Bitwise XOR of each array element with all other array elements
Given an array arr[] of length N, the task for every array element is to print the sum of its Bitwise XOR with all other array elements. Examples: Input: arr[] = {1, 2, 3}Output: 5 4 3Explanation:For arr[0]: arr[0] ^ arr[0] + arr[0] ^ arr[1] + arr[0] ^ arr[2] = 1^1 + 1^2 + 1^3 = 0 + 3 + 2 = 5For arr
9 min read
Minimize Bitwise XOR of array elements with 1 required to make sum of array at least K
Given an array arr[] consisting of N positive integers and a positive integer K, the task is to count minimum Bitwise XOR of array elements with 1 required such that the sum of the array is at least K. Examples: Input: arr[] = {0, 1, 1, 0, 1}, K = 4Output: 1Explanation: Performing Bitwise XOR of arr
6 min read
Maximize total set bits of elements in N sized Array with sum M
Given two integers N and M denoting the size of an array and the sum of the elements of the array, the task is to find the maximum possible count of total set bits of all the elements of the array such that the sum of the elements is M. Examples: Input: N = 1, M = 15Output: 4Explanation: Since N =1,
8 min read
Count pairs with bitwise XOR exceeding bitwise AND from a given array
Given an array, arr[] of size N, the task is to count the number of pairs from the given array such that the bitwise AND(&) of each pair is less than its bitwise XOR(^). Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 8Explanation: Pairs that satisfy the given conditions are: (1 & 2) < (
10 min read
Find element with the maximum set bits in an array
Given an array arr[]. The task is to find an element from arr[] which has the maximum count of set bits.Examples: Input: arr[] = {10, 100, 1000, 10000} Output: 1000 Binary(10) = 1010 (2 set bits) Binary(100) = 1100100 (3 set bits) Binary(1000) = 1111101000 (6 set bits) Binary(10000) = 10011100010000
5 min read
Smallest element with K set bits such that sum of Bitwise AND of each array element with K is maximum
Given an array arr[] consisting of N integers and integer K, the task is to find the smallest integer X with exactly K set bits such that the sum of Bitwise AND of X with every array element arr[i] is maximum. Examples: Input: arr[] = {3, 4, 5, 1}, K = 1Output: 4Explanation: Consider the value of X
8 min read
Count N-length arrays of made up of elements not exceeding 2^K - 1 having maximum sum and Bitwise AND equal to 0
Given two integers N and K, the task is to find the number of N-length arrays that satisfies the following conditions: The sum of the array elements is maximum possible.For every possible value of i ( 1 ? i ? N ), the ith element should lie between 0 and 2K - 1.Also, Bitwise AND of all the array ele
7 min read
Count of even and odd set bit with array element after XOR with K
Given an array arr[] and a number K. The task is to find the count of the element having odd and even number of the set-bit after taking XOR of K with every element of the given arr[].Examples: Input: arr[] = {4, 2, 15, 9, 8, 8}, K = 3 Output: Even = 2, Odd = 4 Explanation: The binary representation
9 min read