Open In App

XOR of pairwise sum of every unordered pairs in an array

Given an array arr[] of length N, the task is to find the XOR of pairwise sum of every possible unordered pairs of the array. The unordered pairs sum is defined as follows – 
 

XOR of pairwise sum  = (A[0] + A[1]) ^
    (A[0] + A[2]) ^ ...(A[0] + A[N]) ^
    (A[1] + A[2]) ^ ...(A[1] + A[N]) ^
    .......
    (A[N-1] + A[N])

Notice that after including A[0] and A[1] 
as pairs, then A[1] and A[0] are not included.

Examples: 
 

Input: arr[] = {1, 2} 
Output:
Explanation: 
There is only one unordered pair. That is (1, 2)
Input: arr[] = {1, 2, 3} 
Output:
Explanation: 
Unordered pairs of the numbers – 
{(1, 2), (1, 3), (2, 3)} 
XOR of unordered pairwise sum – 
=> (1 + 2) ^ (1 + 3) ^ (2 + 3) 
=> 3 ^ 4 ^ 5 
=> 2 
 

 

Naive Approach: The idea is to find every possible unordered pair with the help of the two loops and find the XOR of these pairs.
Below is the implementation of the above approach:
 




// C++ implementation to find XOR of
// pairwise sum of every unordered
// pairs in an array
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find XOR of pairwise
// sum of every unordered pairs
int xorOfSum(int a[], int n)
{
    int answer = 0;
     
    // Loop to choose every possible
    // pairs in the array
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++)
            answer ^= (a[i] + a[j]);
    }
 
    return answer;
}
 
// Driver Code
int main()
{
    int n = 3;
    int A[n] = { 1, 2, 3 };
 
    cout << xorOfSum(A, n);
    return 0;
}




// Java implementation to find XOR of
// pairwise sum of every unordered
// pairs in an array
class GFG{
  
// Function to find XOR of pairwise
// sum of every unordered pairs
static int xorOfSum(int a[], int n)
{
    int answer = 0;
      
    // Loop to choose every possible
    // pairs in the array
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++)
            answer ^= (a[i] + a[j]);
    }
  
    return answer;
}
  
// Driver Code
public static void main(String[] args)
{
    int n = 3;
    int A[] = { 1, 2, 3 };
  
    System.out.print(xorOfSum(A, n));
}
}
 
// This code is contributed by PrinciRaj1992




# Python3 implementation to find XOR of
# pairwise sum of every unordered
# pairs in an array
 
# Function to find XOR of pairwise
# sum of every unordered pairs
def xorOfSum(a, n):
    answer = 0
 
    # Loop to choose every possible
    # pairs in the array
    for i in range(n):
        for j in range(i + 1, n):
            answer ^= (a[i] + a[j])
 
    return answer
 
# Driver Code
if __name__ == '__main__':
    n = 3
    A=[1, 2, 3]
 
    print(xorOfSum(A, n))
 
# This code is contributed by mohit kumar 29




// C# implementation to find XOR of
// pairwise sum of every unordered
// pairs in an array
using System;
using System.Collections.Generic;
 
class GFG{
   
// Function to find XOR of pairwise
// sum of every unordered pairs
static int xorOfSum(int []a, int n)
{
    int answer = 0;
       
    // Loop to choose every possible
    // pairs in the array
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++)
            answer ^= (a[i] + a[j]);
    }
   
    return answer;
}
   
// Driver Code
public static void Main(String[] args)
{
    int n = 3;
    int []A = { 1, 2, 3 };
   
    Console.Write(xorOfSum(A, n));
}
}
  
// This code is contributed by PrinciRaj1992




<script>
// JavaScript implementation to find XOR of
// pairwise sum of every unordered
// pairs in an array
 
// Function to find XOR of pairwise
// sum of every unordered pairs
function xorOfSum(a, n)
{
    let answer = 0;
     
    // Loop to choose every possible
    // pairs in the array
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++)
            answer ^= (a[i] + a[j]);
    }
 
    return answer;
}
 
// Driver Code
    let n = 3;
    let A = [ 1, 2, 3 ];
 
    document.write(xorOfSum(A, n));
 
// This code is contributed by Surbhi Tyagi
 
</script>

Output: 
2

 

 Time complexity: O(n2), where n is the size of the  array.

 Space complexity: O(1)

Efficient Approach: 
 

Auxiliary Space: O(1)
Below is the implementation of the above approach:
 




// C++ implementation to find XOR of
// pairwise sum of every unordered
// pairs in an array
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find XOR of pairwise
// sum of every unordered pairs
int xorOfSum(int a[], int n)
{
 
    int i, j, k;
     
    // Sort the array
    sort(a, a + n);
 
    int ans = 0;
 
    // Array elements are not greater
    // than 1e7 so 27 bits are suffice
    for (k = 0; k < 27; ++k) {
         
        // Modded elements of array
        vector<int> b(n);
         
        // Loop to find the modded
        // elements of array
        for (i = 0; i < n; i++)
            b[i] = a[i] % (1 << (k + 1));
 
        // Sort the modded array
        sort(b.begin(), b.end());
 
        int cnt = 0;
        for (i = 0; i < n; i++) {
            // finding the bound for j
            // for given i using binary search
            int l = lower_bound(b.begin() +
                           i + 1, b.end(),
               (1 << k) - b[i]) - b.begin();
            int r = lower_bound(b.begin() +
                    i + 1, b.end(), (1 << (k + 1)) -
                          b[i]) - b.begin();
 
            // All the numbers in the range
            // of indices can be added to the
            // count to check the xor.
            cnt += r - l;
 
            l = lower_bound(b.begin() + i + 1,
                 b.end(), (1 << (k + 1)) +
                 (1 << k) - b[i]) - b.begin();
            cnt += n - l;
        }
        // Remainder of cnt * kth power
        // of 2 added to the xor value
        ans += (cnt % 2) * 1LL * (1 << k);
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    int n = 3;
    int A[n] = { 1, 2, 3 };
 
    cout << xorOfSum(A, n);
    return 0;
}




// Java implementation to find XOR of pairwise sum of every
// unordered pairs in an array
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Function to find the lower_bound of an array
  // ie, the leftmost element that is greater than
  // or equal to the given element
  static int lower_bound(int[] array, int startIndex,
                         int element)
  {
    for (int i = startIndex; i < array.length; i++) {
      if (array[i] >= element) {
        return i;
      }
    }
    return array.length;
  }
 
  // Function to find XOR of pairwise
  // sum of every unordered pairs
  static int xorOfSum(int[] a, int n)
  {
    Arrays.sort(a);
    int ans = 0;
    for (int k = 0; k < 27; k++) {
      int[] b = new int[n];
      for (int i = 0; i < n; i++) {
        b[i] = a[i] % (1 << (k + 1));
      }
      Arrays.sort(b);
      int cnt = 0;
      for (int i = 0; i < n; i++) {
        int l = lower_bound(b, i + 1,
                            (1 << k) - b[i]);
        int r = lower_bound(b, i + 1,
                            (1 << (k + 1)) - b[i]);
        cnt += r - l;
        l = lower_bound(b, i + 1,
                        (1 << (k + 1)) + (1 << k)
                        - b[i]);
        cnt += n - l;
      }
      ans += (cnt % 2) * (1 << k);
    }
    return ans;
  }
 
  public static void main(String[] args)
  {
    int n = 3;
    int[] A = { 1, 2, 3 };
    System.out.println(xorOfSum(A, n));
  }
}
 
// This code is contributed by lokeshmvs21.




# Python3 implementation to find XOR of
# pairwise sum of every unordered
# pairs in an array
 
# Function to find the lower_bound of an array
# ie, the leftmost element that is greater than
# or equal to the given element
def lower_bound(arr, startIndex, element):
 
    n = len(arr)
    for i in range(startIndex, n):
 
        if (arr[i] >= element):
            return i
    return n
 
 
# Function to find XOR of pairwise
# sum of every unordered pairs
def xorOfSum(a, n):
 
    # Sort the array
    a.sort()
 
    ans = 0
 
    # Array elements are not greater
    # than 1e7 so 27 bits are suffice
    for k in range(27):
 
        # Modded elements of array
        b = [0 for _ in range(n)]
 
        # Loop to find the modded
        # elements of array
        for i in range(n):
            b[i] = a[i] % (1 << (k + 1))
 
        # Sort the modded array
        b.sort()
 
        cnt = 0
        for i in range(n):
 
            # finding the bound for j
            # for given i using binary search
            l = lower_bound(b, i + 1, (1 << k) - b[i])
            r = lower_bound(b, i + 1, (1 << (k + 1)) - b[i])
 
            # All the numbers in the range
            # of indices can be added to the
            # count to check the xor.
            cnt += r - l
 
            l = lower_bound(b, i + 1, (1 << (k + 1)) +
                            (1 << k) - b[i])
            cnt += n - l
 
        # Remainder of cnt * kth power
        # of 2 added to the xor value
        ans += (cnt % 2) * (1 << k)
 
    return ans
 
# Driver Code
n = 3
A = [1, 2, 3]
 
# Function call
print(xorOfSum(A, n))
 
# This code is contributed by phasing17




// C# implementation to find XOR of pairwise sum of every
// unordered pairs in an array
using System;
public class GFG {
 
  // Function to find the lower_bound of an array
  // ie, the leftmost element that is greater than
  // or equal to the given element
  static int lower_bound(int[] array, int startIndex,
                         int element)
  {
    for (int i = startIndex; i < array.Length; i++) {
      if (array[i] >= element) {
        return i;
      }
    }
    return array.Length;
  }
 
  // Function to find XOR of pairwise
  // sum of every unordered pairs
  static int xorOfSum(int[] a, int n)
  {
    Array.Sort(a);
    int ans = 0;
    for (int k = 0; k < 27; k++) {
      int[] b = new int[n];
      for (int i = 0; i < n; i++) {
        b[i] = a[i] % (1 << (k + 1));
      }
      Array.Sort(b);
      int cnt = 0;
      for (int i = 0; i < n; i++) {
        int l = lower_bound(b, i + 1,
                            (1 << k) - b[i]);
        int r = lower_bound(b, i + 1,
                            (1 << (k + 1)) - b[i]);
        cnt += r - l;
        l = lower_bound(b, i + 1,
                        (1 << (k + 1)) + (1 << k)
                        - b[i]);
        cnt += n - l;
      }
      ans += (cnt % 2) * (1 << k);
    }
    return ans;
  }
 
  static public void Main()
  {
 
    // Code
    int n = 3;
    int[] A = { 1, 2, 3 };
    Console.WriteLine(xorOfSum(A, n));
  }
}
 
// This code is contributed by lokesh.




// JavaScript implementation to find XOR of
// pairwise sum of every unordered
// pairs in an array
 
// Function to find the lower_bound of an array
// ie, the leftmost element that is greater than
// or equal to the given element
function lower_bound(array, startIndex, element)
{
     
    var n = array.length;
    for (var i = startIndex; i < n; i++)
    {
        if (array[i] >= element)
            return i;
    }
    return n;
}
 
// Function to find XOR of pairwise
// sum of every unordered pairs
function xorOfSum(a, n)
{
 
    var i;
    var j;
    var k;
     
    // Sort the array
    a.sort();
 
    var ans = 0;
 
    // Array elements are not greater
    // than 1e7 so 27 bits are suffice
    for (k = 0; k < 27; k++) {
         
        // Modded elements of array
        b = new Array(n);
         
        // Loop to find the modded
        // elements of array
        for (i = 0; i < n; i++)
            b[i] = a[i] % (1 << (k + 1));
 
        // Sort the modded array
        b.sort();
 
        var cnt = 0;
        for (i = 0; i < n; i++)
        {
         
            // finding the bound for j
            // for given i using binary search
            var l = lower_bound(b, i + 1, (1 << k) - b[i]);
            var r = lower_bound(b,i + 1, (1 << (k + 1)) - b[i]);
 
            // All the numbers in the range
            // of indices can be added to the
            // count to check the xor.
            cnt += r - l;
 
            l = lower_bound(b, i + 1, (1 << (k + 1)) +
                 (1 << k) - b[i]);
            cnt += n - l;
        }
         
        // Remainder of cnt * kth power
        // of 2 added to the xor value
        ans += (cnt % 2) * (1 << k);
    }
 
    return ans;
}
 
// Driver Code
var n = 3;
var A = [ 1, 2, 3 ];
 
// Function call
console.log(xorOfSum(A, n));
 
// this code is contributed by phasing17

Output: 
2

 

Performance Analysis: 
 

Outermost loop runs for log(max(A)) times and for each loop we create and sort array b ,which consists of N elements ,hence complexity is O(N*log(N)*log(max(A)))
 


Article Tags :