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 <= 105
1 <= nums[i] <= 109
1 <= modulo <= 109
0 <= k < modulo
class Solution {
fun countInterestingSubarrays(nums: List<Int>, modulo: Int, k: Int): Long {
var prefixCnt = 0
val freq: MutableMap<Int, Int> = HashMap()
freq[0] = 1
var interestingSubarrays: Long = 0
for (num in nums) {
if (num % modulo == k) {
prefixCnt++
}
val expectedPrefix = (prefixCnt - k + modulo) % modulo
interestingSubarrays += freq.getOrDefault(expectedPrefix, 0).toLong()
freq[prefixCnt % modulo] = freq.getOrDefault(prefixCnt % modulo, 0) + 1
}
return interestingSubarrays
}
}