Sum of Bitwise-OR of all subarrays of a given Array | Set 2
Last Updated :
18 Apr, 2023
Give an array of positive integers. The task is to find the total sum after performing the bitwise 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:
- 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.
- 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++
// 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;
// If vec is empty then cntSubarrNotSet
// should be 0 and not 1
if (vec.size() == 0)
cntSubarrNotSet = 0;
// 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;
}
Java
// Java program to find sum of bitwise OR
// of all subarrays
import java.util.*;
class GFG {
// Function to find sum of bitwise OR
// of all subarrays
static int givesum(int A[], int n)
{
// Find max element of the array
int max = Arrays.stream(A).max().getAsInt();
// Find the max bit position
// set in the array
int maxBit = (int)Math.ceil(Math.log(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<Integer> vec = new Vector<>();
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 % 2 == 1)) {
vec.add(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.get(j) - vec.get(j - 1) == 1) {
cnt++;
}
else {
cntSubarrNotSet += cnt * (cnt + 1) / 2;
cnt = 1;
}
}
// For last element of vec
cntSubarrNotSet += cnt * (cnt + 1) / 2;
// If vec is empty then cntSubarrNotSet
// should be 0 and not 1
if (vec.size() == 0)
cntSubarrNotSet = 0;
// Variable to store count of subarrays
// whose bitwise OR will have i-th bit set
int cntSubarrIthSet = totalSubarrays - cntSubarrNotSet;
s += cntSubarrIthSet * Math.pow(2, i);
}
return s;
}
// Driver code
public static void main(String[] args)
{
int A[] = { 1, 2, 3, 4, 5 };
int n = A.length;
System.out.println(givesum(A, n));
}
}
// This code is contributed by 29AjayKumar
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
# If vec is empty then cntSubarrNotSet
# should be 0 and not 1
if len(vec) == 0:
cntSubarrNotSet = 0
# 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
C#
// C# program to find sum of bitwise OR
// of all subarrays
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
// Function to find sum of bitwise OR
// of all subarrays
static int givesum(int[] A, int n)
{
// Find max element of the array
int max = A.Max();
// Find the max bit position
// set in the array
int maxBit = (int)Math.Ceiling(Math.Log(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++) {
// Vector to store indexes of the array
// with i-th bit not set
List<int> vec = new List<int>();
// 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 % 2 == 1)) {
vec.Add(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.Count; 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;
// If vec is empty then cntSubarrNotSet
// should be 0 and not 1
if (vec.Count() == 0)
cntSubarrNotSet = 0;
// Variable to store count of subarrays
// whose bitwise OR will have i-th bit set
int cntSubarrIthSet = totalSubarrays - cntSubarrNotSet;
s += (int)(cntSubarrIthSet * Math.Pow(2, i));
}
return s;
}
// Driver code
public static void Main()
{
int[] A = { 1, 2, 3, 4, 5 };
int n = A.Length;
Console.WriteLine(givesum(A, n));
}
}
/* This code contributed by PrinciRaj1992 */
PHP
<?php
// PHP program to find sum of bitwise OR
// of all subarrays
// Function to find sum of bitwise OR
// of all subarrays
function givesum($A, $n)
{
// Find max element of the array
$max = max($A);
// Find the max bit position set in
// the array
$maxBit = (int)((log($max) /
log10(2)) + 1);
$totalSubarrays = (int)($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 = 0; $i < $maxBit; $i++)
{
$c1 = 0;
// Vector to store indexes of
// the array with i-th bit not set
$vec = array();
$sum = 0;
// Traverse the array
for ($j = 0; $j < $n; $j++)
{
// Check if ith bit is
// not set in A[j]
$a = $A[$j] >> $i;
if (!($a & 1))
{
array_push($vec, $j);
}
}
// Variable to store count of subarrays
// whose bitwise OR will have i-th bit
// not set
$cntSubarrNotSet = 0;
$cnt = 1;
for ($j = 1; $j < count($vec); $j++)
{
if ($vec[$j] - $vec[$j - 1] == 1)
{
$cnt++;
}
else
{
$cntSubarrNotSet += (int)($cnt *
($cnt + 1) / 2);
$cnt = 1;
}
}
// For last element of vec
$cntSubarrNotSet += (int)($cnt *
($cnt + 1) / 2);
// If vec is empty then cntSubarrNotSet
// should be 0 and not 1
if (count($vec) == 0)
$cntSubarrNotSet = 0;
// 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
$A = array( 1, 2, 3, 4, 5 );
$n = count($A);
echo givesum($A, $n);
// This code is contributed by mits
?>
JavaScript
<script>
// Javascript program to find sum of bitwise OR of all subarrays
// Function to find sum of bitwise OR
// of all subarrays
function givesum(A, n)
{
// Find max element of the array
let max = Number.MIN_VALUE;
for(let i = 0; i < A.length; i++)
{
max = Math.max(max, A[i]);
}
// Find the max bit position
// set in the array
let maxBit = Math.ceil(Math.log(max) + 1);
let totalSubarrays = n * (n + 1) / 2;
let s = 0;
// Traverse from 1st bit to last bit which
// can be set in any element of the array
for (let i = 0; i < maxBit; i++) {
// Vector to store indexes of the array
// with i-th bit not set
let vec = [];
// Traverse the array
for (let j = 0; j < n; j++) {
// Check if ith bit is not set in A[j]
let a = A[j] >> i;
if (!(a % 2 == 1)) {
vec.push(j);
}
}
// Variable to store count of subarrays
// whose bitwise OR will have i-th bit
// not set
let cntSubarrNotSet = 0;
let cnt = 1;
for (let j = 1; j < vec.length; 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;
// If vec is empty then cntSubarrNotSet
// should be 0 and not 1
if (vec.length == 0)
cntSubarrNotSet = 0;
// Variable to store count of subarrays
// whose bitwise OR will have i-th bit set
let cntSubarrIthSet = totalSubarrays - cntSubarrNotSet;
s += parseInt(cntSubarrIthSet * Math.pow(2, i), 10);
}
return s;
}
let A = [ 1, 2, 3, 4, 5 ];
let n = A.length;
document.write(givesum(A, n));
// This code is contributed by suresh07.
</script>
Time Complexity: O(N*logN)
Auxiliary Space: O(log(MAX(A))) where max(A) is the maximum element in A.
Similar Reads
Bitwise OR of all unordered pairs from a given array Given an array arr[] of size N, the task is to find the Bitwise XOR of all possible unordered pairs from the given array. Examples: Input: arr[] = {1, 5, 3, 7} Output: 7 Explanation: All possible unordered pairs are (1, 5), (1, 3), (1, 7), (5, 3), (5, 7), (3, 7) Bitwise OR of all possible pairs are
8 min read
Queries to calculate Bitwise OR of each subtree of a given node in an N-ary Tree Given an N-ary Tree consisting of N nodes valued from 1 to N, an array arr[] consisting of N positive integers, where arr[i] is the value associated with the ith node, and Q queries, each consisting of a node. The task for each query is to find the Bitwise OR of node values present in the subtree of
11 min read
Count pairs whose Bitwise AND exceeds Bitwise XOR from a given array Given an array arr[] of size N, the task is to count the number of pairs from the given array such that the Bitwise AND (&) of each pair is greater than its Bitwise XOR(^). Examples : Input: arr[] = {1, 2, 3, 4} Output:1Explanation:Pairs that satisfy the given conditions are: (2 & 3) > (2
6 min read
Count of Arrays of size N with elements in range [0, (2^K)-1] having maximum sum & bitwise AND 0 Given two integers N and K, The task is to find the count of all possible arrays of size N with maximum sum & bitwise AND of all elements as 0. Also, elements should be within the range of 0 to 2K-1. Examples: Input: N = 3, K = 2Output: 9Explanation: 22 - 1 = 3, so elements of arrays should be b
6 min read
Count of even set bits between XOR of two arrays Given two arrays A[] and B[] having N and M positive elements respectively. The task is to count the number of elements in array A with even number of set bits in XOR for every element of array B. Examples: Input: A[] = { 4, 2, 15, 9, 8, 8 }, B[] = { 3, 4, 22 } Output: 2 4 4 Explanation: Binary repr
11 min read