Problem 898

Abstract / Summary

Find the unique bitwise OR results of all possible subarrays within a given array of integers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
14 lines | 379 bytes | submitted May 9, 2024 | GitHub   20% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  1. Extend Existing Subarrays - Every value t stored in todo corresponds to the OR of a subarray that ends at the previous element. By OR-ing a with each t, 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)
  2. Start a New Subarray - The element a alone forms a subarray of length one, so its value is added to next.

     next.add(a)
  3. Collect Global Results - All values in next are merged into all. The union operator |= updates all in place, preserving previously discovered results.

     all |= next
  4. Prepare for the Next Iteration - todo is replaced by next, 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. all remains an empty set, and the method returns 0, correctly indicating that no subarrays exist.
  • Single-Element Input - For a list containing one integer, the inner comprehension produces an empty set because todo is initially empty. The element itself is added to next, then merged into all. The final count is 1, reflecting the sole subarray.
  • Zero Values - If an element is 0, the OR operation does not change existing bits. The algorithm still adds 0 as 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 next combines iteration and deduplication in a single step, eliminating the need for an explicit loop and a secondary deduplication pass.
  • In-Place Set Union - Updating all with the |= operator modifies the set directly, avoiding the creation of an intermediate set that would increase memory pressure.
  • State Pruning - After each iteration, todo is replaced by next. 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 older todo set 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.56 | σ = 0.92

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
26 links | 14 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

7 solutions   May 9, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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