Problem Description
Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr. A subarray is a contiguous sequence of elements, and the bitwise OR of a subarray is the result of applying the OR operation to every element in that subarray.
Key Insights
- Instead of evaluating every subarray explicitly, dynamic programming can be used to update the OR values for subarrays ending at each index.
- When processing each element, all previous subarray OR results are combined (using bitwise OR) with the current element to capture the essence of extending subarrays.
- A global set is maintained to collect all distinct OR results, avoiding duplicates.
- The maximum number of distinct OR results from combining numbers is bounded by the number of bits, ensuring efficient processing.
Space and Time Complexity
Time Complexity: O(n * 32), which simplifies to O(n) due to the bounded number of bits. Space Complexity: O(n) in the worst-case for storing results in a set.
Solution
The algorithm maintains a temporary set, current_or_set, that contains all the distinct OR values ending at the current index. For each new element, it computes a new set by OR-ing the current element with each value in current_or_set and also adds the current element itself (representing subarrays that only include that element). This new set represents all distinct OR values for subarrays ending at the current element. These values are then added to a global set, distinct_results, to ensure all unique OR results are tracked throughout the array. The final answer is the size of distinct_results.