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.
Input: A = [1, 2] Output: 3 Explanation: The possible subarrays are , , [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.
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.
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.
Time Complexity: O(N*log(K)), where N is the length of A, and K is the maximum size of elements in A.
- Count subarrays having total distinct elements same as original array
- Sum of bitwise OR of all subarrays
- Sum of bitwise AND of all subarrays
- Sum of Bitwise-OR of all subarrays of a given Array | Set 2
- Number of subarrays have bitwise OR >= K
- Subarrays with distinct elements
- Count the number of subarrays having a given XOR
- Count subarrays with Prime sum
- Count subarrays with same even and odd elements
- Count subarrays with all elements greater than K
- Count the number of non-increasing subarrays
- Count Strictly Increasing Subarrays
- Count subarrays with equal number of 1's and 0's
- Count pairs with bitwise OR less than Max
- Count of subarrays whose maximum element is greater than k
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.