What is Prefix Sum

Pattern overview

prefix sum (cumulative sum array) precomputes cumulative sums so any subarray sum can be calculated in O(1)O(1). You use it when answering multiple range sum queries or finding subarrays with target sums. It trades O(n)O(n) preprocessing for O(1)O(1) queries, transforming O(n)O(n) per query to O(1)O(1).

You'll see this in range queries, subarray sums, and matrix problems. If you can explain these concepts in your own words, you'll solve related problems faster under interview pressure.

1770079193353-tmbitu47d9.jpg