Leetcode 898. Bitwise ORs of Subarrays
The problem is to find the number of distinct values that can be obtained by performing bitwise OR on all subarrays of a given array.
Input:
A = [1, 2, 4]
Output:
6
Explanation: The subarrays are [1], [1, 2], [1, 2, 4], [2], [2, 4], [4]. Their corresponding bitwise ORs are 1, 3, 7, 2, 6, 4. The distinct values are: 1, 2, 3, 4, 6, 7.
Here’s the implementation of the above strategy in C++:
#include <vector>
#include <unordered_set>
int subarrayBitwiseORs(std::vector<int>& A) {
std::unordered_set<int> res;
std::unordered_set<int> cur;
for (int num : A) {
std::unordered_set<int> next;
next.insert(num);
for (int val : cur) {
next.insert(num | val);
}
cur = std::move(next);
for (int val : cur) {
res.insert(val);
}
}
return res.size();
}
res
to store all distinct OR results and cur
to store current OR results.num
in the array:
next
and initialize it with num
(this handles the single-element subarray case).cur
, compute the OR with num
and add it to next
.cur
to be next
, effectively shifting the currently considered subarray window.cur
to the result set res
.res
contains all distinct OR values from subarrays.The time complexity of this approach is as follows:
Thus, the overall time complexity is approximately ( O(n^2) ). This should be efficient enough for ( n ) up to 5000.
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?