Python 0898.py
class Solution:
def subarrayBitwiseORs(self, arr: List[int]) -> int:
all = set()
todo = set() # all ORed values up to the current position
for a in arr:
# extend with current value
next = set(a | t for t in todo)
next.add(a)
all |= next
todo = next
return len(all)
Difficulty
and has an acceptance rate of about 57% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method that determines how many distinct results can be obtained by applying the bitwise OR operation to every possible contiguous subarray of an integer list. It builds the collection of results incrementally while scanning the input once, using set data structures to guarantee uniqueness and to keep intermediate states compact.
Core Logic
The algorithm maintains two sets while iterating over the input list. The first set, named all, accumulates every distinct OR value that has been seen so far. The second set, called todo, holds the OR results that end at the current array position. For each element a in the input, a new set next is created by OR-ing a with each value already present in todo. The element itself is also added to next because a subarray consisting of a single element is a valid candidate. After constructing next, the algorithm merges it into all and then replaces todo with next for the next iteration.
all = set()
todo = set()
for a in arr:
next = set(a | t for t in todo)
next.add(a)
all |= next
todo = next
When the loop finishes, the size of all is returned, representing the total number of unique OR outcomes.
Step-by-Step Walkthrough
Initialization
Two empty sets are created. all will eventually contain the final answer, while todo tracks the OR values that terminate at the element currently being processed.
all = set()
todo = set()
Processing Each Element
For each integer a in the input list:
-
Extend Existing Subarrays - Every value
tstored intodocorresponds to the OR of a subarray that ends at the previous element. By OR-ingawith eacht, the code forms the OR results of those subarrays extended by the new element. This is performed with a set comprehension, which automatically discards duplicates.next = set(a | t for t in todo) -
Start a New Subarray - The element
aalone forms a subarray of length one, so its value is added tonext.next.add(a) -
Collect Global Results - All values in
nextare merged intoall. The union operator|=updatesallin place, preserving previously discovered results.all |= next -
Prepare for the Next Iteration -
todois replaced bynext, so that in the following loop iteration the algorithm works with the OR values that now end at the current position.todo = next
Final Result
After the loop, the method returns the cardinality of all, which is the count of distinct OR values across all subarrays.
return len(all)
Edge Cases Handled
The design naturally accommodates several boundary conditions:
- Empty Input - When the input list is empty, the loop body never executes.
allremains an empty set, and the method returns0, correctly indicating that no subarrays exist. - Single-Element Input - For a list containing one integer, the inner comprehension produces an empty set because
todois initially empty. The element itself is added tonext, then merged intoall. The final count is1, reflecting the sole subarray. - Zero Values - If an element is
0, the OR operation does not change existing bits. The algorithm still adds0as a possible result and correctly propagates it through subsequent extensions. - Repeated Numbers - When the same integer appears multiple times, the set structure ensures that duplicate OR results are stored only once, preventing unnecessary growth of the result collection.
- Large Integers - The bitwise OR operation works uniformly for any non-negative integer that fits within Python’s arbitrary-precision integer type, so the method remains correct regardless of magnitude.
Performance Optimizations
The implementation leverages several techniques to keep execution efficient:
- Incremental Construction - By focusing only on subarrays that end at the current index, the algorithm avoids recomputing OR values for earlier portions of the array. This incremental approach reduces the amount of work per element.
- Set Comprehension - The use of a set comprehension to generate
nextcombines iteration and deduplication in a single step, eliminating the need for an explicit loop and a secondary deduplication pass. - In-Place Set Union - Updating
allwith the|=operator modifies the set directly, avoiding the creation of an intermediate set that would increase memory pressure. - State Pruning - After each iteration,
todois replaced bynext. Because the OR operation is monotonic (adding more elements can only set additional bits, never clear them), many intermediate values become redundant as the scan progresses. Discarding the oldertodoset prevents the accumulation of stale entries, keeping the size of the working set bounded. - Avoidance of Nested Loops - The algorithm does not employ explicit nested loops over subarray boundaries. Instead, it relies on the mathematical properties of the OR operation to collapse many potential subarray calculations into a compact representation.
These choices collectively enable the method to handle input lists of considerable length while maintaining a manageable memory footprint and execution time.
ELI5 - Simplified Explanation
Imagine a treasure chest where a collection of numbers lives. The code goes through each number in the collection one by one, just like walking down a line of toys.
There is a small empty box that keeps track of special combinations. As the code looks at each new toy, it mixes that toy with everything already inside the small box. This mixing process uses a special math trick called OR, which is like stacking building blocks together to see what new shape they make. All these new shapes get added to a big pile.
The big pile holds onto every unique shape ever created. The code keeps doing this for every toy until the end of the line is reached. By the time the work is finished, the big pile contains all the different shapes that were possible to make.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 2401: Longest Nice Subarray
- problem 2411: Smallest Subarrays With Maximum Bitwise OR
- problem 2505: Bitwise OR of All Subsequence Sums
Solved On The Same Day
- problem 640: Solve the Equation
- problem 915: Partition Array into Disjoint Intervals
- problem 947: Most Stones Removed with Same Row or Column
- problem 974: Subarray Sums Divisible by K
- problem 978: Longest Turbulent Subarray
- problem 1508: Range Sum of Sorted Subarray Sums
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality