Prefix Sum
Answer thousands of range-sum questions by doing the adding once, up front, instead of once per question.
After this lesson you will be able to
- Explain why re-adding a range for every query is too slow, and what repeated work the prefix array removes.
- Build a prefix array with a leading
0and answer any range sum with a single subtraction. - Extend the idea to rectangles in a grid (2D) and to many range updates at once (the difference array).
- Turn “count subarrays with property X” into “find two prefix values that differ by k” using a dictionary.
- Decide when prefix sums do not apply: changing data, and operations that cannot be undone like max.
Before you start. You should be comfortable with list indexing (the first element is index 0) and looping over a list with .