Bitwise ORs of Subarrays

medium bit manipulation bitwise or set

Problem

Given an integer array arr, take the bitwise OR of every contiguous subarray. Return the number of distinct values among all those subarray ORs.

Inputarr = [1, 1, 2]
Output3
The subarray ORs are 1, 1, 2, 1, 3, 3. The distinct values are {1, 2, 3}, so the answer is 3.

def subarray_bitwise_ors(arr):
    result = set()
    cur = set()
    for x in arr:
        cur = {x | y for y in cur} | {x}
        result |= cur
    return len(result)
function subarrayBitwiseORs(arr) {
  const result = new Set();
  let cur = new Set();
  for (const x of arr) {
    const next = new Set([x]);
    for (const y of cur) next.add(x | y);
    cur = next;
    for (const v of cur) result.add(v);
  }
  return result.size;
}
class Solution {
    public int subarrayBitwiseORs(int[] arr) {
        Set<Integer> result = new HashSet<>();
        Set<Integer> cur = new HashSet<>();
        for (int x : arr) {
            Set<Integer> next = new HashSet<>();
            next.add(x);
            for (int y : cur) next.add(x | y);
            cur = next;
            result.addAll(cur);
        }
        return result.size();
    }
}
int subarrayBitwiseORs(vector<int>& arr) {
    unordered_set<int> result, cur;
    for (int x : arr) {
        unordered_set<int> next;
        next.insert(x);
        for (int y : cur) next.insert(x | y);
        cur = next;
        result.insert(cur.begin(), cur.end());
    }
    return (int)result.size();
}
Time: O(n · 32) Space: O(n · 32)