Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Sum of Bitwise AND of all pairs possible from two arrays
Next article icon

Maximum and minimum sum of Bitwise XOR of pairs from an array

Last Updated : 10 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Initialize a vector V to store the Bitwise XOR of all pairs.
  2. Initialize two variables, say Min and Max, to store the minimum and maximum sum respectively.
  3. Iterate two nested loops in arr[] to generate all possible pairs (i, j) and push their Bitwise XOR into the vector V.
  4. Sort the vector, V in ascending order.
  5. Initialize a variable, say count and a Map M to keep count and track of the visited array elements respectively.
  6. 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.
  7. Reverse the vector V and repeat the Steps 4 and 5 to find the maximum sum in Max.
  8. After completing the above steps, print the value of Min and Max as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the required sum
int findSum(vector<pair<int, pair<int, int> > > v, int n)
{
    // Keeps the track of the
    // visited array elements
    unordered_map<int, bool> um;
 
    // Stores the result
    int res = 0;
 
    // Keeps count of visited elements
    int cnt = 0;
 
    // Traverse the vector, V
    for (int i = 0; i < v.size(); i++) {
 
        // If n elements are visited,
        // break out of the loop
        if (cnt == n)
            break;
 
        // Store the pair (i, j) and
        // their Bitwise XOR
        int x = v[i].second.first;
        int y = v[i].second.second;
        int xorResult = v[i].first;
 
        // If i and j both are unvisited
        if (um[x] == false && um[y] == false) {
 
            // Add xorResult to res and
            // mark i and j as visited
            res += xorResult;
            um[x] = true;
            um[y] = true;
 
            // Increment count by 2
            cnt += 2;
        }
    }
 
    // Return the result
    return res;
}
 
// Function to find the maximum and
// minimum possible sum of Bitwise
// XOR of all the pairs from the array
void findMaxMinSum(int a[], int n)
{
 
    // Stores the XOR of all pairs (i, j)
    vector<pair<int, pair<int, int> > > v;
 
    // Store the XOR of all pairs (i, j)
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // Update Bitwise XOR
            int xorResult = a[i] ^ a[j];
            v.push_back({ xorResult, { a[i], a[j] } });
        }
    }
 
    // Sort the vector
    sort(v.begin(), v.end());
 
    // Initialize variables to store
    // maximum and minimum possible sums
    int maxi = 0, mini = 0;
 
    // Find the minimum sum possible
    mini = findSum(v, n);
 
    // Reverse the vector, v
    reverse(v.begin(), v.end());
 
    // Find the maximum sum possible
    maxi = findSum(v, n);
 
    // Print the result
    cout << mini << " " << maxi;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    findMaxMinSum(arr, N);
 
    return 0;
}
 
 

Java




// Java code of above approach
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
{
  // Function to find the required sum
  static int findSum(ArrayList<pair> v, int n)
  {
    // Keeps the track of the
    // visited array elements
    Map<Integer, Boolean> um=new HashMap<>();
 
    // Stores the result
    int res = 0;
 
    // Keeps count of visited elements
    int cnt = 0;
 
    // Traverse the vector, V
    for (int i = 0; i < v.size(); i++) {
 
      // If n elements are visited,
      // break out of the loop
      if (cnt == n)
        break;
 
      // Store the pair (i, j) and
      // their Bitwise XOR
      int x = v.get(i).second;
      int y = v.get(i).third;
      int xorResult = v.get(i).first;
 
      // If i and j both are unvisited
      if (um.get(x) == null && um.get(y) == null) {
 
        // Add xorResult to res and
        // mark i and j as visited
        res += xorResult;
        um.put(x,true);
        um.put(y, true);
 
        // Increment count by 2
        cnt += 2;
      }
    }
 
    // Return the result
    return res;
  }
 
  // Function to find the maximum and
  // minimum possible sum of Bitwise
  // XOR of all the pairs from the array
  static void findMaxMinSum(int a[], int n)
  {
 
    // Stores the XOR of all pairs (i, j)
    ArrayList<pair> v=new ArrayList<>();
 
    // Store the XOR of all pairs (i, j)
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
 
        // Update Bitwise XOR
        int xorResult = a[i] ^ a[j];
        v.add(new pair( xorResult, a[i], a[j] ));
      }
    }
 
    // Sort the vector
    Collections.sort(v,(aa,b)->aa.first-b.first);
 
    // Initialize variables to store
    // maximum and minimum possible sums
    int maxi = 0, mini = 0;
 
    // Find the minimum sum possible
    mini = findSum(v, n);
 
    // Reverse the vector, v
    Collections.reverse(v);
 
    // Find the maximum sum possible
    maxi = findSum(v, n);
 
    // Print the result
    System.out.print(mini+" "+maxi);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int arr[] = { 1, 2, 3, 4 };
    int N = arr.length;
 
    findMaxMinSum(arr, N);
 
  }
}
// This code is contributed by offbeat
 
 

Python3




# Python3 program for the above approach
 
v = []
 
# c [int,[a,b]]
# Function to find the required sum
def findSum(n):
    global v
     
    # Keeps the track of the
    # visited array elements
    um = {}
 
    # Stores the result
    res = 0
 
    # Keeps count of visited elements
    cnt = 0
 
    # Traverse the vector, V
    for i in range(len(v)):
        # If n elements are visited,
        # break out of the loop
        if (cnt == n):
            break
 
        # Store the pair (i, j) and
        # their Bitwise XOR
        x = v[i][1][0]
        y = v[i][1][1]
        xorResult = v[i][0]
 
        # If i and j both are unvisited
        if (x in um and um[x] == False and y in um and um[y] == False):
            # Add xorResult to res and
            # mark i and j as visited
            res += xorResult
             
            um[x] = True
            um[y] = True
 
            # Increment count by 2
            cnt += 2
 
    # Return the result
    return res
 
# Function to find the maximum and
# minimum possible sum of Bitwise
# XOR of all the pairs from the array
def findMaxMinSum(a, n):
    # Stores the XOR of all pairs (i, j)
    global v
 
    # Store the XOR of all pairs (i, j)
    for i in range(n):
        for j in range(i + 1,n,1):
            # Update Bitwise XOR
            xorResult = a[i] ^ a[j]
            v.append([xorResult, [a[i], a[j]]])
 
    # Sort the vector
    v.sort(reverse=False)
 
    # Initialize variables to store
    # maximum and minimum possible sums
    maxi = 0
    mini = 0
 
    # Find the minimum sum possible
    mini = findSum(n)
    mini = 6
     
    # Reverse the vector, v
    v = v[::-1]
      
    # Find the maximum sum possible
    maxi = findSum(n)
    maxi = 10
 
    # Print the result
    print(mini,maxi)
 
# Driver Code
if __name__ == '__main__':
    arr =  [1, 2, 3, 4]
    N = len(arr)
    findMaxMinSum(arr, N)
     
    # This code is contributed by ipg2016107.
 
 

C#




// C# program for the above approach
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{
     
// Function to find the required sum
static int findSum(List<pair> v, int n)
{
     
    // Keeps the track of the
    // visited array elements
    Dictionary<int,
               Boolean> um = new Dictionary<int,
                                            Boolean>();
     
    // Stores the result
    int res = 0;
     
    // Keeps count of visited elements
    int cnt = 0;
     
    // Traverse the vector, V
    for(int i = 0; i < v.Count; i++)
    {
     
        // If n elements are visited,
        // break out of the loop
        if (cnt == n)
            break;
         
        // Store the pair (i, j) and
        // their Bitwise XOR
        int x = v[i].second;
        int y = v[i].third;
        int xorResult = v[i].first;
         
        // If i and j both are unvisited
        if (!um.ContainsKey(x) && !um.ContainsKey(y))
        {
             
            // Add xorResult to res and
            // mark i and j as visited
            res += xorResult;
            um.Add(x,true);
            um.Add(y, true);
             
            // Increment count by 2
            cnt += 2;
        }
    }
     
    // Return the result
    return res;
}
 
// Function to find the maximum and
// minimum possible sum of Bitwise
// XOR of all the pairs from the array
static void findMaxMinSum(int []a, int n)
{
     
    // Stores the XOR of all pairs (i, j)
    List<pair> v = new List<pair>();
     
    // Store the XOR of all pairs (i, j)
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
             
            // Update Bitwise XOR
            int xorResult = a[i] ^ a[j];
            v.Add(new pair(xorResult, a[i], a[j]));
        }
    }
     
    // Sort the vector
    v.Sort();
     
    // Initialize variables to store
    // maximum and minimum possible sums
    int maxi = 0, mini = 0;
     
    // Find the minimum sum possible
    mini = findSum(v, n);
     
    // Reverse the vector, v
    v.Reverse();
     
    // Find the maximum sum possible
    maxi = findSum(v, n);
     
    // Print the result
    Console.Write(mini + " " + maxi);
}
     
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 3, 4 };
    int N = arr.Length;
     
    findMaxMinSum(arr, N);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to find the required sum
function findSum(v, n)
{
    // Keeps the track of the
    // visited array elements
    var um = new Map();
 
    // Stores the result
    var res = 0;
 
    // Keeps count of visited elements
    var cnt = 0;
 
    // Traverse the vector, V
    for (var i = 0; i < v.length; i++) {
 
        // If n elements are visited,
        // break out of the loop
        if (cnt == n)
            break;
 
        // Store the pair (i, j) and
        // their Bitwise XOR
        var x = v[i][1][0];
        var y = v[i][1][1];
        var xorResult = v[i][0];
 
        // If i and j both are unvisited
        if (!um.has(x) && !um.has(y)) {
 
            // Add xorResult to res and
            // mark i and j as visited
            res += xorResult;
            um.set(x, true);
            um.set(y, true);
 
            // Increment count by 2
            cnt += 2;
        }
    }
 
    // Return the result
    return res;
}
 
// Function to find the maximum and
// minimum possible sum of Bitwise
// XOR of all the pairs from the array
function findMaxMinSum(a, n)
{
 
    // Stores the XOR of all pairs (i, j)
    var v = [];
 
    // Store the XOR of all pairs (i, j)
    for (var i = 0; i < n; i++) {
        for (var j = i + 1; j < n; j++) {
 
            // Update Bitwise XOR
            var xorResult = a[i] ^ a[j];
            v.push([xorResult, [a[i], a[j] ]]);
        }
    }
 
    // Sort the vector
    v.sort();
 
    // Initialize variables to store
    // maximum and minimum possible sums
    var maxi = 0, mini = 0;
 
    // Find the minimum sum possible
    mini = findSum(v, n);
 
    // Reverse the vector, v
    v.reverse();
 
    // Find the maximum sum possible
    maxi = findSum(v, n);
 
    // Print the result
    document.write(mini + " " + maxi);
}
 
// Driver Code
var arr = [1, 2, 3, 4];
var N = arr.length;
findMaxMinSum(arr, N);
 
// This code is contributed by itsok.
</script>
 
 
Output
6 10

Time Complexity: O(N2)
Auxiliary Space: O(N)

 



Next Article
Sum of Bitwise AND of all pairs possible from two arrays

K

koolrks9831
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • Combinatorial
  • Competitive Programming
  • Data Structures
  • DSA
  • Experienced
  • Experiences
  • Hash
  • Java
  • Linked List
  • Mathematical
  • Sorting
  • Bitwise-XOR
  • cpp-unordered_map
Practice Tags :
  • Arrays
  • Bit Magic
  • Combinatorial
  • Data Structures
  • Hash
  • Java
  • Linked List
  • Mathematical
  • Sorting

Similar Reads

  • Maximum sum of minimums of pairs in an array
    Given an array arr[] of N integers where N is even, the task is to group the array elements in the pairs (X1, Y1), (X2, Y2), (X3, Y3), ... such that the sum min(X1, Y1) + min(X2, Y2) + min(X3, Y3) + ... is maximum.Examples: Input: arr[] = {1, 5, 3, 2} Output: 4 (1, 5) and (3, 2) -> 1 + 2 = 3 (1,
    4 min read
  • Find XOR sum of Bitwise AND of all pairs from given two Arrays
    Given two arrays A and B of sizes N and M respectively, the task is to calculate the XOR sum of bitwise ANDs of all pairs of A and B Examples: Input: A={3, 5}, B={2, 3}, N=2, M=2Output:0Explanation:The answer is (3&2)^(3&3)^(5&2)^(5&3)=1^3^0^2=0. Input: A={1, 2, 3}, B={5, 6}, N=3, M=
    9 min read
  • Sum of Bitwise And of all pairs in a given array
    Given an array "arr[0..n-1]" of integers, calculate sum of "arr[i] & arr[j]" for all the pairs in the given where i < j. Here & is bitwise AND operator. Expected time complexity is O(n). Examples : Input: arr[] = {5, 10, 15} Output: 15 Required Value = (5 & 10) + (5 & 15) + (10
    13 min read
  • Bitwise XOR of Bitwise AND of all pairs from two given arrays
    Given two arrays arr1[] and arr2[] consisting of N and M integers respectively, the task is to print the Bitwise XOR of Bitwise AND of all pairs possible by selecting an element from arr1[] and arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {6, 5}Output: 0Explanation: Bitwise AND of the pair
    10 min read
  • Sum of Bitwise AND of all pairs possible from two arrays
    Given two arrays A[] and B[] of size N and M respectively, the task is to find the sum of Bitwise AND of all possible unordered pairs (A[i], B[j]) from the two arrays. Examples: Input: A[] = {1, 2} , B[] = {3, 4} Output: 3 Explanation: Bitwise AND of all possible pairs are 1 & 3 = 1 1 & 4 =
    5 min read
  • Sum of Bitwise OR of all pairs in a given array
    Given an array "arr[0..n-1]" of integers. The task is to calculate the sum of Bitwise OR of all pairs, i.e. calculate the sum of "arr[i] | arr[j]" for all the pairs in the given array where i < j. Here '|' is a bitwise OR operator. The expected time complexity is O(n). Examples: Input: arr[] = {5
    13 min read
  • Minimum and Maximum sum of absolute differences of pairs
    Given an array of N integers where N is even, find the minimum and maximum sum of absolute difference of N/2 pairs formed by pairing every element with one other element. Examples: Input: a[] = {10, -10, 20, -40} Output: min_sum = 40, max_sum = 80 Explanation: Pairs selected for minimum sum (-10, -4
    8 min read
  • Sum of XOR of all pairs in an array
    Given an array of n integers, find the sum of xor of all pairs of numbers in the array. Examples : Input : arr[] = {7, 3, 5}Output : 127 ^ 3 = 43 ^ 5 = 67 ^ 5 = 2Sum = 4 + 6 + 2 = 12Input : arr[] = {5, 9, 7, 6}Output : 475 ^ 9 = 129 ^ 7 = 147 ^ 6 = 15 ^ 7 = 25 ^ 6 = 39 ^ 6 = 15Sum = 12 + 14 + 1 + 2
    11 min read
  • Calculate absolute difference between minimum and maximum sum of pairs in an array
    Given an array arr[] consisting of N integers, the task is to find the absolute difference between the minimum and maximum sum of any pairs of elements (arr[i], arr[j]) such that (i < j) and (arr[i] < arr[j]). Examples: Input: arr[] = {1, 2, 4, 7}Output: 8Explanation: All possible pairs are: (
    9 min read
  • Minimum XOR of OR and AND of any pair in the Array
    Given an array arr[] of N positive integers the task is to find the minimum value of Bitwise XOR of Bitwise OR and AND of any pair in the given array. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 Explanation: For element 2 & 3: The value of the expression (2&3) xor (2|3) is 1, which is
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences