MediumNo. 0898
Bitwise ORs of Subarrays — LeetCode 898 Python Solution
- Pattern
- Bit Manipulation
- Topics
- Bit Manipulation, Array, Dynamic Programming
- 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
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
- Time
- O(n × log M)
- Space · auxiliary
- O(n × log M)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0473 | Matchsticks to Square | Medium |
| 0526 | Beautiful Arrangement | Medium |
| 0638 | Shopping Offers | Medium |
| 0698 | Partition to K Equal Sum Subsets | Medium |
| 0805 | Split Array With Same Average | Hard |
| 0943 | Find the Shortest Superstring | Hard |
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 × log M).
- What is the space complexity of LeetCode 898. Bitwise ORs of Subarrays?
The Python solution on this page uses O(n × 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.