Medium
You are given a 0-indexed integer array nums, an integer modulo, and an integer k.
Your task is to find the count of subarrays that are interesting.
A subarray nums[l..r] is interesting if the following condition holds:
cnt be the number of indices i in the range [l, r] such that nums[i] % modulo == k. Then, cnt % modulo == k.Return an integer denoting the count of interesting subarrays.
Note: A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [3,2,4], modulo = 2, k = 1
Output: 3
Explanation: In this example the interesting subarrays are: The subarray nums[0..0] which is [3].
It can be shown that there are no other interesting subarrays. So, the answer is 3.
Example 2:
Input: nums = [3,1,9,6], modulo = 3, k = 0
Output: 2
Explanation: In this example the interesting subarrays are: The subarray nums[0..3] which is [3,1,9,6].
It can be shown that there are no other interesting subarrays. So, the answer is 2.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1091 <= modulo <= 1090 <= k < moduloimport java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public long countInterestingSubarrays(List<Integer> nums, int modulo, int k) {
int prefixCnt = 0;
Map<Integer, Integer> freq = new HashMap<>();
freq.put(0, 1);
long interestingSubarrays = 0;
for (Integer num : nums) {
if (num % modulo == k) {
prefixCnt++;
}
int expectedPrefix = (prefixCnt - k + modulo) % modulo;
interestingSubarrays += freq.getOrDefault(expectedPrefix, 0);
freq.put(prefixCnt % modulo, freq.getOrDefault(prefixCnt % modulo, 0) + 1);
}
return interestingSubarrays;
}
}