Bitwise ORs of Subarrays — LeetCode 898 Python Solution
MediumBit ManipulationArrayDynamic Programming
- Problem
- #898
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M) |
| Space | O(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.