Bitwise ORs of Subarrays in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A of non-negative integers. For every (contiguous) subarray say B = [A[i], A[i+1], ..., A[j]] (with i <= j), we will do the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | ... | A[j]. We have to find the number of possible results. (Results that occur more than once are only counted once in the final answer.)

So if the input is like [1,1,2], then the result will be 3 as subarrays are [1], [1], [2], [1,1], [1,2], [1,1,2], then the results will be 1,1,2,1,3,3, then there are three distinct results.

To solve this, we will follow these steps −

  • Create two sets ret and curr2

  • for i in range 0 to size of array

    • make a set curr1, insert A[i] into it

    • for each element e in curr2 −

      • insert (e OR A[i]) into curr1

    • for each element e curr1

      • insert e in ret

    • curr2 := curr1

  • return size of ret

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int subarrayBitwiseORs(vector<int>& A) {
      unordered_set <int> ret;
      unordered_set <int> curr2;
      for(int i = 0; i < A.size(); i++){
         unordered_set <int> curr1;
         curr1.insert(A[i]);
         unordered_set<int>::iterator it = curr2.begin();
         while(it != curr2.end()){
            curr1.insert(*it | A[i]);
            it++;
         }
         it = curr1.begin();
         while(it != curr1.end()){
            ret.insert(*it);
            it++;
         }
         curr2 = curr1;
      }
      return ret.size();
   }
};
main(){
   vector<int> v = {1,1,2};
   Solution ob;
   cout << (ob.subarrayBitwiseORs(v));
}

Input

[1,1,2]

Output

3
raja
Updated on 30-Apr-2020 10:59:30

Advertisements