Number of Subarrays With AND Value of K Problem
Description
LeetCode Problem 3209.
Given an array of integers nums and an integer k, return the number of subarrays of nums where the bitwise AND of the elements of the subarray equals k.
Example 1:
Input: nums = [1,1,1], k = 1
Output: 6
Explanation:
All subarrays contain only 1's.
Example 2:
Input: nums = [1,1,2], k = 1
Output: 3
Explanation:
Subarrays having an AND value of 1 are: [1,1,2], [1,1,2], [1,1,2].
Example 3:
Input: nums = [1,2,3], k = 2
Output: 2
Explanation:
Subarrays having an AND value of 2 are: [1,2,3], [1,2,3].
Constraints:
1 <= nums.length <= 10^50 <= nums[i], k <= 10^9
Solution
Approach: Hash Map of AND Values
Fix the right end r. As the left end moves left, the AND of the subarray can only lose bits, so it takes at most about 30 distinct values (the values are below 230). So for each right end we can keep a map from each distinct AND value to the number of left ends producing it.
Moving to the next element x: AND every key of the old map with x (merging counts of equal results), then add x itself with count 1 for the subarray that starts at the new position. Add the count of key k to the answer.
Complexity: O(n log M) time and O(log M) space, where M is the largest value.
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
ans = 0
pre = Counter()
for x in nums:
cur = Counter()
for y, v in pre.items():
cur[x & y] += v
cur[x] += 1
ans += cur[k]
pre = cur
return ans