Skip to content
Related Articles

Related Articles

Sum of Bitwise OR of every array element paired with all other array elements
  • Difficulty Level : Medium
  • Last Updated : 09 Feb, 2021

Given an array arr[] consisting of non-negative integers, the task for each array element arr[i] is to print the sum of Bitwise OR of all pairs (arr[i], arr[j]) ( 0 ≤ j ≤ N ).

Examples:

Input: arr[] = {1, 2, 3, 4}
Output: 12 14 16 22
Explanation:
For i = 0 the required sum will be (1 | 1) + (1 | 2) + (1 | 3) + (1 | 4) = 12
For i = 1 the required sum will be (2 | 1) + (2 | 2) + (2 | 3) + (2 | 4) = 14
For i = 2 the required sum will be (3 | 1) + (3 | 2) + (3 | 3) + (3 | 4) = 16
For i = 3 the required sum will be (4 | 1) + (4 | 2) + (4 | 3) + (4 | 4) = 22

Input: arr[] = {3, 2, 5, 4, 8}
Output: 31 28 37 34 54

 

Naive Approach: The simplest approach for every array element arr[i] is to traverse the array and calculate sum of Bitwise OR of all possible (arr[i], arr[j]) and print the obtained sum.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print required sum for
// every valid index i
void printORSumforEachElement(int arr[], int N)
{
    for (int i = 0; i < N; i++) {
 
        // Store the required sum
        // for current array element
        int req_sum = 0;
 
        // Generate all possible pairs (arr[i], arr[j])
        for (int j = 0; j < N; j++) {
 
            // Update the value of req_sum
            req_sum += (arr[i] | arr[j]);
        }
 
        // Print the required sum
        cout << req_sum << " ";
    }
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 2, 3, 4 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    printORSumforEachElement(arr, N);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to print required sum for
// every valid index i
static void printORSumforEachElement(int arr[], int N)
{
    for (int i = 0; i < N; i++)
    {
 
        // Store the required sum
        // for current array element
        int req_sum = 0;
 
        // Generate all possible pairs (arr[i], arr[j])
        for (int j = 0; j < N; j++)
        {
 
            // Update the value of req_sum
            req_sum += (arr[i] | arr[j]);
        }
 
        // Print the required sum
        System.out.print(req_sum+ " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
   
    // Given array
    int arr[] = { 1, 2, 3, 4 };
 
    // Size of the array
    int N = arr.length;
 
    // Function Call
    printORSumforEachElement(arr, N);
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to print required sum for
# every valid index i
def printORSumforEachElement(arr, N):
     
    for i in range(0, N):
         
        # Store the required sum
        # for current array element
        req_sum = 0
         
        # Generate all possible pairs(arr[i],arr[j])
        for j in range(0, N):
             
            # Update the value of req_sum
            req_sum += (arr[i] | arr[j])
             
        # Print required sum
        print(req_sum, end = " ")
 
# Driver code
 
# Given array
arr = [ 1, 2, 3, 4 ]
 
# Size of array
N = len(arr)
 
# Function call
printORSumforEachElement(arr, N)
 
# This code is contributed by Virusbuddah

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
public class GFG
{
 
// Function to print required sum for
// every valid index i
static void printORSumforEachElement(int []arr, int N)
{
    for (int i = 0; i < N; i++)
    {
 
        // Store the required sum
        // for current array element
        int req_sum = 0;
 
        // Generate all possible pairs (arr[i], arr[j])
        for (int j = 0; j < N; j++)
        {
 
            // Update the value of req_sum
            req_sum += (arr[i] | arr[j]);
        }
 
        // Print the required sum
        Console.Write(req_sum+ " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
   
    // Given array
    int []arr = { 1, 2, 3, 4 };
 
    // Size of the array
    int N = arr.Length;
 
    // Function Call
    printORSumforEachElement(arr, N);
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output: 

12 14 16 22

 

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

Efficient Approach: The optimal idea is to use Bit Manipulation by using the assumption that integers are represented using 32 bits. Follow the steps below to solve the problem:

  1. Consider every k-th bit and use a frequency array freq[] to store the count of elements for which k-th bit is set.
  2. For every array element check whether k-th bit of that element is set or not. If k-th bit is set then simply increase the frequency of k-th bit.
  3. Traverse the array and for every element arr[i] check whether k-th bit of arr[i] is set or not.
  4. Initialize required sum to 0 for every index i.
  5. If k-th bit of arr[i] is set then it means, k-th bit of every possible (arr[i] | arr[j]) will also be set. So in this case add (1 << k) * N to the required sum.
  6. Otherwise, if k-th bit of arr[i] is not set then it means that k-th bit of (arr[i] | arr[j]) will be set if and only if k-th bit of arr[j] is set. So in this case add (1 << k) * freq[k] to the required sum which is previously calculated that k-th bit is set for freq[k] number of elements.
  7. Finally, print the value of required sum for index i.

Below is the implementation of the above approach: 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print required sum for
// every valid index i
void printORSumforEachElement(int arr[], int N)
{
    // Frequency array to store frequency
    // of every k-th bit
    int freq[32];
 
    // Initialize frequency array
    memset(freq, 0, sizeof freq);
 
    for (int i = 0; i < N; i++) {
        for (int k = 0; k < 32; k++) {
 
            // If k-th bit is set, then update
            // the frequency of k-th bit
            if ((arr[i] & (1 << k)) != 0)
                freq[k]++;
        }
    }
 
    for (int i = 0; i < N; i++) {
 
        // Stores the required sum
        // for the current array element
        int req_sum = 0;
 
        for (int k = 0; k < 32; k++) {
 
            // If k-th bit is set
            if ((arr[i] & (1 << k)) != 0)
                req_sum += (1 << k) * N;
 
            // If k-th bit is not set
            else
                req_sum += (1 << k) * freq[k];
        }
 
        // Print the required sum
        cout << req_sum << " ";
    }
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 2, 3, 4 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    printORSumforEachElement(arr, N);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to print required sum for
// every valid index i
static void printORSumforEachElement(int arr[], int N)
{
   
    // Frequency array to store frequency
    // of every k-th bit
    int []freq = new int[32];
    for (int i = 0; i < N; i++)
    {
        for (int k = 0; k < 32; k++)
        {
 
            // If k-th bit is set, then update
            // the frequency of k-th bit
            if ((arr[i] & (1 << k)) != 0)
                freq[k]++;
        }
    }
    for (int i = 0; i < N; i++)
    {
 
        // Stores the required sum
        // for the current array element
        int req_sum = 0;
        for (int k = 0; k < 32; k++)
        {
 
            // If k-th bit is set
            if ((arr[i] & (1 << k)) != 0)
                req_sum += (1 << k) * N;
 
            // If k-th bit is not set
            else
                req_sum += (1 << k) * freq[k];
        }
 
        // Print the required sum
        System.out.print(req_sum+ " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
   
    // Given array
    int arr[] = { 1, 2, 3, 4 };
 
    // Size of the array
    int N = arr.length;
 
    // Function Call
    printORSumforEachElement(arr, N);
}
}
 
// This code is contributed by shikhasingrajput

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to print required sum for
# every valid index i
def printORSumforEachElement(arr, N):
     
    # Frequency array to store frequency
    # of every k-th bit
    freq = [0 for i in range(32)]
 
    for i in range(N):
        for k in  range(32):
             
            # If k-th bit is set, then update
            # the frequency of k-th bit
            if ((arr[i] & (1 << k)) != 0):
                freq[k] += 1
 
    for i in range(N):
         
        # Stores the required sum
        # for the current array element
        req_sum = 0
 
        for k in range(32):
             
            # If k-th bit is set
            if ((arr[i] & (1 << k)) != 0):
                req_sum += (1 << k) * N
 
            # If k-th bit is not set
            else:
                req_sum += (1 << k) * freq[k]
 
        # Print the required sum
        print(req_sum, end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [ 1, 2, 3, 4 ]
 
    # Size of the array
    N = len(arr)
 
    # Function Call
    printORSumforEachElement(arr, N)
     
# This code is contributed by SURENDRA_GANGWAR

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
class GFG
{
   
    // Function to print required sum for
    // every valid index i
    static void printORSumforEachElement(int[] arr, int N)
    {
       
        // Frequency array to store frequency
        // of every k-th bit
        int[] freq = new int[32];
 
        for (int i = 0; i < N; i++)
        {
            for (int k = 0; k < 32; k++)
            {
 
                // If k-th bit is set, then update
                // the frequency of k-th bit
                if ((arr[i] & (1 << k)) != 0)
                    freq[k]++;
            }
        }
 
        for (int i = 0; i < N; i++)
        {
 
            // Stores the required sum
            // for the current array element
            int req_sum = 0;
            for (int k = 0; k < 32; k++)
            {
 
                // If k-th bit is set
                if ((arr[i] & (1 << k)) != 0)
                    req_sum += (1 << k) * N;
 
                // If k-th bit is not set
                else
                    req_sum += (1 << k) * freq[k];
            }
 
            // Print the required sum
            Console.Write(req_sum + " ");
        }
    }
 
    // Driver Code
    public static void Main()
    {
        // Given array
        int[] arr = { 1, 2, 3, 4 };
 
        // Size of the array
        int N = arr.Length;
 
        // Function Call
        printORSumforEachElement(arr, N);
    }
}
 
// This code is contributed by chitranayal.

chevron_right


Output: 

12 14 16 22

 

Time Complexity: O(32 * N)
Auxiliary Space: O(m), where m = 32

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :