Bitwise ORs of Subarrays - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: arr = [0]
Output: 1
💡 Note: Only one subarray [0], with bitwise OR = 0. So there is 1 distinct value.
Example 2 — Multiple Elements
$ Input: arr = [1,1,2]
Output: 3
💡 Note: Subarrays: [1]=1, [1]=1, [2]=2, [1,1]=1, [1,2]=3, [1,1,2]=3. Distinct ORs: {1,2,3}.
Example 3 — All Same Elements
$ Input: arr = [1,2,4]
Output: 6
💡 Note: Subarrays: [1]=1, [2]=2, [4]=4, [1,2]=3, [2,4]=6, [1,2,4]=7. Distinct ORs: {1,2,3,4,6,7}.

Constraints

  • 1 ≤ arr.length ≤ 5 × 104
  • 0 ≤ arr[i] ≤ 109

Visualization

Tap to expand
Bitwise ORs of Subarrays Set Propagation Approach INPUT Input Array: arr arr[0] 0 Binary: 0000 All Subarrays: [0] (only 1 subarray) Bitwise OR of [0]: 0 | = 0 ALGORITHM STEPS 1 Initialize Sets result = {}, curr = {} 2 Process arr[0]=0 new_curr = {0|0} = {0} 3 Update curr Set curr = {0} 4 Add to Result result = {0} Set Propagation: {0} curr --> {0} result FINAL RESULT Distinct OR Values Found: result set { 0 } Count of distinct values: Output 1 OK - Verified |result| = 1 Only one subarray [0] with OR value = 0 Key Insight: Set Propagation tracks all possible OR values ending at each index. For each new element, we OR it with all previous OR values in curr set, plus itself. This avoids O(n^2) subarray enumeration since OR values grow monotonically (at most 32 distinct values per position). TutorialsPoint - Bitwise ORs of Subarrays | Set Propagation Approach
Asked in
Google 25 Facebook 18
25.4K Views
Medium Frequency
~25 min Avg. Time
890 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