1.Prefix sums
A prefix-sum array stores the running total up to each index, built once in O(n). After that, the sum of any range [i, j] is one subtraction, O(1), instead of re-adding that range every time.
Key features
- prefix has length n + 1: prefix[0] = 0, and prefix[k] = sum of the first k elements
- Range sum [i, j] (inclusive) is prefix[j + 1] - prefix[i]
- Building the prefix array is O(n); each range query afterward is O(1)
- itertools.accumulate builds the same running-total array, without the leading 0 — see this section's Python-tools group
- build prefix[] — O(n), once
- prefix[j+1] - prefix[i] — O(1), any range
prefix[k] is the sum of the first k elements — an inclusive range [i, j] is prefix[j + 1] - prefix[i], never prefix[j] - prefix[i].