Input: arr =[1,1,2]Output: 3Explanation: The possible subarrays are [1],[1],[2],[1,1],[1,2],[1,1,2].These yield the results 1,1,2,1,3,3.There are 3 unique values, so the answer is3.
The key idea is to keep track of all possible bitwise OR results for subarrays ending at each position. Since OR is monotonic (adding more elements can only set more bits), the number of unique results per step is manageable. By iteratively updating the set of ORs for each subarray ending at the current index, we can efficiently collect all unique OR values.
classSolution {
publicintsubarrayBitwiseORs(int[] arr) {
Set<Integer> ans =new HashSet<>(), cur =new HashSet<>();
for (int x : arr) {
Set<Integer> nxt =new HashSet<>();
nxt.add(x);
for (int y : cur) nxt.add(y | x);
cur = nxt;
ans.addAll(cur);
}
return ans.size();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funsubarrayBitwiseORs(arr: IntArray): Int {
val ans = mutableSetOf<Int>()
var cur = mutableSetOf<Int>()
for (x in arr) {
val nxt = mutableSetOf(x)
for (y in cur) nxt.add(y or x)
cur = nxt
ans.addAll(cur)
}
return ans.size
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defsubarrayBitwiseORs(self, arr: list[int]) -> int:
ans: set[int] = set()
cur: set[int] = set()
for x in arr:
nxt = {x}
for y in cur:
nxt.add(y | x)
cur = nxt
ans |= cur
return len(ans)