Sum of XOR of all pairs in an array

Difficulty Level :
Medium
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 : 12
7 ^ 3 = 4
3 ^ 5 = 6
7 ^ 5 = 2
Sum = 4 + 6 + 2 
    = 12

Input : arr[] = {5, 9, 7, 6}
Output : 47
5 ^ 9 = 12
9 ^ 7 = 14
7 ^ 6 = 1
5 ^ 7 = 2
5 ^ 6 = 3
9 ^ 6 = 15
Sum = 12 + 14 + 1 + 2 + 3 + 15
    = 47

Naive SolutionA Brute Force approach is to run two loops and time complexity is O(n2).
C++
Java
Python3
C#
PHP
JavaScript
// A Simple C++ program to compute// sum of bitwise OR of all pairs#include <bits/stdc++.h>using namespace std; // Returns sum of bitwise OR// of all pairsint pairORSum(int arr[], int n){    int ans = 0; // Initialize result     // Consider all pairs (arr[i], arr[j) such that    // i < j    for (int i = 0; i < n; i++)        for (int j = i + 1; j < n; j++)            ans += arr[i] ^ arr[j];     return ans;} // Driver program to test above functionint main(){    int arr[] = { 5, 9, 7, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << pairORSum(arr, n) << endl;    return 0;}
// A Simple Java program to compute// sum of bitwise OR of all pairsimport java.io.*; class GFG {                      // Returns sum of bitwise OR    // of all pairs    static int pairORSum(int arr[], int n)    {        // Initialize result        int ans = 0;             // Consider all pairs (arr[i], arr[j)        // such that i < j        for (int i = 0; i < n; i++)            for (int j = i + 1; j < n; j++)                ans += arr[i] ^ arr[j];             return ans;    }     // Driver program to test above function    public static void main (String[] args) {            int arr[] = { 5, 9, 7, 6 };        int n = arr.length;                 System.out.println(pairORSum(arr,                                arr.length));    }}  // This code is contributed by vt_m
# A Simple Python 3 program to compute# sum of bitwise OR of all pairs # Returns sum of bitwise OR# of all pairsdef pairORSum(arr, n) :    ans = 0     # Initialize result     # Consider all pairs (arr[i], arr[j)    # such that i < j    for i in range(0, n) :                 for j in range(i + 1, n) :                         ans = ans + (arr[i] ^ arr[j])                 return ans      # Driver Codearr = [ 5, 9, 7, 6 ]n = len(arr) print(pairORSum(arr, n))   # This code is contributed by Nikita Tiwari.
// A Simple C# program to compute// sum of bitwise OR of all pairsusing System; class GFG {                      // Returns sum of bitwise OR    // of all pairs    static int pairORSum(int []arr, int n)    {        // Initialize result        int ans = 0;             // Consider all pairs (arr[i], arr[j)        // such that i < j        for (int i = 0; i < n; i++)            for (int j = i + 1; j < n; j++)                ans += arr[i] ^ arr[j];             return ans;    }     // Driver program to test above function    public static void Main () {             int []arr = { 5, 9, 7, 6 };        int n = arr.Length;                 Console.WriteLine(pairORSum(arr,                                arr.Length));    }}  // This code is contributed by vt_m
<?php// A Simple PHP program to compute// sum of bitwise OR of all pairs // Returns sum of bitwise OR// of all pairsfunction pairORSum($arr, $n){         // Initialize result    $ans = 0;     // Consider all pairs    // (arr[i], arr[j) such that    // i < j    for ( $i = 0; $i < $n; $i++)        for ( $j = $i + 1; $j < $n; $j++)            $ans += $arr[$i] ^ $arr[$j];     return $ans;}     // Driver Code    $arr = array( 5, 9, 7, 6 );    $n = count($arr);    echo pairORSum($arr, $n) ; // This code is contributed by anuj_67.
<script>    // A Simple Javascript program to compute    // sum of bitwise OR of all pairs     // Returns sum of bitwise OR    // of all pairs    const pairORSum = (arr, n) => {        let ans = 0; // Initialize result         // Consider all pairs (arr[i], arr[j) such that        // i < j        for (let i = 0; i < n; i++)            for (let j = i + 1; j < n; j++)                ans += arr[i] ^ arr[j];         return ans;    }     // Driver program to test above function    let arr = [5, 9, 7, 6];    let n = arr.length;    document.write(pairORSum(arr, n));     // This code is contributed by rakeshsahni </script>?>
Output :
47
Efficient SolutionAn Efficient Solution can solve this problem in O(n) time. The assumption here is that integers are represented using 32 bits.Optimized solution will be to try bit manipulation. To implement the solution, we consider all bits which are 1 and which are 0 and store their count in two different variables. Next multiple those counts along with the power of 2 raised to that bit position. Do this for all the bit positions of the numbers. Their sum would be our answer.How this actually works?
For example, look at the rightmost bit of all the numbers in the array. Suppose that a numbers have a rightmost 0-bit, and b numbers have a 1-bit. Then out of the pairs, a*b of them will have 1 in the rightmost bit of the XOR. This is because there are a*b ways to choose one number that has a 0-bit and one that has a 1-bit. These bits will therefore contribute a*b towards the total of all the XORs.
In general, when looking at the nth bit (where the rightmost bit is the 0th), count how many numbers have 0 (call this an) and how many have 1 (call this bn). The contribution towards the final sum will be an*bn*pow(2,n). You need to do this for each bit and sum all these contributions together.
This can be done in O(kn) time, where k is the number of bits in the given values.
Explanation :  arr[] = { 7, 3, 5 }
7 = 1 1 1
3 = 0 1 1
5 = 1 0 1
For bit position 0 : 
Bits with zero = 0
Bits with one = 3
Answer = 0 * 3 * 2 ^ 0 = 0
Similarly, for bit position 1 :
Bits with zero = 1
Bits with one = 2
Answer = 1 * 2 * 2 ^ 1 = 4
Similarly, for bit position 2 :
Bits with zero = 1
Bits with one = 2
Answer = 1 * 2 * 2 ^ 2 = 8
 Final answer = 0 + 4 + 8 = 12 


CPP
Java
Python3
C#
PHP
JavaScript
// An efficient C++ program to compute// sum of bitwise OR of all pairs#include <bits/stdc++.h>using namespace std; // Returns sum of bitwise OR// of all pairslong long int sumXOR(int arr[], int n){    long long int sum = 0;    for (int i = 0; i < 32; i++)    {        //  Count of zeros and ones        int zc = 0, oc = 0;                 // Individual sum at each bit position        long long int idsum = 0;        for (int j = 0; j < n; j++)        {            if (arr[j] % 2 == 0)                zc++;            else                oc++;            arr[j] /= 2;        }                 // calculating individual bit sum        idsum = oc * zc * (1 << i);         // final sum           sum += idsum;    }    return sum;} int main(){    long long int sum = 0;    int arr[] = { 5, 9, 7, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    sum = sumXOR(arr, n);    cout << sum;    return 0;}
// An efficient Java program to compute// sum of bitwise OR of all pairsimport java.io.*; class GFG {         // Returns sum of bitwise OR    // of all pairs    static long sumXOR(int arr[], int n)    {        long sum = 0;        for (int i = 0; i < 32; i++)        {            // Count of zeros and ones            int zc = 0, oc = 0;                         // Individual sum at each bit position            long idsum = 0;                         for (int j = 0; j < n; j++)            {                if (arr[j] % 2 == 0)                    zc++;                                     else                    oc++;                arr[j] /= 2;            }                         // calculating individual bit sum            idsum = oc * zc * (1 << i);                 // final sum            sum += idsum;        }        return sum;    }         // Driver Code    public static void main(String args[])    {        long sum = 0;        int arr[] = { 5, 9, 7, 6 };        int n = arr.length;                 sum = sumXOR(arr, n);        System.out.println(sum);    }} // This code is contributed by Nikita Tiwari.
# An efficient Python3 program to compute# sum of bitwise OR of all pair # Returns sum of bitwise OR# of all pairsdef sumXOR( arr,  n):         sum = 0    for i in range(0, 32):         #  Count of zeros and ones        zc = 0        oc = 0                  # Individual sum at each bit position        idsum = 0        for j in range(0, n):            if (arr[j] % 2 == 0):                zc = zc + 1                             else:                oc = oc + 1            arr[j] = int(arr[j] / 2)                           # calculating individual bit sum        idsum = oc * zc * (1 << i)          # final sum           sum = sum + idsum;         return sum   # driver functionsum = 0arr = [  5, 9, 7, 6 ]n = len(arr)sum = sumXOR(arr, n);print (sum) # This code is contributed by saloni1297
// An efficient C# program to compute// sum of bitwise OR of all pairsusing System; class GFG {         // Returns sum of bitwise OR    // of all pairs    static long sumXOR(int []arr, int n)    {        long sum = 0;        for (int i = 0; i < 32; i++)        {            // Count of zeros and ones            int zc = 0, oc = 0;                         // Individual sum at each bit position            long idsum = 0;                         for (int j = 0; j < n; j++)            {                if (arr[j] % 2 == 0)                    zc++;                                     else                    oc++;                arr[j] /= 2;            }                         // calculating individual bit sum            idsum = oc * zc * (1 << i);                 // final sum            sum += idsum;        }        return sum;    }         // Driver Code    public static void Main()    {        long sum = 0;        int []arr = { 5, 9, 7, 6 };        int n = arr.Length;                 sum = sumXOR(arr, n);        Console.WriteLine(sum);    }} // This code is contributed by vt_m.
<?php// An efficient PHP program to compute// sum of bitwise OR of all pairs // Returns sum of bitwise OR// of all pairsfunction sumXOR($arr, $n){    $sum = 0;    for ($i = 0; $i < 32; $i++)    {        // Count of zeros and ones        $zc = 0; $oc = 0;                 // Individual sum at each        // bit position        $idsum = 0;        for ($j = 0; $j < $n; $j++)        {            if ($arr[$j] % 2 == 0)                $zc++;            else                $oc++;                             $arr[$j] /= 2;        }                 // calculating individual bit sum        $idsum = $oc * $zc * (1 << $i);         // final sum        $sum += $idsum;    }         return $sum;} // Driver code    $sum = 0;    $arr = array( 5, 9, 7, 6 );    $n = count($arr);    $sum = sumXOR($arr, $n);    echo $sum; // This code is contributed by anuj_67
<script>    // An efficient JavaScript program to compute    // sum of bitwise OR of all pairs     // Returns sum of bitwise OR    // of all pairs    const sumXOR = (arr, n) => {        let sum = 0;        for (let i = 0; i < 32; i++) {             // Count of zeros and ones            let zc = 0, oc = 0;             // Individual sum at each bit position            let idsum = 0;            for (let j = 0; j < n; j++) {                if (arr[j] % 2 == 0)                    zc++;                else                    oc++;                arr[j] = parseInt(arr[j] / 2);            }             // calculating individual bit sum            idsum = oc * zc * (1 << i);             // final sum               sum += idsum;        }        return sum;    }     let sum = 0;    let arr = [5, 9, 7, 6];    let n = arr.length;    sum = sumXOR(arr, n);    document.write(sum);     // This code is contributed by rakeshsahni </script> ?>
47
vt_m
Ganeshchowdharysadanala
rakeshsahni
Bitwise-XOR
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
How to swap two numbers without using a temporary variable?
Program to find whether a given number is power of 2
Little and Big Endian Mystery