Given an array arr
, you need to find the number of distinct values that can be obtained by taking the bitwise OR of all possible subarrays (non-empty) of arr
.
arr
?
n
where 1 <= n <= 50000
.0
to 10^9
.1
if at least one of the corresponding bits of the operands is 1
.Here’s how you can implement this strategy:
def subarrayBitwiseORs(arr):
res = set() # To hold all distinct OR results
cur = set() # Current set of OR results
for num in arr:
cur = {num | x for x in cur} | {num} # Include the number itself and OR with all previous results
res |= cur # Merge current OR results into the global set of results
return len(res) # Return the count of distinct OR results
# Example usage:
# arr = [1, 2, 4]
# print(subarrayBitwiseORs(arr)) # Output should be the count of distinct bitwise OR results
Time Complexity: The worst-case scenario involves creating up to O(n)
new OR results at each step, leading to a total complexity of O(n^2)
. However, the union operations with sets help reduce redundancy.
Space Complexity: The space required is O(n)
for tracking current OR results, but the total space utilized can grow due to the set of distinct results.
The strategy and approach ensure that the problem is dealt with in an efficient manner, suitable for the given constraints.
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?