Count Consistent Subarrays II Problem
Description
LeetCode Problem 4114.
You are given an integer array nums.
A subarray is called consistent if the bitwise AND of all its elements is equal to the minimum value of the subarray.
Return the number of consistent subarrays in nums.
Example 1:
Input: nums = [5,3,1,2]
Output: 6
Explanation:
The following subarrays are consistent:
Subarray Values Bitwise AND Minimum Value
nums[0..0] [5] 5 5
nums[1..1] [3] 3 3
nums[2..2] [1] 1 1
nums[3..3] [2] 2 2
nums[1..2] [3, 1] 3 AND 1 = 1 1
nums[0..2] [5, 3, 1] 5 AND 3 AND 1 = 1 1
Therefore, the number of consistent subarrays is 6.
Example 2:
Input: nums = [1,1,1]
Output: 6
Explanation:
For every subarray, both the bitwise AND and the minimum value are equal to 1. Therefore, the answer is 6.
Example 3:
Input: nums = [0]
Output: 1
Explanation:
The only subarray is [0], whose bitwise AND and minimum value are both 0. Therefore, the answer is 1.
Constraints:
1 <= nums.length <= 2 * 10^50 <= nums[i] <= 10^6
Solution
Approach: Monotonic Stack
Say a contains b when a & b == b; then a >= b. The AND of a subarray is contained in every element, so it is at most the minimum. It equals the minimum exactly when every element contains the minimum.
Count each consistent subarray once, at the rightmost index i of its minimum x = nums[i]. We need how far the subarray can reach:
- To the left, up to (but not including)
left[i], the nearest index whose value does not containx. Scan left to right with a stack, pop while the top containsx, and the top that remains isleft[i](or-1). - To the right, up to (but not including)
right, the nearest index whose value equalsxor does not containx. Scan right to left, pop while the top is different fromxand containsx, and the top that remains isright(orn).
The left end can be any of i - left[i] positions and the right end any of right - i, so index i adds (i - left[i]) * (right - i) subarrays.
Complexity: O(n) time and O(n) space, since each index is pushed and popped once in each scan.
class Solution:
def countConsistent(self, nums: List[int]) -> int:
n = len(nums)
# a contains b when a & b == b. A subarray is consistent when every element contains its minimum.
# Count each consistent subarray once, at the rightmost index i of its minimum x = nums[i].
# left[i]: the nearest index to the left whose value misses a bit of x
left = [-1] * n
stack = []
for i in range(n):
x = nums[i]
while stack and nums[stack[-1]] & x == x:
stack.pop()
if stack:
left[i] = stack[-1]
stack.append(i)
# right: the nearest index to the right whose value equals x or misses a bit of x
stack = []
ans = 0
for i in range(n - 1, -1, -1):
x = nums[i]
while stack and nums[stack[-1]] != x and nums[stack[-1]] & x == x:
stack.pop()
right = stack[-1] if stack else n
stack.append(i)
ans += (i - left[i]) * (right - i)
return ans