Skip to content
Related Articles

Related Articles

Maximize Bitwise XOR of K with two numbers from Array

View Discussion
Improve Article
Save Article
  • Last Updated : 29 Apr, 2022

Given an integer K and an array arr[] of size N, the task is to choose two elements from the array in such a way that the Bitwise XOR of those two with K (i.e. K ⊕ First chosen element ⊕ Second chosen element) is the maximum. 

Note: Any array element can be chosen as many times as possible

Examples:

Input: N = 3, K = 2, arr[]= [1, 2, 3]
Output: 3
Explanation: If we choose one element from the second index 
and another one from the third index, then the XOR of triplet 
will be 2 ^ 2 ^ 3 = 3, which is the maximum possible.

Input: N = 3, K = 7, arr[] = [4, 2, 3]
Output: 7
Explanation: If we choose both the element from the third index,  
then the XOR of triplet will be 7 ^ 3 ^ 3 = 7, which is the maximum possible.

Input: N = 3, K = 3, arr[] = [1, 2, 3]
Output: 3
Explanation: If we choose both the element from the third index,  
then the XOR of triplet will be 3 ^ 3 ^ 3 = 3, which is the maximum possible.

 

Naive Approach: The approach to the problem is to:

Iterate over all the unique pairs in the array and find the xor value of the triplet and keep track of the maximum.

Follow the steps mentioned below to implement the above idea:

  • Use two nested loops for generating all the unique pairs.
  • Find the xor of the each triplets arr[i] ⊕ arr[j] ⊕ K.
  • Find the maximum of xor for each pair.
  • At the end return the maximum xor value obtained.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum Xor
int maxXor(vector<int>& v, int k)
{
    // Here ans will store the maximum xor
    // value possible of the triplet
    int n = v.size(), ans = 0;
 
    // We will try for all (n*(n+1))/2 pairs.
    // And maximize the 'ans'.
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            ans = max(ans, v[i] ^ v[j] ^ k);
        }
    }
    return ans;
}
 
// Driver Code
int main()
{
    int N = 3, K = 2;
    vector<int> arr = { 1, 2, 3 };
 
    // Function call
    cout << maxXor(arr, K);
    return 0;
}


Java




// JAVA code to implement the approach
import java.util.*;
 
class GFG {
 
    // Function to find the maximum Xor
    public static int maxXor(int v[], int k)
    {
 
        // Here ans will store the maximum xor
        // value possible of the triplet
        int n = v.length, ans = 0;
 
        // We will try for all (n*(n+1))/2 pairs.
        // And maximize the 'ans'.
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                ans = Math.max(ans, v[i] ^ v[j] ^ k);
            }
        }
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 3, K = 2;
        int[] arr = new int[] { 1, 2, 3 };
 
        // Function call
        System.out.print(maxXor(arr, K));
    }
}
 
// This code is contributed by Taranpreet


Python3




# Python code to implement the approach
 
# Function to find the maximum Xor
def maxXor(v, k):
   
    # Here ans will store the maximum xor
    # value possible of the triplet
    n, ans = len(v), 0
 
    # We will try for all (n*(n+1))/2 pairs.
    # And maximize the 'ans'.
    for i in range(n):
        for j in range(i, n):
            ans = max(ans, v[i] ^ v[j] ^ k)
    return ans
 
# Driver Code
N, K = 3, 2
arr = [ 1, 2, 3 ]
 
# Function call
print(maxXor(arr, K))
 
# This code is contributed by shinjanpatra


C#




// C# code to implement the approach
using System;
 
class GFG
{
   
    // Function to find the maximum Xor
    static int maxXor(int[] v, int k)
    {
       
        // Here ans will store the maximum xor
        // value possible of the triplet
        int n = v.Length, ans = 0;
 
        // We will try for all (n*(n+1))/2 pairs.
        // And maximize the 'ans'.
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                ans = Math.Max(ans, v[i] ^ v[j] ^ k);
            }
        }
        return ans;
    }
 
    // Driver Code
    public static void Main()
    {
        int N = 3, K = 2;
        int[] arr = { 1, 2, 3 };
 
        // Function call
        Console.Write(maxXor(arr, K));
    }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
        // JavaScript program for the above approach
 
        // Function to find the maximum Xor
        function maxXor(v, k) {
            // Here ans will store the maximum xor
            // value possible of the triplet
            let n = v.length, ans = 0;
 
            // We will try for all (n*(n+1))/2 pairs.
            // And maximize the 'ans'.
            for (let i = 0; i < n; i++) {
                for (let j = i; j < n; j++) {
                    ans = Math.max(ans, v[i] ^ v[j] ^ k);
                }
            }
            return ans;
        }
 
        // Driver Code
 
        let N = 3, K = 2;
        let arr = [1, 2, 3];
 
        // Function call
        document.write(maxXor(arr, K));
 
    // This code is contributed by Potta Lokesh
 
    </script>


Output

3

Time Complexity: O(N * N)
Auxiliary Space: O(1)

Efficient Approach: The problem can be efficiently solved using Trie data structure based on the following idea:

  • To maximize the xor of the triplet iterate over all the elements considering them as the second element. and choose the third element efficiently in such a way that the xor of triplet is maximum possible.
  • Maximize the XOR by choosing the other elements in such a way that the resultant bit is 1 most of the time, and give priority to the MSB first then to the LSB because the contribution of MSB is always greater than the LSB in final decimal value. 
  • For this, traverse from the MSB to LSB and if the bit is set then we will search for 0 so that the resultant bit is 1 and vice versa.
  • Use Trie data structure. Because in order to maximize the xor value, we need to do the prefix search for the complement of that number, which can be done efficiently using trie

Follow the below steps to solve this problem:

  • Firstly add all the elements to the trie.
  • Every bit in a number has 2 possibilities: 0 & 1, So, we have 2 pointers in every Trie Node: 
    • child[0] -> pointing to 0 bit & 
    • child[1] -> pointing to 1 bit.
  • Now insert all the elements into the trie.
    • Use a bitset of size 32 (bitset<32> B) and go from the most significant bit (MSB) to the least significant bit (LSB).
    • Now start at the root of the Trie and check if child[0] or child[1] is present (not NULL), depending upon the current bit B[j] (j ranges from 0 to the total number bit) of the number.
    • If it’s present, go to its child, if not, create a new Node at that child (0 bit or 1 bit) and move to its child.
  • Now traverse the array and consider each element as the second chosen element.
  • Till now the current XOR value of the triplet is K ^ arr[i].
  • Now find the third element using trie such that its xor with current xor is maximum.
    • Start at the root of the Trie and at the MSB of the number (initialize ans = 0 to store the answer).
    • If the current bit is set in the current xor, go to child[0] to check if it’s not NULL. 
      • If it’s not NULL, add 2i-1 to ans (because this bit will be set in the answer), else go to child[1].
    • If it’s not set, go to child[1] to see it’s not NULL. 
      • If it’s not NULL, we add 2i-1 to ans, else we go to child[0].
  • Find the maximum (say maxi) among the maximum possible xor at each index.
  • Return maxi as the answer.

Below is the implementation of the above approach :

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Class for trie data structure
class TrieNode {
public:
    TrieNode* child[2];
 
    TrieNode()
    {
        // For '0' bit.
        this->child[0] = NULL;
        // For '1' bit.
        this->child[1] = NULL;
    }
};
 
TrieNode* newNode;
 
// Function toinsert the elements in trie
void insert(int x)
{
    TrieNode* t = newNode;
 
    // Convert x to bitwise representation
    bitset<32> bs(x);
 
    // Start from the MSB and
    // move towards the LSB
    for (int j = 30; j >= 0; j--) {
        if (!t->child[bs[j]]) {
            t->child[bs[j]]
                = new TrieNode();
        }
        t = t->child[bs[j]];
    }
}
 
// Function to return the max XOR of
// any element x with K
int findMaxXor(int k)
{
    TrieNode* t = newNode;
    bitset<32> bs(k);
 
    // Here 'ans' will store the maximum
    // possible xor corresponding to 'k'
    int ans = 0;
    for (int j = 30; j >= 0; j--) {
 
        // For set bit we go to the bit
        // '0' and for the bit '0' go
        // towards '1', if available
        if (t->child[!bs[j]]) {
            ans += (1 << j), t = t->child[!bs[j]];
        }
        else {
            t = t->child[bs[j]];
        }
    }
    return ans;
}
 
// Function to find maximum possible xor
int maxXor(vector<int>& v, int K)
{
    int n = v.size();
 
    newNode = new TrieNode();
 
    // Insert all the nodes
    for (int i = 0; i < n; i++) {
        insert(v[i]);
    }
 
    // Here 'ans' will store the maximum
    // possible xor value of the triplet
    int ans = 0;
 
    // Try for every option, considering
    // them as the second element
    for (int i = 0; i < n; i++) {
        ans = max(ans, findMaxXor(v[i] ^ K));
    }
 
    return ans;
}
 
// Driver code
int main()
{
    int N = 3, K = 2;
    vector<int> arr = { 1, 2, 3 };
 
    // Function call
    cout << maxXor(arr, K);
    return 0;
}


Output

3

Time Complexity: O(N * logM) where M is the maximum element of the array.
Auxiliary Space: O(logM)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!