Learn
Prefix Sum
Prefix Sum, also known as cumulative sum or running total, preprocesses an array so you can answer range sum queries in time after preprocessing.
You define as the sum of elements from index to . The sum from to is .
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
Prefix Sum, also known as cumulative sum or running total, preprocesses an array so you can answer range sum queries in time after preprocessing.
You define as the sum of elements from index to . The sum from to is .
Apply what you learned by solving the practice problem for Prefix Sum (Range Sum Query).
Go to Practice Problemfunction buildPrefixSum(arr, n):
prefix = array of size n + 1
prefix[0] = 0
for i from 0 to n - 1:
prefix[i + 1] = prefix[i] + arr[i]
return prefix
function rangeSum(prefix, L, R):
return prefix[R + 1] - prefix[L]
Why : This handles the edge case when . The sum from to is just .
2D prefix sum: For a matrix, you use representing the sum of the rectangle from to . You apply inclusion-exclusion for rectangle queries.
When to use what: Use prefix sums when your array is static. Use Segment Trees when you need both queries and updates.
Applications: You use Prefix Sum for range sum queries, subarray sum problems, 2D region queries, and difference arrays for range updates.
Time complexity: preprocessing, per query.
Space complexity: for the prefix array.