Given an array , the prefix sum array is defined by , with . The sum of any range is then — a single subtraction.
Why it's useful
Without prefix sums, range-sum queries on an array of size cost . With them, you pay upfront to build and per query, total . For any query-heavy workload this is a massive speedup.
Beyond sums
The same idea generalizes: prefix XOR, prefix product (with care for zeros), prefix min/max (less useful — you can't "reverse" min). In 2D, the prefix sum over a matrix lets you query the sum of any submatrix in via the inclusion-exclusion formula .
Subarray sum problems
"Count subarrays whose sum equals " — a classic. Iterate through the array maintaining the running prefix sum . At each step, check whether has appeared before (use a hash map of prefix-sum counts). If yes, every previous occurrence is the start of a subarray with sum . time, extra space.
Difference arrays
The dual technique: given many range-update operations and one final read, use a difference array. To add to , mark and . After all updates, compute the prefix sum of to get the final array. Each update is instead of .