Prefix Sums & Range Queries
When to use: many queries/updates over ranges of an array — "sum of a[l..r]", "add v to a[l..r]", "how many smaller elements to the right".
| Need | Structure | Query | Update |
|---|---|---|---|
| Static range sums | prefix sums pre[i+1] = pre[i] + a[i] | O(1) | — |
| Many range adds, read at the end | difference array d[l] += v, d[r+1] -= v, prefix-sum once | O(n) total | O(1) |
| Range sums + point updates | Fenwick tree (BIT) | O(log n) | O(log n) |
| Range min/max/sum + range updates | segment tree (lazy propagation) | O(log n) | O(log n) |
| Counting inversions / pairs | merge sort with counting, or BIT over ranks | O(n log n) | — |
class BIT: # Fenwick tree, 1-indexed
def __init__(self, n): self.t = [0] * (n + 1)
def add(self, i, v): # a[i] += v
while i < len(self.t):
self.t[i] += v
i += i & -i # jump to the next node covering i
def sum(self, i): # a[1] + ... + a[i]
s = 0
while i:
s += self.t[i]
i -= i & -i # drop the lowest set bit
return s
difference array: add 10 to [1,3] and 5 to [2,4] on n=6
d: 0 10 5 0 -10 -5 (d[l] += v, d[r+1] -= v)
prefix: 0 10 15 15 5 0 <- final values
Problems
Showing 10 of 10