[LeetCode] Count of Interesting Subarrays

2845. Count of Interesting Subarrays

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:

  • Let 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
long long countInterestingSubarrays(vector<int>& nums, int modulo, int k) {
int sum = 0;
long long res = 0;
unordered_map<int, int> freq{{0,1}};
for(int i = 0; i < nums.size(); i++) {
sum = sum + ((nums[i] % modulo) == k);
sum %= modulo;
res += freq[(sum - k + modulo) % modulo];
freq[sum] += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/03/PS/LeetCode/count-of-interesting-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.