Bitwise ORs of Subarrays — LeetCode 898 Python Solution

MediumBit ManipulationArrayDynamic Programming
Problem
#898
Reading time
2 min

The 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.

Example

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

Python solution

Python
class Solution:
    def subarrayBitwiseORs(self, arr: List[int]) -> int:
        ans = set()
        s = set()
        for x in arr:
            s = {x | y for y in s} | {x}
            ans |= s
        return len(ans)

Complexity

MeasureComplexity
TimeO(n \times \log M)
SpaceO(n \times \log M) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 898. Bitwise ORs of Subarrays is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 898. Bitwise ORs of Subarrays?
LeetCode 898. Bitwise ORs of Subarrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 898. Bitwise ORs of Subarrays?
The Python solution on this page runs in O(n \times \log M).
What is the space complexity of LeetCode 898. Bitwise ORs of Subarrays?
The Python solution on this page uses O(n \times \log M) auxiliary space.
What topics does LeetCode 898. Bitwise ORs of Subarrays cover?
LeetCode 898. Bitwise ORs of Subarrays is tagged Bit Manipulation, Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview