Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

898. Bitwise ORs of Subarrays

Explanation

To solve this problem, we can iterate through the array and keep track of the possible bitwise ORs of all the subarrays ending at each index. We can use a set to store the unique values of bitwise ORs.

  1. Initialize a set to store unique bitwise OR results.
  2. Initialize a set to store the bitwise OR results that end at each index.
  3. Iterate through the array:
    • For each element, calculate the bitwise OR with each value in the set of bitwise ORs ending at the previous index and add the result to the set of bitwise ORs ending at the current index.
    • Add the element itself to the set of bitwise ORs ending at the current index.
    • Add all values in the set of bitwise ORs ending at the current index to the main set of unique bitwise ORs.
  4. Return the size of the set of unique bitwise ORs.

Time complexity: O(n * log(max(arr))) Space complexity: O(n)

class Solution {
    public int subarrayBitwiseORs(int[] arr) {
        Set<Integer> uniqueORs = new HashSet<>();
        Set<Integer> curORs = new HashSet<>();
        
        for (int num : arr) {
            Set<Integer> newCurORs = new HashSet<>();
            for (int prev : curORs) {
                newCurORs.add(num | prev);
            }
            newCurORs.add(num);
            curORs = newCurORs;
            uniqueORs.addAll(curORs);
        }
        
        return uniqueORs.size();
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.