Open In App

Queries to calculate maximum Bitwise XOR of X with any array element not exceeding M

Improve
Improve
Like Article
Like
Save
Share
Report

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);


Output

3 3 7 

 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);


Output:

3 3 7

Time Complexity: O(N*log N + K*log K)
Auxiliary Space: O(N)



Last Updated : 30 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads