Sum of Bitwise-OR of all subarrays of a given Array | Set 2

Give an array of positive integers. The task is to find the total sum after performing the bit wise OR operation on all the sub arrays of the given array.

Examples:

Input : arr[] = {1, 2, 3, 4, 5}
Output : 71

Input : arr[] = {6, 5, 4, 3, 2}
Output : 84

Explanation:



Simple Approach: A simple approach is to find the bitwise OR of each subarray of the given array using two nested loops, and then find the total sum. Time complexity of this approach will be O(N2).

Efficient Approach:

  1. Observe here that if a bit is being set by an element of the array then all subarray having that element will have that bit set. Therefore when we calculate sum of all subarrays having that number, we can directly multiply number of subarrays by the value that bit is making.
  2. Now, to do this an easy way will be to calculate the number of subarrays for which a bit is not set and subtract it from the total number of subarrays.

Let’s see an example:
Let the array A = [1, 2, 3, 4, 5]. Now the 1st bit is not set in the elements 2 and 4 and total number of such subarrays for which the Bitwise-OR will not have the 1st bit set will be 2.

Therefore, total number of subarrays for which the bitwise-OR will have 1st bit as set will be: 15-2 = 13.

Therefore we will add (13 * pow(2, 0)) to sum.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find sum of bitwise OR
// of all subarrays
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find sum of bitwise OR
// of all subarrays
int givesum(int A[], int n)
{
    // Find max element of the array
    int max = *max_element(A, A + n);
  
    // Find the max bit position set in
    // the array
    int maxBit = log2(max) + 1;
  
    int totalSubarrays = n * (n + 1) / 2;
  
    int s = 0;
  
    // Traverse from 1st bit to last bit which
    // can be set in any element of the array
    for (int i = 0; i < maxBit; i++) {
        int c1 = 0;
  
        // Vector to store indexes of the array
        // with i-th bit not set
        vector<int> vec;
  
        int sum = 0;
  
        // Traverse the array
        for (int j = 0; j < n; j++) {
  
            // Check if ith bit is not set in A[j]
            int a = A[j] >> i;
            if (!(a & 1)) {
                vec.push_back(j);
            }
        }
  
        // Variable to store count of subarrays
        // whose bitwise OR will have i-th bit
        // not set
        int cntSubarrNotSet = 0;
  
        int cnt = 1;
  
        for (int j = 1; j < vec.size(); j++) {
            if (vec[j] - vec[j - 1] == 1) {
                cnt++;
            }
            else {
                cntSubarrNotSet += cnt * (cnt + 1) / 2;
  
                cnt = 1;
            }
        }
  
        // For last element of vec
        cntSubarrNotSet += cnt * (cnt + 1) / 2;
  
        // Variable to store count of subarrays
        // whose bitwise OR will have i-th bit set
        int cntSubarrIthSet = totalSubarrays - cntSubarrNotSet;
  
        s += cntSubarrIthSet * pow(2, i);
    }
  
    return s;
}
  
// Driver code
int main()
{
    int A[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(A) / sizeof(A[0]);
  
    cout << givesum(A, n);
  
    return 0;
}

chevron_right


Python3

# Python 3 program to find sum of
# bitwise OR of all subarrays

# from math lib. import log2 function
from math import log2

# Function to find sum of bitwise OR
# of all subarrays
def givesum(A, n) :

# Find max element of the array
max_element = max(A)

# Find the max bit position set in
# the array
maxBit = int(log2(max_element)) + 1

totalSubarrays = n * (n + 1) // 2

s = 0

# Traverse from 1st bit to last bit which
# can be set in any element of the array
for i in range(maxBit) :
c1 = 0

# List to store indexes of the array
# with i-th bit not set
vec = []

sum = 0

# Traverse the array
for j in range(n) :

# Check if ith bit is not set in A[j]
a = A[j] >> i

if (not(a & 1)) :
vec.append(j)

# Variable to store count of subarrays
# whose bitwise OR will have i-th bit
# not set
cntSubarrNotSet = 0

cnt = 1

for j in range(1, len(vec)) :

if (vec[j] – vec[j – 1] == 1) :
cnt += 1

else :

cntSubarrNotSet += cnt * (cnt + 1) // 2

cnt = 1

# For last element of vec
cntSubarrNotSet += cnt * (cnt + 1) // 2

# Variable to store count of subarrays
# whose bitwise OR will have i-th bit set
cntSubarrIthSet = totalSubarrays – cntSubarrNotSet

s += cntSubarrIthSet * pow(2, i)

return s

# Driver code
if __name__ == “__main__” :

A = [ 1, 2, 3, 4, 5 ]
n = len(A)

print(givesum(A, n))

# This code is contributed by Ryuga

Output:

71

Time Complexity: O(N*logN)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Ryuga