Sub topic 2
Prefix sums and why updates break them
This chapter assumes you know zero-based indexing, Big-O notation, and basic loops. Here you will see what a prefix sum array gives you, and where it stops working.
The idea
A prefix sum array p stores running totals of an array a. Entry p[i] is the sum of the first i elements, so p[0] is 0 and p[i + 1] = p[i] + a[i]. The extra leading zero removes special cases at the left edge.
The sum of a[l..r] (inclusive) is then one subtraction: p[r + 1] - p[l]. Everything before l appears in both terms and cancels.
def build_prefix(a):
p = [0] * (len(a) + 1)
for i, x in enumerate(a):
p[i + 1] = p[i] + x
return p
def range_sum(p, l, r):
return p[r + 1] - p[l]
def point_update(p, i, delta):
# a[i] changes by delta, so every total from a[i] onward changes.
for j in range(i + 1, len(p)):
p[j] += delta
a = [5, 2, 7, 1, 3]
p = build_prefix(a)
print(p) # [0, 5, 7, 14, 15, 18]
print(range_sum(p, 1, 3)) # 15 - 5 = 10
point_update(p, 2, 3) # a[2] goes from 7 to 10
print(p) # [0, 5, 7, 17, 18, 21]
print(range_sum(p, 1, 3)) # 18 - 5 = 13Building costs O(n), and each query costs O(1).
Why updates break it
Every p[j] with j > i includes a[i]. Changing one element therefore changes all the entries after it.
In the worst case, an update at index 0 rewrites all n entries. With q operations that mix updates and queries, the total work can reach O(q · n). For n and q around 10^5, that is about 10^10 steps, which is far too slow.
Comparing the two simple approaches
| Approach | Range query | Point update |
|---|---|---|
| Loop over the array | O(n) | O(1) |
| Prefix sum array | O(1) | O(n) |
| Goal for this tutorial | O(log n) | O(log n) |
Each simple approach makes one operation cheap and the other expensive. The data structures in the next chapters accept a small cost on both operations, so neither one becomes a bottleneck.
Common errors
- Leaving out the leading zero, so that
p[l - 1]fails whenlis 0. - Writing
p[r] - p[l]instead ofp[r + 1] - p[l]. This dropsa[r]from the answer. - Updating only
p[i + 1]and leaving later entries stale. - Mixing inclusive and half-open bounds. Here,
landrare both inclusive.
Exercise
An array has n = 100000 elements. You receive 100000 operations, half of them point updates at random positions and half of them range-sum queries. Roughly how many basic steps does the prefix-sum approach take, and which operation causes most of the cost?
Show answer
Each update rewrites about n/2 entries on average, so 50000 updates cost about 50000 × 50000 = 2.5 × 10^9 steps. Queries cost only 50000 steps in total. The updates cause almost all of the cost.