898. Bitwise ORs of Subarrays #1992
-
Topics: Given an integer array The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A subarray is a contiguous non-empty sequence of elements within an array. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the number of distinct bitwise ORs of all non-empty contiguous subarrays in a given integer array. The challenge is to compute this efficiently given the constraints, especially since a brute-force approach would be infeasible for large arrays. Approach
Let's implement this solution in PHP: 898. Bitwise ORs of Subarrays <?php
/**
* @param Integer[] $arr
* @return Integer
*/
function subarrayBitwiseORs($arr) {
$ans = array();
$cur = array();
foreach ($arr as $x) {
$next_cur = array();
$next_cur[$x] = true;
foreach ($cur as $key => $dummy) {
$val = $key | $x;
$next_cur[$val] = true;
}
$cur = $next_cur;
foreach ($cur as $key => $dummy) {
$ans[$key] = true;
}
}
return count($ans);
}
// Test cases
$arr1 = [0];
$arr2 = [1, 1, 2];
$arr3 = [1, 2, 4];
echo subarrayBitwiseORs($arr1) . "\n"; // Output: 1
echo subarrayBitwiseORs($arr2) . "\n"; // Output: 3
echo subarrayBitwiseORs($arr3) . "\n"; // Output: 6
?> Explanation:
This approach efficiently tracks distinct OR values by leveraging the bounded nature of bitwise operations, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to find the number of distinct bitwise ORs of all non-empty contiguous subarrays in a given integer array. The challenge is to compute this efficiently given the constraints, especially since a brute-force approach would be infeasible for large arrays.
Approach