Leetcode 898: Bitwise ORs of Subarrays

grid47
grid47
Exploring patterns and algorithms
Aug 9, 2024 5 min read

Given an array of integers, return the number of distinct bitwise OR results from all the non-empty subarrays. A subarray is a contiguous sequence of elements from the array, and the bitwise OR of a subarray is the bitwise OR of each of the integers in that subarray.
Problem
Approach
Steps
Complexity
Input: You are given an array of integers. Your task is to find the number of distinct bitwise OR results from all non-empty subarrays.
Example: Input: arr = [2, 4, 8]
Constraints:
• 1 <= arr.length <= 50000
• 0 <= arr[i] <= 10^9
Output: The output is an integer representing the number of distinct bitwise OR results from all non-empty subarrays.
Example: Output: 6
Constraints:
• The result should be an integer.
Goal: The goal is to count the number of distinct bitwise OR results from all the subarrays of the given array.
Steps:
• 1. Use two sets: one to track the current bitwise OR results for each subarray, and another to store the final distinct results.
• 2. For each element in the array, calculate the bitwise OR with each element from the previous subarrays and update the results.
• 3. Add the new results to the set of distinct results.
• 4. After processing the entire array, return the size of the distinct results set.
Goal: The problem requires counting distinct results of bitwise OR operations on subarrays within the given array length and element range.
Steps:
• The length of arr is between 1 and 50000.
• Each element of arr is between 0 and 10^9.
Assumptions:
• The input array will contain at least one element.
• The elements can be large integers, up to 10^9.
Input: Input: arr = [2, 4, 8]
Explanation: The distinct bitwise OR results from all subarrays are: 2, 4, 8, 6 (2 | 4), 12 (4 | 8), and 14 (2 | 4 | 8). The result is 6 distinct values.

Input: Input: arr = [0]
Explanation: The only subarray is [0], and the result is 0. So the output is 1.

Input: Input: arr = [1, 1, 2]
Explanation: The subarrays and their results are: [1], [1], [2], [1, 1], [1, 2], [1, 1, 2]. These give the OR results: 1, 1, 2, 1, 3, 3. There are 3 distinct results.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus