Prefix Sums
Signal: many range-sum queries, "subarray sum equals k", "balance point", counting subarrays with a property, or products of everything except one element.
Core idea: precompute P[i] = a[0] + … + a[i−1] (with P[0] = 0). Then the sum of any range a[l..r] is P[r+1] − P[l] in O(1).
Prefix sum + hash map
The powerful variant: "count subarrays whose sum is k". A subarray (l, r] sums to k exactly when P[r] − P[l] = k, i.e., P[l] = P[r] − k. Scan once, keeping a map prefix value → how many times seen:
python
from collections import defaultdict
count = defaultdict(int); count[0] = 1 # the empty prefix
p = ans = 0
for x in nums:
p += x
ans += count[p - k] # earlier prefixes that complete a k-sum here
count[p] += 1This works with negative numbers, where sliding windows fail. The same idea generalizes: "equal number of 0s and 1s" (map 0 → −1, then look for sum 0), "sum divisible by k" (store p mod k).