#898

Bitwise ORs of Subarrays

Medium
ArrayDynamic ProgrammingBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the properties of the bitwise OR operation, where the result can only grow as we include more elements. By maintaining a running OR and using a set to track distinct results, we can efficiently compute the unique ORs without generating all subarrays.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a set to store unique bitwise OR results.
  2. 2Step 2: Use a variable to keep track of the current OR and an array to store the last seen ORs for each position.
  3. 3Step 3: Iterate through the array, updating the current OR and adding it to the set, while also updating the last seen ORs.
solution.py12 lines
1def subarrayBitwiseOR(arr):
2    unique_or = set()
3    current_or = 0
4    last_seen = []
5    for num in arr:
6        current_or = 0
7        for last in last_seen:
8            current_or |= last
9        current_or |= num
10        unique_or.add(current_or)
11        last_seen.append(current_or)
12    return len(unique_or)

Complexity note: The time complexity is O(n) because we only traverse the array once. The space complexity is O(n) due to the storage of unique OR results in a set.

  • 1The bitwise OR operation accumulates bits, meaning once a bit is set, it remains set for all subsequent ORs.
  • 2Distinct results can be efficiently tracked using a set, avoiding duplicates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.