Bitwise ORs of Subarrays - Problem
Find all unique bitwise OR values across every possible subarray of an integer array.

Given an integer array arr, you need to calculate the bitwise OR of every contiguous subarray and count how many distinct values you get.

For example, with array [1, 1, 2]:
• Subarrays: [1], [1], [2], [1,1], [1,2], [1,1,2]
• Their ORs: 1, 1, 2, 1, 3, 3
• Distinct values: {1, 2, 3} → Answer: 3

Challenge: Can you solve this efficiently without checking every subarray individually?

Input & Output

example_1.py — Small Array
$ Input: [1, 1, 2]
Output: 3
💡 Note: Subarrays and their ORs: [1]→1, [1]→1, [2]→2, [1,1]→1, [1,2]→3, [1,1,2]→3. Unique values: {1, 2, 3}, so answer is 3.
example_2.py — Powers of 2
$ Input: [1, 2, 4]
Output: 6
💡 Note: All subarrays: [1]→1, [2]→2, [4]→4, [1,2]→3, [2,4]→6, [1,2,4]→7. All ORs are distinct: {1,2,3,4,6,7}, giving answer 6.
example_3.py — Single Element
$ Input: [0]
Output: 1
💡 Note: Only one subarray [0] with OR value 0, so there's exactly 1 distinct value.

Visualization

Tap to expand
Paint Mixing Analogy112Paint 1Paint 2Paint 3Step 11Colors: {1}Step 211Colors: {1}Step 3123Colors: {1,2,3}Final Result3 Unique Colors
Understanding the Visualization
1
Start with first paint
Begin with paint bucket containing color 1
2
Add second paint
Mixing paint 1 with paint 1 still gives color 1
3
Add third paint
Mixing with paint 2 creates new colors: pure 2 and mixed 3
4
Count unique colors
Final palette contains 3 distinct colors: {1, 2, 3}
Key Takeaway
🎯 Key Insight: Bitwise OR can only set bits (add colors), never unset them. With 32 bits maximum, each position contributes at most 32 distinct values, making the solution surprisingly efficient!

Time & Space Complexity

Time Complexity
⏱️
O(n × 32)

Each position processes at most 32 distinct OR values from previous position, leading to linear time in practice

n
2n
Linear Growth
Space Complexity
O(32)

Sets store at most 32 distinct OR values at any point, plus the result set

n
2n
Linear Space

Constraints

  • 1 ≤ arr.length ≤ 5 × 104
  • 0 ≤ arr[i] ≤ 109
  • Each integer fits in 32 bits (key insight for optimization)
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 23
68.5K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen