Taro Logo

Bitwise ORs of Subarrays

#130 Most AskedMedium
Topics:
ArraysBit Manipulation

Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr.

The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: arr = [0]
Output: 1
Explanation: There is only one possible result: 0.

Example 2:

Input: arr = [1,1,2]
Output: 3
Explanation: 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 is 3.

Example 3:

Input: arr = [1,2,4]
Output: 6
Explanation: The possible results are 1, 2, 3, 4, 6, and 7.

Constraints:

  • 1 <= arr.length <= 5 * 104
  • 0 <= arr[i] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the input array and the range of values for its elements?
  2. Can the input array contain negative numbers, zeros, or only positive integers?
  3. How should an empty input array be handled, and what should be the expected return value in that case?
  4. Does the problem guarantee that the resulting count of unique bitwise OR values will fit within standard integer limits?
  5. Are elements with identical values considered distinct based on their positions in the array, or should duplicate values be treated uniformly?

Brute Force Solution

Approach

We need to find all the unique results you can get by combining numbers in different parts of a list using a special rule. The brute force approach is like trying every single possible part of the list and combining the numbers in it to see what results we get.

Here's how the algorithm would work step-by-step:

  1. First, consider the result you get from just the first number in the list.
  2. Then, consider the result from the first two numbers, then the first three, and so on, up to the entire list.
  3. Next, start at the second number in the list and consider the result from just that number.
  4. Then consider the result from the second and third numbers, the second, third, and fourth, and so on, up to the end of the list.
  5. Keep repeating this process, each time starting one number later in the list, until you reach the last number alone.
  6. Each time you combine the numbers in a part of the list, remember the result you get.
  7. At the end, look at all the results you remembered, and remove any duplicates so you only have the unique results.

Code Implementation

def bitwise_ors_of_subarrays_brute_force(numbers):
    unique_results = set()

    # Iterate through each starting index of the subarray
    for start_index in range(len(numbers)): 
        current_bitwise_or = 0

        # Iterate through each ending index of the subarray, beginning at start_index
        for end_index in range(start_index, len(numbers)): 
            current_bitwise_or |= numbers[end_index]

            # Add the current bitwise OR to the set of unique results
            unique_results.add(current_bitwise_or)

    # Converting to list to return
    return list(unique_results)

Big(O) Analysis

Time Complexity
O(n²) – The algorithm iterates through all possible subarrays of the input array of size n. The outer loop starts at each index i from 0 to n-1. The inner loop iterates from i to n-1, calculating the bitwise OR of the subarray starting at index i. Therefore, for each starting index i, the algorithm performs (n-i) operations. The total number of operations is approximately n + (n-1) + (n-2) + ... + 1, which is n*(n+1)/2. Simplifying this expression, the time complexity is O(n²).
Space Complexity
O(N) – The algorithm remembers all unique bitwise OR results encountered. In the worst-case scenario, where all subarrays produce unique bitwise OR results, the number of unique results could be proportional to the number of subarrays. The number of subarrays is roughly N*(N+1)/2, where N is the length of the input array. Thus, storing these unique results requires auxiliary space proportional to O(N^2). However, since a bitwise OR operation can only produce values between 0 and the maximum possible value representable within the bits of the integer which is constant, and the maximum possible unique value can only be N, the auxiliary space is O(N) since we use a set to store unique values. The set to store unique results dominates the space complexity.

Optimal Solution

Approach

Instead of recalculating every possible combination from scratch, the optimal approach builds results progressively from left to right. It realizes that as you consider larger groups of numbers, the combined values can only grow or stay the same, creating a very small number of unique totals to remember.

Here's how the algorithm would work step-by-step:

  1. Begin at the very first number in the sequence and note its value as your first unique total.
  2. Move to the next number and combine it with everything you built so far, creating a fresh set of possible totals.
  3. Filter out any duplicate totals so you only keep the distinct values that are genuinely new.
  4. Add these new distinct values to your master collection of all unique totals ever seen.
  5. Repeat this expanding process for each subsequent position in the entire sequence, carrying forward only the active totals from the previous step.
  6. Once you reach the very end of the sequence, count how many distinct totals accumulated in your master collection.

Code Implementation

class Solution:
    def subarrayBitwiseORs(self, array_of_numbers: list[int]) -> int:
        master_collection = set()
        current_active_totals = set()

        # We iterate through each number to dynamically build all possible subarray OR combinations.
        for current_number in array_of_numbers:
            
            next_active_totals = {current_number | previous_total for previous_total in current_active_totals}
            next_active_totals.add(current_number)
            
            current_active_totals = next_active_totals
            master_collection.update(current_active_totals)

        # Returning the total count of distinct values accumulated across all valid subarrays.
        return len(master_collection)

Big(O) Analysis

Time Complexity
O(30n) – As we iterate through each of the n elements in the array to compute subarray bitwise ORs, the number of unique OR values ending at any given position cannot exceed the number of bits in an integer, which is at most 30. For each of the n positions, we process a previous set of at most 30 unique totals to generate the new set. This means the inner operations are capped at a constant size of 30 rather than growing with n. Thus, the total operations scale linearly as approximately 30 times n, which simplifies to O(n).
Space Complexity
O(30N) – To implement the progressive building and filtering steps described, the algorithm maintains a master collection set of unique totals and a smaller active set of current subarray OR values for the most recent position. Because the bitwise OR operation can only set bits and never exceed the maximum integer size of approximately thirty bits, the active set of totals ending at any given position can never exceed thirty elements. As we iterate through all N elements of the sequence, these dynamic sets accumulate at most thirty unique values per index. Therefore, the auxiliary space complexity simplifies to Big O of N after dropping the constant factor.

Edge Cases

Empty array or null input
How to Handle:
Return zero immediately as no subarrays can be formed from an empty input.
Array with a single element
How to Handle:
Return one because only a single subarray exists, resulting in one unique bitwise OR value.
Maximum length array with large constraints
How to Handle:
Utilize the property that bitwise OR results only grow, limiting the number of unique values per ending index to at most thirty-two to pass within time limits.
Array containing all identical values
How to Handle:
The algorithm efficiently collapses overlapping subarray results, resulting in just a single unique bitwise OR value added to the global set.
Array containing zeros
How to Handle:
Zero acts as an identity element for bitwise OR operations, which the cumulative reduction handles naturally without special conditional branches.
Inputs with negative integers
How to Handle:
Negative numbers in two's complement representation have their sign bit set, which propagates correctly through standard bitwise OR operations.
Array with alternating or maximally varied bits
How to Handle:
The running set of results will quickly reach maximum bit capacity and stabilize, preventing unnecessary duplicate computations in subsequent iterations.
Language-specific integer overflow
How to Handle:
Ensure standard integer types are used that conform to the bit-width requirements of the bitwise operations without causing unexpected sign extensions.
0/245 completed