Prefix Sum Applications (Advanced Usage)
Advanced prefix usage goes beyond static arrays: frequency with complements, counting subarrays by sum, 2D/3D accumulators, and offline queries that sweep while maintaining a running prefix map.
Why this shows up in the real world
Fraud monitors track cumulative spend per merchant; anomalies are “sudden jumps” in prefix deltas. Warehouse pick paths prefix travel time along aisles to compare alternate routes. Climate anomaly maps integrate anomalies over regions—rectangular sums via 2D prefix are standard preprocessing.
Core idea (explained for students)
Classic pattern: transform the array (for example replace 0 with -1 in binary balance problems) then ask whether a prefix repeats—equivalently whether some subarray sums to zero. Another pattern: maintain count[pref] in a hash map while scanning to count subarrays with target sum T via current - T lookups.
Try this in Python
from collections import defaultdict
def subarrays_with_sum_zero(a: list[int]) -> int:
pref, cnt, ans = 0, defaultdict(int), 0
cnt[0] = 1
for x in a:
pref += x
ans += cnt[pref]
cnt[pref] += 1
return ans
print(subarrays_with_sum_zero([1, -1, 1, -1]))
Common mistakes
- Losing sight of modular equivalence classes when counting subarrays divisible by k.
- Memory blowups when storing every prefix in huge streams—use bounded structures if applicable.
- Mixing inclusive/exclusive formulas between 1D and 2D templates.
Key takeaways
- Prefix sums are a language for range questions—learn its idioms.
- Draw the timeline of prefix values when debugging counting problems.
- Combine with coordinate compression when values are huge but sparse.
