Leetcode 898. Bitwise ORs of Subarrays
Given an array arr
of integers, find the number of unique results from all possible bitwise OR operations of subarrays.
Example:
Input: arr = [1,1,2]
Output: 3
Explanation: The possible subarrays are [1], [1], [2], [1,1], [1,2], [1,1,2]. The results of these OR operations are:
1 = 1
1 = 1
2 = 2
1 | 1 = 1
1 | 2 = 3
1 | 1 | 2 = 3
There are 3 unique values, so the answer is 3.
cur
: To store the results of OR operations ending at the current index.res
: To store all unique OR results.Iteration:
For each element in the array, update the cur
set to include results of OR operations combining the current element with all previous subarray results. Add all results to res
.
arr[i]
:
new_cur
set with arr[i]
.cur
, compute the OR operation with arr[i]
and add to new_cur
.arr[i]
, set cur
to new_cur
.Unique Results:
Insert the results of new_cur
into the res
set.
res
set will be the number of unique OR results.n
is the length of the array. Given the constraints, this approach should be efficient.import java.util.HashSet;
import java.util.Set;
public class Solution {
public int subarrayBitwiseORs(int[] arr) {
Set<Integer> res = new HashSet<>();
Set<Integer> cur = new HashSet<>();
for (int num : arr) {
Set<Integer> newCur = new HashSet<>();
newCur.add(num);
for (int x : cur) {
newCur.add(num | x);
}
cur = newCur;
res.addAll(cur);
}
return res.size();
}
}
res
(to store all unique OR results) and cur
(to store OR results ending with the current element).cur
set from the previous iteration.cur
set with these new OR results.cur
to res
.res
set, which represents the number of unique OR results.This approach ensures we efficiently track all unique results without redundant computations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?