Maximum and minimum sum of Bitwise XOR of pairs from an array
Last Updated :
10 Nov, 2021
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 10
Explanation:
Bitwise XOR of the all possible pair splits are as follows:
(1, 2), (3, 4) → 3 + 7 =10.
(1, 3), (2, 4) → 2 + 6 = 8.
(1, 4), (2, 3) → 5 + 1 = 6.
Therefore, the maximum sum and minimum sums are 10 and 6 respectively.
Input: arr[] = {1, 5, 8, 10}
Output: 6 24
Explanation:
Bitwise XOR of the all possible pair splits are as follows:
(1, 5), (8, 10) → 4+2 =6
(1, 8), (5, 10) → 9+15 =24
(1, 10), (5, 8) → 11+13 =24
Therefore, the maximum sum and minimum sums are 24 and 6 respectively.
Naive Approach: The simplest approach is to generate every possible permutation of N/2 pairs from the arr[] and calculate the sum of their respective Bitwise XORs. Finally, print the maximum and the minimum sum of Bitwise XORs obtained.
Time Complexity: O(N*N!)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to store the Bitwise XOR of all unique pairs (i, j) in an array and sort it in ascending order. Now, to get the minimum possible sum, follow the steps below to solve the problem:
- Initialize a vector V to store the Bitwise XOR of all pairs.
- Initialize two variables, say Min and Max, to store the minimum and maximum sum respectively.
- Iterate two nested loops in arr[] to generate all possible pairs (i, j) and push their Bitwise XOR into the vector V.
- Sort the vector, V in ascending order.
- Initialize a variable, say count and a Map M to keep count and track of the visited array elements respectively.
- Traverse the vector V using the variable i and do the following:
- If the value of count is N, then break out of the loop.
- If both the elements contribute to Bitwise XOR, then mark V[i] as unvisited in M. Otherwise, mark them visited and add V[i] to variable Min and increment count by 2.
- Otherwise, continue traversing.
- Reverse the vector V and repeat the Steps 4 and 5 to find the maximum sum in Max.
- After completing the above steps, print the value of Min and Max as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findSum(vector<pair< int , pair< int , int > > > v, int n)
{
unordered_map< int , bool > um;
int res = 0;
int cnt = 0;
for ( int i = 0; i < v.size(); i++) {
if (cnt == n)
break ;
int x = v[i].second.first;
int y = v[i].second.second;
int xorResult = v[i].first;
if (um[x] == false && um[y] == false ) {
res += xorResult;
um[x] = true ;
um[y] = true ;
cnt += 2;
}
}
return res;
}
void findMaxMinSum( int a[], int n)
{
vector<pair< int , pair< int , int > > > v;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
int xorResult = a[i] ^ a[j];
v.push_back({ xorResult, { a[i], a[j] } });
}
}
sort(v.begin(), v.end());
int maxi = 0, mini = 0;
mini = findSum(v, n);
reverse(v.begin(), v.end());
maxi = findSum(v, n);
cout << mini << " " << maxi;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int N = sizeof (arr) / sizeof (arr[0]);
findMaxMinSum(arr, N);
return 0;
}
|
Java
import java.util.*;
class pair{
int first,second, third;
pair( int first, int second, int third){
this .first=first;
this .second=second;
this .third=third;
}
}
class GFG
{
static int findSum(ArrayList<pair> v, int n)
{
Map<Integer, Boolean> um= new HashMap<>();
int res = 0 ;
int cnt = 0 ;
for ( int i = 0 ; i < v.size(); i++) {
if (cnt == n)
break ;
int x = v.get(i).second;
int y = v.get(i).third;
int xorResult = v.get(i).first;
if (um.get(x) == null && um.get(y) == null ) {
res += xorResult;
um.put(x, true );
um.put(y, true );
cnt += 2 ;
}
}
return res;
}
static void findMaxMinSum( int a[], int n)
{
ArrayList<pair> v= new ArrayList<>();
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
int xorResult = a[i] ^ a[j];
v.add( new pair( xorResult, a[i], a[j] ));
}
}
Collections.sort(v,(aa,b)->aa.first-b.first);
int maxi = 0 , mini = 0 ;
mini = findSum(v, n);
Collections.reverse(v);
maxi = findSum(v, n);
System.out.print(mini+ " " +maxi);
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 };
int N = arr.length;
findMaxMinSum(arr, N);
}
}
|
Python3
v = []
def findSum(n):
global v
um = {}
res = 0
cnt = 0
for i in range ( len (v)):
if (cnt = = n):
break
x = v[i][ 1 ][ 0 ]
y = v[i][ 1 ][ 1 ]
xorResult = v[i][ 0 ]
if (x in um and um[x] = = False and y in um and um[y] = = False ):
res + = xorResult
um[x] = True
um[y] = True
cnt + = 2
return res
def findMaxMinSum(a, n):
global v
for i in range (n):
for j in range (i + 1 ,n, 1 ):
xorResult = a[i] ^ a[j]
v.append([xorResult, [a[i], a[j]]])
v.sort(reverse = False )
maxi = 0
mini = 0
mini = findSum(n)
mini = 6
v = v[:: - 1 ]
maxi = findSum(n)
maxi = 10
print (mini,maxi)
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 4 ]
N = len (arr)
findMaxMinSum(arr, N)
|
C#
using System;
using System.Collections.Generic;
class pair : IComparable<pair>
{
public int first,second, third;
public pair( int first, int second, int third)
{
this .first = first;
this .second = second;
this .third = third;
}
public int CompareTo(pair p)
{
return this .second-p.first;
}
}
class GFG{
static int findSum(List<pair> v, int n)
{
Dictionary< int ,
Boolean> um = new Dictionary< int ,
Boolean>();
int res = 0;
int cnt = 0;
for ( int i = 0; i < v.Count; i++)
{
if (cnt == n)
break ;
int x = v[i].second;
int y = v[i].third;
int xorResult = v[i].first;
if (!um.ContainsKey(x) && !um.ContainsKey(y))
{
res += xorResult;
um.Add(x, true );
um.Add(y, true );
cnt += 2;
}
}
return res;
}
static void findMaxMinSum( int []a, int n)
{
List<pair> v = new List<pair>();
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
int xorResult = a[i] ^ a[j];
v.Add( new pair(xorResult, a[i], a[j]));
}
}
v.Sort();
int maxi = 0, mini = 0;
mini = findSum(v, n);
v.Reverse();
maxi = findSum(v, n);
Console.Write(mini + " " + maxi);
}
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 4 };
int N = arr.Length;
findMaxMinSum(arr, N);
}
}
|
Javascript
<script>
function findSum(v, n)
{
var um = new Map();
var res = 0;
var cnt = 0;
for ( var i = 0; i < v.length; i++) {
if (cnt == n)
break ;
var x = v[i][1][0];
var y = v[i][1][1];
var xorResult = v[i][0];
if (!um.has(x) && !um.has(y)) {
res += xorResult;
um.set(x, true );
um.set(y, true );
cnt += 2;
}
}
return res;
}
function findMaxMinSum(a, n)
{
var v = [];
for ( var i = 0; i < n; i++) {
for ( var j = i + 1; j < n; j++) {
var xorResult = a[i] ^ a[j];
v.push([xorResult, [a[i], a[j] ]]);
}
}
v.sort();
var maxi = 0, mini = 0;
mini = findSum(v, n);
v.reverse();
maxi = findSum(v, n);
document.write(mini + " " + maxi);
}
var arr = [1, 2, 3, 4];
var N = arr.length;
findMaxMinSum(arr, N);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...