Count distinct Bitwise OR of all Subarrays

14 Jun, 2022
Given an array A of non-negative integers, where . The task is to count number of distinct possible results obtained by taking the bitwise OR of all the elements in all possible Subarrays.Examples:  
Input: A = [1, 2]
Output: 3
Explanation: The possible subarrays are [1], [2], [1, 2].
These Bitwise OR of subarrays are 1, 2, 3.
There are 3 distinct values, so the answer is 3.

Input: A = [1, 2, 4]
Output: 6
Explanation: The possible distinct values are 1, 2, 3, 4, 6, and 7.
Approach: The Naive approach is to generate all possible subarrays and take bitwise OR of all elements in the subarray. Store each result in set and return length of the set. Efficient Approach: We can make the above approach better. The Naive approach is to calculate all possible result where, res(i, j) = A[i] | A[i+1] | ... | A[j]. However we can speed this up by taking note of the fact that res(i, j+1) = res(i, j) | A[j+1]. At the kth step, say we have all of the res(i, k) in some set pre. Then we can find the next pre set (for k -> k+1) by using res(i, k+1) = res(i, k) | A[k+1].However, the number of unique values in this set pre is atmost 32, since the list res(k, k), res(k-1, k), res(k-2, k), ... is monotone increasing, and any subsequent values that are different from previous must have more 1’s in it’s binary representation which can have maximum of 32 ones.Below is the implementation of above approach.  
Python
# Python implementation of the above approach # function to return count of distinct bitwise ORdef subarrayBitwiseOR(A):     # res contains distinct values    res = set()     pre = {0}     for x in A:        pre = {x | y for y in pre} | {x}        res |= pre     return len(res)  # Driver programA = [1, 2, 4] # print required answerprint(subarrayBitwiseOR(A)) # This code is written by# Sanjit_Prasad
6
Time Complexity: O(N*log(K)), where N is the length of A, and K is the maximum size of elements in A.
C++ implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // function to calculate count of// distinct bitwise OR of all// subarrays.int distintBitwiseOR(int arr[], int n){    unordered_set<int> ans, prev;     for (int i = 0; i < n; i++) {        unordered_set<int> ne;         for (auto x : prev)            ne.insert(arr[i] | x);        ne.insert(arr[i]);         for (auto x : ne)            ans.insert(x);         prev = ne;    }     return ans.size();} // Driver Codeint main(){    int n = 3;    int arr[] = { 1, 2, 4 };     cout << distintBitwiseOR(arr, n);     return 0;}
// Java implementation of the above approachimport java.io.*;import java.util.*; class GFG{     // function to calculate count of// distinct bitwise OR of all// subarrays. static int distintBitwiseOR(int arr[], int n)  {         HashSet<Integer>ans = new HashSet<>();        HashSet<Integer>prev = new HashSet<>();        for(int i = 0; i < n; i++)        {            HashSet<Integer>ne = new HashSet<>();            ne.add(arr[i]);            for(int x :prev)            {                ne.add(arr[i]|x);            }            for(int x :ne)            {              ans.add(x);            }                        prev = ne;        }        return ans.size();    }      // Driver code    public static void main (String[] args) {         int n = 3;         int arr[] = { 1, 2, 4 };         System.out.println(distintBitwiseOR(arr, n));              }} // This code is contributed by iramkhalid24.
# Python implementation of the above approach # function to calculate count of# distinct bitwise OR of all# subarrays.def distintBitwiseOR(arr,n):     ans,prev = set(), set()     for i in range(n):        ne = set()         for x in prev:            ne.add(arr[i] | x)        ne.add(arr[i])         for x in ne:            ans.add(x)         prev = ne     return len(ans) # Driver Coden = 3arr = [ 1, 2, 4 ] print(distintBitwiseOR(arr, n)) # This code is written by Shinjanpatra
// C# implementation of the above approachusing System;using System.Collections.Generic; public class GFG{   // function to calculate count of  // distinct bitwise OR of all  // subarrays.  static int distintBitwiseOR(int[] arr, int n)  {     HashSet<int> ans = new HashSet<int>();    HashSet<int> prev = new HashSet<int>();     for (int i = 0; i < n; i++) {      HashSet<int> ne = new HashSet<int>();      ne.Add(arr[i]);      foreach(var x in prev) { ne.Add(arr[i] | x); }       foreach(var x in ne) { ans.Add(x); }       prev = ne;    }    return ans.Count;  }   // Driver code  public static void Main(string[] args)  {    int n = 3;    int[] arr = { 1, 2, 4 };     // Function call    Console.WriteLine(distintBitwiseOR(arr, n));  }} // This code is contributed by phasing17
<script> // JavaScript implementation of the above approach // function to calculate count of// distinct bitwise OR of all// subarrays.function distintBitwiseOR(arr,n){    let ans = new Set(), prev = new Set();     for (let i = 0; i < n; i++) {        let ne = new Set();         for (let x of prev)            ne.add(arr[i] | x);        ne.add(arr[i]);         for (let x of ne)            ans.add(x);         prev = ne;    }     return ans.size;} // Driver Code let n = 3;let arr = [ 1, 2, 4 ]; document.write(distintBitwiseOR(arr, n)); // This code is written by Shinjanpatra </script>
6
 
pawanharwani11
iramkhalid24
shinjanpatra
phasing17
Bitwise-OR
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
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Introduction to Arrays
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Little and Big Endian Mystery
How to swap two numbers without using a temporary variable?