Given an array arr[] of size N and an array Q[], the task is to calculate the sum of Bitwise XOR of all elements of the array arr[] with each element of the array q[].
Examples:
Input: arr[ ] = {5, 2, 3}, Q[ ] = {3, 8, 7}
Output: 7 34 11
Explanation:
For Q[0] ( = 3): Sum = Â 5 ^ 3 + 2 ^ 3 + 3 ^ 3 = 7.
For Q[1] ( = 8): Sum = 5 ^ 8 + 2 ^ 8 + 3 ^ 8 = 34.
For Q[2] ( = 7): Sum = 5 ^ 7 + 2 ^ 7 + 3 ^ 7 = 11.Input: arr[ ] = {2, 3, 4}, Q[ ] = {1, 2}
Output: 10 7
Naive Approach: The simplest approach to solve the problem is to traverse the array Q[] and for each array element, calculate the sum of its Bitwise XOR with all elements of the array arr[].Â
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: Follow the steps below to optimize the above approach:
- Initialize an array count[], of size 32. to store the count of set bits at each position of the elements of the array arr[].
- Traverse the array arr[].
- Update the array count[] accordingly. In a 32-bit binary representation, if the ith bit is set, increase the count of set bits at that position.
- Traverse the array Q[] and for each array element, perform the following operations:
- Initialize variables, say sum = 0, to store the required sum of Bitwise XOR .
- Iterate over each bit positions of the current element.
- If current bit is set, add count of elements with ith bit not set * 2i to sum.
- Otherwise, add count[i] * Â 2i.
- Finally, print the value of sum.
Below is the implementation of the above approach:
C++
// C++ Program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to calculate sum of Bitwise // XOR of elements of arr[] with k int xorSumOfArray( int arr[], int n, int k, int count[]) { Â
    // Initialize sum to be zero     int sum = 0;     int p = 1; Â
    // Iterate over each set bit     for ( int i = 0; i < 31; i++) { Â
        // Stores contribution of         // i-th bet to the sum         int val = 0; Â
        // If the i-th bit is set         if ((k & (1 << i)) != 0) { Â
            // Stores count of elements             // whose i-th bit is not set             int not_set = n - count[i]; Â
            // Update value             val = ((not_set)*p);         }         else { Â
            // Update value             val = (count[i] * p);         } Â
        // Add value to sum         sum += val; Â
        // Move to the next         // power of two         p = (p * 2);     } Â
    return sum; } Â
void sumOfXors( int arr[], int n, int queries[], int q) { Â
    // Stores the count of elements     // whose i-th bit is set     int count[32]; Â
    // Initialize count to 0     // for all positions     memset (count, 0, sizeof (count)); Â
    // Traverse the array     for ( int i = 0; i < n; i++) { Â
        // Iterate over each bit         for ( int j = 0; j < 31; j++) { Â
            // If the i-th bit is set             if (arr[i] & (1 << j)) Â
                // Increase count                 count[j]++;         }     } Â
    for ( int i = 0; i < q; i++) {         int k = queries[i];         cout << xorSumOfArray(arr, n, k, count) << " " ;     } } Â
// Driver Code int main() { Â Â Â Â int arr[] = { 5, 2, 3 }; Â Â Â Â int queries[] = { 3, 8, 7 }; Â
    int n = sizeof (arr) / sizeof ( int );     int q = sizeof (queries) / sizeof ( int ); Â
    sumOfXors(arr, n, queries, q); Â
    return 0; } |
Java
// Java Program for the above approach import java.util.Arrays; Â
class GFG{ Â
// Function to calculate sum of Bitwise // XOR of elements of arr[] with k static int xorSumOfArray( int arr[], int n,                          int k, int count[]) {          // Initialize sum to be zero     int sum = 0 ;     int p = 1 ; Â
    // Iterate over each set bit     for ( int i = 0 ; i < 31 ; i++)     {                  // Stores contribution of         // i-th bet to the sum         int val = 0 ; Â
        // If the i-th bit is set         if ((k & ( 1 << i)) != 0 )         {                          // Stores count of elements             // whose i-th bit is not set             int not_set = n - count[i]; Â
            // Update value             val = ((not_set)*p);         }         else         {                          // Update value             val = (count[i] * p);         } Â
        // Add value to sum         sum += val; Â
        // Move to the next         // power of two         p = (p * 2 );     }     return sum; } Â
static void sumOfXors( int arr[], int n,                       int queries[], int q) {          // Stores the count of elements     // whose i-th bit is set     int []count = new int [ 32 ]; Â
    // Initialize count to 0     // for all positions     Arrays.fill(count, 0 ); Â
    // Traverse the array     for ( int i = 0 ; i < n; i++)     {                  // Iterate over each bit         for ( int j = 0 ; j < 31 ; j++)         {                          // If the i-th bit is set             if  ((arr[i] & ( 1 << j)) != 0 ) Â
                // Increase count                 count[j]++;         }     } Â
    for ( int i = 0 ; i < q; i++)     {         int k = queries[i];         System.out.print(             xorSumOfArray(arr, n, k, count) + " " );     } } Â
// Driver Code public static void main(String args[]) { Â Â Â Â int arr[] = { 5 , 2 , 3 }; Â Â Â Â int queries[] = { 3 , 8 , 7 }; Â Â Â Â int n = arr.length; Â Â Â Â int q = queries.length; Â
    sumOfXors(arr, n, queries, q); } } Â
// This code is contributed by SoumikMondal |
Python3
# Python3 Program for the above approach Â
# Function to calculate sum of Bitwise # XOR of elements of arr[] with k def xorSumOfArray(arr, n, k, count):          # Initialize sum to be zero     sum = 0     p = 1 Â
    # Iterate over each set bit     for i in range ( 31 ):                  # Stores contribution of         # i-th bet to the sum         val = 0 Â
        # If the i-th bit is set         if ((k & ( 1 << i)) ! = 0 ):                          # Stores count of elements             # whose i-th bit is not set             not_set = n - count[i] Â
            # Update value             val = ((not_set) * p) Â
        else :                          # Update value             val = (count[i] * p) Â
        # Add value to sum         sum + = val Â
        # Move to the next         # power of two         p = (p * 2 ) Â
    return sum Â
def sumOfXors(arr, n, queries, q):          # Stores the count of elements     # whose i-th bit is set     count = [ 0 for i in range ( 32 )] Â
    # Traverse the array     for i in range (n):                  # Iterate over each bit         for j in range ( 31 ):                          # If the i-th bit is set             if (arr[i] & ( 1 << j)):                                  # Increase count                 count[j] + = 1 Â
    for i in range (q):         k = queries[i]                  print (xorSumOfArray(arr, n, k, count), end = " " ) Â
# Driver Code if __name__ = = '__main__' : Â Â Â Â Â Â Â Â Â arr = [ 5 , 2 , 3 ] Â Â Â Â queries = [ 3 , 8 , 7 ] Â Â Â Â n = len (arr) Â Â Â Â q = len (queries) Â Â Â Â Â Â Â Â Â sumOfXors(arr, n, queries, q) Â
# This code is contributed by SURENDRA_GANGWAR |
C#
// C# Program for the above approach using System; Â
public class GFG{ Â Â Â Â Â // Function to calculate sum of Bitwise // XOR of elements of arr[] with k static int xorSumOfArray( int []arr, int n, int k, int []count) { Â
    // Initialize sum to be zero     int sum = 0;     int p = 1; Â
    // Iterate over each set bit     for ( int i = 0; i < 31; i++) { Â
        // Stores contribution of         // i-th bet to the sum         int val = 0; Â
        // If the i-th bit is set         if ((k & (1 << i)) != 0) { Â
            // Stores count of elements             // whose i-th bit is not set             int not_set = n - count[i]; Â
            // Update value             val = ((not_set)*p);         }         else { Â
            // Update value             val = (count[i] * p);         } Â
        // Add value to sum         sum += val; Â
        // Move to the next         // power of two         p = (p * 2);     } Â
    return sum; } Â
static void sumOfXors( int []arr, int n, int []queries, int q) { Â
    // Stores the count of elements     // whose i-th bit is set     int []count = new int [32]; Â
    // Initialize count to 0     // for all positions          for ( int i = 0; i < 32; i++)         count[i] = 0;              // Traverse the array     for ( int i = 0; i < n; i++) { Â
        // Iterate over each bit         for ( int j = 0; j < 31; j++) { Â
            // If the i-th bit is set             if ((arr[i] & (1 << j)) != 0) Â
                // Increase count                 count[j]++;         }     } Â
    for ( int i = 0; i < q; i++) {         int k = queries[i];         Console.Write(xorSumOfArray(arr, n, k, count) + " " );     } } Â
// Driver Code static public void Main () { Â Â Â Â int []arr = { 5, 2, 3 }; Â Â Â Â int []queries = { 3, 8, 7 }; Â
    int n = arr.Length;     int q = queries.Length; Â
    sumOfXors(arr, n, queries, q); } } Â
// This code is contributed by AnkThon |
Javascript
<script> Â
// Javascript program for the above approach Â
// Function to calculate sum of Bitwise // XOR of elements of arr[] with k function xorSumOfArray(arr, n, k, count) {          // Initialize sum to be zero     var sum = 0;     var p = 1; Â
    // Iterate over each set bit     for ( var i = 0; i < 31; i++)     {                  // Stores contribution of         // i-th bet to the sum         var val = 0; Â
        // If the i-th bit is set         if ((k & (1 << i)) != 0)         {                          // Stores count of elements             // whose i-th bit is not set             var not_set = n - count[i]; Â
            // Update value             val = ((not_set)*p);         }         else         {                          // Update value             val = (count[i] * p);         } Â
        // Add value to sum         sum += val; Â
        // Move to the next         // power of two         p = (p * 2);     }     return sum; } Â
function sumOfXors(arr, n, queries, q) {          // Stores the count of elements     // whose i-th bit is set     var count = new Array(32); Â
    // Initialize count to 0     // for all positions     count.fill(0); Â
    // Traverse the array     for ( var i = 0; i < n; i++)     {                  // Iterate over each bit         for ( var j = 0; j < 31; j++)         {                          // If the i-th bit is set             if (arr[i] & (1 << j)) Â
                // Increase count                 count[j]++;         }     } Â
    for ( var i = 0; i < q; i++)     {         var k = queries[i];         document.write(xorSumOfArray(             arr, n, k, count) + " " );     } } Â
// Driver code var arr = [ 5, 2, 3 ]; var queries = [ 3, 8, 7 ]; var n = arr.length; var q = queries.length; Â
sumOfXors(arr, n, queries, q); Â
// This code is contributed by SoumikMondal Â
</script> |
7 34 11
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!