Prefix Sum
DSA · Beginner
Definition
A prefix sum array stores the running total so any range sum is computed in O(1).
Turns repeated range-sum queries from O(n) each into O(1) each.
Diagram
Flowchart
Example: Range sum query
a = [2, 4, 1, 3]
pre = [0]
for x in a:
pre.append(pre[-1] + x)
print(pre[3] - pre[1])Output: 5
Complexity
Build O(n) · Query O(1)
Key points
- Combine with hash map for subarray-sum-equals-k
- 2D prefix sums work on matrices
Interview questions
Count subarrays with sum k?
Store counts of prefix sums; add count[pre − k] at each step.