### Manik's blog

By Manik, history, 7 weeks ago,

Quite a tricky problem I was stuck on trying to solve. Would appreciate some help on how to approach it.

Given an array, compute the number of subarrays with a mean = k

1 <= n <= 1e5

1 <= a[i], k <= 1e9

Thanks!

• +9

 » 7 weeks ago, # | ← Rev. 2 →   +17 let's say dp store prefix sums. if i
•  » » 7 weeks ago, # ^ |   0 Thank you so much for your tip, it helped me solve the problem! Code for anyone who is curiousfrom bisect import bisect_left from itertools import accumulate a = [2, 2, 0, 4, 2] k = 2 a = [0] + a n = len(a) ans = 0 pf = list(accumulate(a)) locations = defaultdict(list) for j in range(n): locations[pf[j] - j * k].append(j) for i in range(n): ans += bisect_left(locations[pf[i] - i * k], i) print(ans) 
•  » » 7 weeks ago, # ^ |   0 Shouldn't you ask the source of the problem before you tell the approach ?
•  » » » 7 weeks ago, # ^ |   0 That problem is very common, I've seen it several times in different platforms/contests.
 » 7 weeks ago, # | ← Rev. 3 →   0 Let $dp[i]$be total subarrays uptil index $i$with mean $k$. So $dp[i] = dp[i-1] + H[p[i] - ki]$where p are the prefix sums.Lets see how,We want the count of all subarrays that end at index i. This is equivalent to saying, : $\frac{p[i] - p[j -1]}{i-j+1} = k$which is nothing but $p[i] - ki = p[j-1] - k(j-1)$for all $j<=i$we can maintain a map $H$and add the contribution of $p[i]-ki$to the answer.
 » 7 weeks ago, # |   +6 Others have explained the solution pretty well, but I think there's a nicer way to think about it.A neat trick that I only learned about a few days ago is called the 'average trick' (that's what I call it, anyway). If you want a subarray $b$ to have an average of $k$, then the sum of $(b_i - k)$ is $0$. So what you can do is subtract $k$ from every element. Then you only need to check that the sum of $b_i$ is $0$.This is a more common and easier to understand problem. If you store the prefix sums, all you need to do is find the number of pairs with the same sum (because then the latter minus the former will be 0).$\newline$ Implementationmap cnt; long long sum = 0; long long ans = 0; // Max ans is n*(n-1)/2 for (int i = 0; i < n; i++) { sum += (a[i] - k); ans += cnt[sum]++; }  Note: The 'cnt[sum]++' adds the number of previous occurrences of $sum$ to the answer, and then increments the number of occurrences.
•  » » 7 weeks ago, # ^ |   0 Ahh, so when you subtract k from each element, it becomes a very standard problem (number of subarrays which sum to 0). This is incredibly elegant, thank you so much for sharing!!
•  » » 7 weeks ago, # ^ |   +3 This is a super cool trick, thanks for bringing it up!