Count Good Subarrays Problem
Description
LeetCode Problem 3878.
You are given an integer array nums.
A subarray is called good if the bitwise OR of all its elements is equal to at least one element present in that subarray.
Return the number of good subarrays in nums.
Here, the bitwise OR of two integers a and b is denoted by a | b.
Example 1:
Input: nums = [4,2,3]
Output: 4
Explanation:
The subarrays of nums are:
Subarray Bitwise OR Present in Subarray
[4] 4 = 4 Yes
[2] 2 = 2 Yes
[3] 3 = 3 Yes
[4, 2] 4 | 2 = 6 No
[2, 3] 2 | 3 = 3 Yes
[4, 2, 3] 4 | 2 | 3 = 7 No
Thus, the good subarrays of nums are [4], [2], [3] and [2, 3]. Thus, the answer is 4.
Example 2:
Input: nums = [1,3,1]
Output: 6
Explanation:
Any subarray of nums containing 3 has bitwise OR equal to 3, and subarrays containing only 1 have bitwise OR equal to 1.
In both cases, the result is present in the subarray, so all subarrays are good, and the answer is 6.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Monotonic Stack + Contribution Counting
A subarray is good when its OR equals one of its elements. Count, for each index i, the subarrays whose OR is exactly nums[i] and for which i is the chosen occurrence.
The OR of a subarray equals nums[i] when every element is a bit-subset of nums[i], that is nums[k] | nums[i] == nums[i]. A monotonic stack finds the nearest left index l[i] and the nearest right index r[i] whose element is not such a subset. To avoid counting a subarray once per equal element, the left pass stops at an equal value (it only pops strictly smaller subsets), while the right pass skips over equal ones. Then every subarray (a, b) with l[i] < a <= i <= b < r[i] is counted once, which gives (i - l[i]) * (r[i] - i) subarrays for index i.
The answer is the sum over all i.
Complexity: time O(n), space O(n), where n is the length of the array.
class Solution:
def countGoodSubarrays(self, nums: List[int]) -> int:
n = len(nums)
l = [-1] * n
stk = []
for i, x in enumerate(nums):
while stk and nums[stk[-1]] < x and (nums[stk[-1]] | x) == x:
stk.pop()
l[i] = stk[-1] if stk else -1
stk.append(i)
r = [n] * n
stk = []
for i in range(n - 1, -1, -1):
while stk and (nums[stk[-1]] | nums[i]) == nums[i]:
stk.pop()
r[i] = stk[-1] if stk else n
stk.append(i)
return sum((i - l[i]) * (r[i] - i) for i in range(n))