Prefix Sums in Python
Chapter 38: Prefix Sums
6 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Running totals: any range sum in one step
Build prefix, where prefix[k] is the sum of the first k numbers; then the sum of nums[i:j] is prefix[j] - prefix[i].
Prefix sums with a dict: runs that add up to k
A run nums[i:j] adds up to k exactly when prefix[j] - prefix[i] == k, that is, when an earlier running total equals prefix[j] - k; so count, in a dict, how often each running total has appeared.
Prefix sums on a grid
P[r][c] is the sum of the top-left block grid[0:r] × [0:c], with an extra row and column of zeros, and any rectangle's sum comes from four entries of P.
Difference arrays: many range updates at once
To add v to every position in a range [on, off), write +v at diff[on] and -v at diff[off]; after all the updates, the running total of diff gives every position's value.
Fenwick tree: prefix sums that can change
tree[i] holds the sum of a block of positions that ends at i, as long as the lowest set bit of i (i & -i); a prefix sum hops down by removing that bit each time, and an update hops up by adding it.
Segment tree: the best of any range, kept up to date
A segment tree is a binary tree in which every node stores the answer (here the maximum) for one range of the list, split in half at each level, so any range is covered by O(log n) whole nodes and a change touches only the O(log n) nodes above one leaf.