Maximize Bitwise XOR of K with two numbers from Array
Last Updated :
21 Feb, 2023
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>
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;
}
Java
//Java code to implement the approach
import java.util.BitSet;
import java.util.Vector;
// Class for trie data structure
public class Trie {
static class TrieNode {
TrieNode[] child = new TrieNode[2];
TrieNode() {
// For '0' bit.
this.child[0] = null;
// For '1' bit.
this.child[1] = null;
}
}
static TrieNode newNode;
// Function toinsert the elements in trie
static void insert(int x) {
TrieNode t = newNode;
// Convert x to bitwise representation
BitSet bs = BitSet.valueOf(new long[] { x });
// Start from the MSB and
// move towards the LSB
for (int j = 30; j >= 0; j--) {
if (t.child[bs.get(j) ? 1 : 0] == null) {
t.child[bs.get(j) ? 1 : 0] = new TrieNode();
}
t = t.child[bs.get(j) ? 1 : 0];
}
}
// Function to return the max XOR of
// any element x with K
static int findMaxXor(int k) {
TrieNode t = newNode;
BitSet bs = BitSet.valueOf(new long[] { 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.get(j) ? 0 : 1] != null) {
ans += (1 << j);
t = t.child[bs.get(j) ? 0 : 1];
} else {
t = t.child[bs.get(j) ? 1 : 0];
}
}
return ans;
}
// Function to find maximum possible xor
static int maxXor(Vector<Integer> v, int K) {
int n = v.size();
newNode = new TrieNode();
// Insert all the nodes
for (int i = 0; i < n; i++) {
insert(v.get(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 = Math.max(ans, findMaxXor(v.get(i) ^ K));
}
return ans;
}
// Driver code
public static void main(String[] args) {
int N = 3, K = 2;
Vector<Integer> arr = new Vector<>();
arr.add(1);
arr.add(2);
arr.add(3);
// Function call
System.out.println(maxXor(arr, K));
}
}
// This code is contributed by Aman Kumar
Python3
from typing import List
class TrieNode:
def __init__(self):
# For '0' bit.
self.child = [None, None]
def insert(root: TrieNode, x: int) -> None:
# Start from the MSB and move towards the LSB
for j in range(30, -1, -1):
# Convert x to bitwise representation
bit = (x >> j) & 1
if root.child[bit] is None:
root.child[bit] = TrieNode()
root = root.child[bit]
def findMaxXor(root: TrieNode, k: int) -> int:
# Here 'ans' will store the maximum possible xor corresponding to 'k'
ans = 0
# Start from the MSB and move towards the LSB
for j in range(30, -1, -1):
# Convert k to bitwise representation
bit = (k >> j) & 1
# For set bit, we go to the bit '0' and for the bit '0' go towards '1', if available
if root.child[1-bit] is not None:
ans += (1 << j)
root = root.child[1-bit]
else:
root = root.child[bit]
return ans
def maxXor(arr: List[int], k: int) -> int:
n = len(arr)
root = TrieNode()
# Insert all the nodes
for i in range(n):
insert(root, arr[i])
# Here 'ans' will store the maximum possible xor value of the triplet
ans = 0
# Try for every option, considering them as the second element
for i in range(n):
ans = max(ans, findMaxXor(root, arr[i] ^ k))
return ans
if __name__ == '__main__':
arr = [1, 2, 3]
K = 2
# Function call
print(maxXor(arr, K))
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class Trie
{
private class TrieNode
{
public TrieNode[] child = new TrieNode[2];
public TrieNode()
{
// For '0' bit.
this.child[0] = null;
// For '1' bit.
this.child[1] = null;
}
}
private static TrieNode newNode;
// Function to insert the elements in trie
private static void Insert(int x)
{
TrieNode t = newNode;
// Convert x to bitwise representation
BitArray bs = new BitArray(new int[] { x });
// Start from the MSB and move towards the LSB
for (int j = 30; j >= 0; j--)
{
if (t.child[bs.Get(j) ? 1 : 0] == null)
{
t.child[bs.Get(j) ? 1 : 0] = new TrieNode();
}
t = t.child[bs.Get(j) ? 1 : 0];
}
}
// Function to return the max XOR of any element x with K
private static int FindMaxXor(int k)
{
TrieNode t = newNode;
BitArray bs = new BitArray(new int[] { 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.Get(j) ? 0 : 1] != null)
{
ans += (1 << j);
t = t.child[bs.Get(j) ? 0 : 1];
}
else
{
t = t.child[bs.Get(j) ? 1 : 0];
}
}
return ans;
}
// Function to find maximum possible XOR
public static int MaxXor(List<int> v, int K)
{
int n = v.Count;
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 = Math.Max(ans, FindMaxXor(v[i] ^ K));
}
return ans;
}
// Driver code
public static void Main()
{
int N = 3, K = 2;
List<int> arr = new List<int> { 1, 2, 3 };
// Function call
Console.WriteLine(MaxXor(arr, K));
}
}
JavaScript
// javascript code to implement the approach
// Class for trie data structure
class TrieNode {
constructor()
{
this.child = new Array(2);
this.child[0] = null;
this.child[1] = null;
}
}
let newNode = null;
// Function toinsert the elements in trie
function insert(x)
{
let t = newNode;
// Convert x to bitwise representation
let bs = x.toString(2);
for(let i = bs.length; i < 32; i++){
bs = bs + '0';
}
// Start from the MSB and
// move towards the LSB
for (let j = 30; j >= 0; j--) {
let index = bs[j].charCodeAt(0) - '0'.charCodeAt(0);
if (t.child[index] == null) {
t.child[index] = new TrieNode();
}
t = t.child[index];
}
}
// Function to return the max XOR of
// any element x with K
function findMaxXor(k)
{
let t = newNode;
let bs = k.toString(2);
for(let i = bs.length; i < 32; i++){
bs = bs + '0';
}
// Here 'ans' will store the maximum
// possible xor corresponding to 'k'
let ans = 0;
for (let j = 30; j >= 0; j--) {
// For set bit we go to the bit
// '0' and for the bit '0' go
// towards '1', if available
let index = bs[j].charCodeAt(0) - '0'.charCodeAt(0);
let nindex;
if(index == 0) nindex = 1;
else nindex = 0;
if (t.child[nindex]) {
ans = ans + (1 << j);
t = t.child[nindex];
}
else {
t = t.child[index];
}
}
return ans;
}
// Function to find maximum possible xor
function maxXor(v, K)
{
let n = v.length;
newNode = new TrieNode();
// Insert all the nodes
for (let i = 0; i < n; i++) {
insert(v[i]);
}
// Here 'ans' will store the maximum
// possible xor value of the triplet
let ans = 0;
// Try for every option, considering
// them as the second element
for (let i = 0; i < n; i++) {
ans = Math.max(ans, findMaxXor(v[i]^K));
}
return ans;
}
// Driver code
let N = 3;
let K = 2;
let arr = [ 1, 2, 3 ];
console.log(maxXor(arr, K));
// The code is contributed by Nidhi goel.
Time Complexity: O(N * logM) where M is the maximum element of the array.
Auxiliary Space: O(logM)
Similar Reads
Maximize number of elements from Array with sum at most K
Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. Examples: Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 1
6 min read
Maximum XOR of Two Numbers in an Array
Given an array arr[] of non-negative integers. The task is to find the maximum possible XOR of any two elements of the array.Example: Input: arr[] = [26, 100, 25, 13, 4, 14]Output: 126 Explanation: XOR of 26 ^ 100 = 126, which is the maximum possible XOR.Input: arr[] = [1, 2, 3, 4, 5, 6, 7]Output: 7
15 min read
Maximize sum of three numbers by performing bitwise XOR
Given three integers A, B, and C. the task is to find the maximum possible sum of three numbers when you are allowed to perform the following operation any number of times (possibly zero): Choose any integer X such that X ? max( A, B, C ), and replace A with A^X, B with B^X, and C with C^X. (Here ^
5 min read
Maximize the bitwise OR of an array
Given an array of N integers. The bitwise OR of all the elements of the array has to be maximized by performing one task. The task is to multiply any element of the array at-most k times with a given integer x.Examples : Input: a = {1, 1, 1}, k = 1, x = 2 Output: 3 Explanation: Any possible choice o
7 min read
Maximum and minimum sum of Bitwise XOR of pairs from an array
Given an array arr[] of size N, the task is to find the maximum and minimum sum of Bitwise XOR of all pairs from an array by splitting the array into N / 2 pairs. Examples: Input: arr[] = {1, 2, 3, 4}Output: 6 10Explanation:Bitwise XOR of the all possible pair splits are as follows:(1, 2), (3, 4) â
11 min read
Minimizing Bitwise-OR with XOR Operation on an Array
Given an array arr[] of non-negative integers where arr[i] >= 0, the task is to select a non-negative integer 'k' and perform the bitwise-XOR operation on every element of the array with 'k' (i.e., XOR0 = arr[0] ^ k, XOR1 = arr[1] ^ k, and so on). The objective is to minimize the bitwise-OR of th
9 min read
Maximize sum of XOR of each element of Array with partition number
Given an array arr of positive integers of size N, the task is to split the array into 3 partitions, such that the sum of bitwise XOR of each element of the array with its partition number is maximum. Examples: Input: arr[] = { 2, 4, 7, 1, 8, 7, 2 }Output: First partition: 2 4 7 1 8Second partition:
9 min read
Number whose sum of XOR with given array range is maximum
You are given a sequence of N integers and Q queries. In each query, you are given two parameters L and R. You have to find the smallest integer X such that 0 <= X < 2^31 and the sum of XOR of x with all elements in range [L, R] is maximum possible.Examples : Input : A = {20, 11, 18, 2, 13} Th
15+ min read
Maximum XOR of Two Numbers in an Array | Set 2
Given an array arr[] consisting of N integers, the task is to find the maximum Bitwise XOR from all the possible pairs in the given array. Examples: Input: arr[] = {25, 10, 2, 8, 5, 3}Output: 28Explanation:The maximum result is 5^25 = 28. Input: arr[] = {1, 2, 3, 4, 5, 6, 7}Output: 7Explanation:The
12 min read
Maximum XOR using K numbers from 1 to n
Given a positive integer n and k. Find maximum xor of 1 to n using at most k numbers. Xor sum of 1 to n is defined as 1 ^ 2 ^ 3 ^ ... ^ n.Examples : Input : n = 4, k = 3 Output : 7 Explanation Maximum possible xor sum is 1 ^ 2 ^ 4 = 7. Input : n = 11, k = 1 Output : 11 Explanation Maximum Possible x
6 min read