Prefix Sums
Precompute running totals once, then answer any range-sum question with one subtraction.
This topic is part of Pro.
Free covers the C and Python courses, the first three DSA topics, the opening system design lessons and the beginner AI lessons, all with the full coach. Pro opens the rest of the library in the FollowtheDamnCode app.
What is in it
- 1Range sums in O(1)Build running totals once; every range sum becomes prefix[r + 1] − prefix[l]. Pro
- 2Prefix sums with a hash mapCount subarrays summing to k — negatives allowed — by looking up earlier prefix sums. Pro
- 3Prefix and suffix passesCombine "everything to my left" with "everything to my right" — product except self, without division. Pro
- 42D prefix sums and difference arraysRectangle sums in a grid with inclusion–exclusion, and range updates in O(1) with a difference array. Pro